Debian Codegraph @

src/com/google/javascript/jscomp/DefaultPassConfig.java

raw symbols SCIP
1 /*
2 * Copyright 2009 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Charsets;
21 import com.google.common.base.Preconditions;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Sets;
25 import com.google.common.io.Files;
26 import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
27 import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
28 import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern;
29 import com.google.javascript.jscomp.NodeTraversal.Callback;
30 import com.google.javascript.jscomp.parsing.ParserRunner;
31 import com.google.javascript.rhino.IR;
32 import com.google.javascript.rhino.Node;
33
34 import java.io.File;
35 import java.io.FileReader;
36 import java.io.IOException;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Set;
42
43 /**
44 * Pass factories and meta-data for native JSCompiler passes.
45 *
46 * @author [email protected] (Nick Santos)
47 */
48 // TODO(nicksantos): This needs state for a variety of reasons. Some of it
49 // is to satisfy the existing API. Some of it is because passes really do
50 // need to share state in non-trivial ways. This should be audited and
51 // cleaned up.
52 public class DefaultPassConfig extends PassConfig {
53
54 /* For the --mark-as-compiled pass */
55 private static final String COMPILED_CONSTANT_NAME = "COMPILED";
56
57 /* Constant name for Closure's locale */
58 private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE";
59
60 // Compiler errors when invalid combinations of passes are run.
61 static final DiagnosticType TIGHTEN_TYPES_WITHOUT_TYPE_CHECK =
62 DiagnosticType.error("JSC_TIGHTEN_TYPES_WITHOUT_TYPE_CHECK",
63 "TightenTypes requires type checking. Please use --check_types.");
64
65 static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR =
66 DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR",
67 "Rename prototypes and inline variables cannot be used together");
68
69 // Miscellaneous errors.
70 static final DiagnosticType REPORT_PATH_IO_ERROR =
71 DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR",
72 "Error writing compiler report to {0}");
73
74 private static final DiagnosticType NAME_REF_GRAPH_FILE_ERROR =
75 DiagnosticType.error("JSC_NAME_REF_GRAPH_FILE_ERROR",
76 "Error \"{1}\" writing name reference graph to \"{0}\".");
77
78 private static final DiagnosticType NAME_REF_REPORT_FILE_ERROR =
79 DiagnosticType.error("JSC_NAME_REF_REPORT_FILE_ERROR",
80 "Error \"{1}\" writing name reference report to \"{0}\".");
81
82 private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN =
83 java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$");
84
85 /**
86 * A global namespace to share across checking passes.
87 */
88 private GlobalNamespace namespaceForChecks = null;
89
90 /**
91 * A symbol table for registering references that get removed during
92 * preprocessing.
93 */
94 private PreprocessorSymbolTable preprocessorSymbolTable = null;
95
96 /**
97 * A type-tightener to share across optimization passes.
98 */
99 private TightenTypes tightenTypes = null;
100
101 /** Names exported by goog.exportSymbol. */
102 private Set<String> exportedNames = null;
103
104 /**
105 * Ids for cross-module method stubbing, so that each method has
106 * a unique id.
107 */
108 private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator =
109 new CrossModuleMethodMotion.IdGenerator();
110
111 /**
112 * Keys are arguments passed to getCssName() found during compilation; values
113 * are the number of times the key appeared as an argument to getCssName().
114 */
115 private Map<String, Integer> cssNames = null;
116
117 /** The variable renaming map */
118 private VariableMap variableMap = null;
119
120 /** The property renaming map */
121 private VariableMap propertyMap = null;
122
123 /** The naming map for anonymous functions */
124 private VariableMap anonymousFunctionNameMap = null;
125
126 /** Fully qualified function names and globally unique ids */
127 private FunctionNames functionNames = null;
128
129 /** String replacement map */
130 private VariableMap stringMap = null;
131
132 /** Id generator map */
133 private String idGeneratorMap = null;
134
135 public DefaultPassConfig(CompilerOptions options) {
136 super(options);
137 }
138
139 @Override
140 protected State getIntermediateState() {
141 return new State(
142 cssNames == null ? null : Maps.newHashMap(cssNames),
143 exportedNames == null ? null :
144 Collections.unmodifiableSet(exportedNames),
145 crossModuleIdGenerator, variableMap, propertyMap,
146 anonymousFunctionNameMap, stringMap, functionNames, idGeneratorMap);
147 }
148
149 @Override
150 protected void setIntermediateState(State state) {
151 this.cssNames = state.cssNames == null ? null :
152 Maps.newHashMap(state.cssNames);
153 this.exportedNames = state.exportedNames == null ? null :
154 Sets.newHashSet(state.exportedNames);
155 this.crossModuleIdGenerator = state.crossModuleIdGenerator;
156 this.variableMap = state.variableMap;
157 this.propertyMap = state.propertyMap;
158 this.anonymousFunctionNameMap = state.anonymousFunctionNameMap;
159 this.stringMap = state.stringMap;
160 this.functionNames = state.functionNames;
161 this.idGeneratorMap = state.idGeneratorMap;
162 }
163
164 GlobalNamespace getGlobalNamespace() {
165 return namespaceForChecks;
166 }
167
168 PreprocessorSymbolTable getPreprocessorSymbolTable() {
169 return preprocessorSymbolTable;
170 }
171
172 void maybeInitializePreprocessorSymbolTable(AbstractCompiler compiler) {
173 if (options.ideMode) {
174 Node root = compiler.getRoot();
175 if (preprocessorSymbolTable == null ||
176 preprocessorSymbolTable.getRootNode() != root) {
177 preprocessorSymbolTable = new PreprocessorSymbolTable(root);
178 }
179 }
180 }
181
182 @Override
183 protected List<PassFactory> getChecks() {
184 List<PassFactory> checks = Lists.newArrayList();
185
186 checks.add(createEmptyPass("beforeStandardChecks"));
187
188 if (options.closurePass) {
189 checks.add(closureGoogScopeAliases);
190 checks.add(closureRewriteGoogClass);
191 }
192
193 if (options.nameAnonymousFunctionsOnly) {
194 if (options.anonymousFunctionNaming ==
195 AnonymousFunctionNamingPolicy.MAPPED) {
196 checks.add(nameMappedAnonymousFunctions);
197 } else if (options.anonymousFunctionNaming ==
198 AnonymousFunctionNamingPolicy.UNMAPPED) {
199 checks.add(nameUnmappedAnonymousFunctions);
200 }
201 return checks;
202 }
203
204 if (options.jqueryPass) {
205 checks.add(jqueryAliases);
206 }
207
208 if (options.angularPass) {
209 checks.add(angularPass);
210 }
211
212 checks.add(checkSideEffects);
213
214 if (options.checkSuspiciousCode ||
215 options.enables(DiagnosticGroups.GLOBAL_THIS) ||
216 options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
217 checks.add(suspiciousCode);
218 }
219
220 if (options.checkControlStructures
221 || options.enables(DiagnosticGroups.ES5_STRICT)) {
222 checks.add(checkControlStructures);
223 }
224
225 if (options.checkRequires.isOn()) {
226 checks.add(checkRequires);
227 }
228
229 if (options.checkProvides.isOn()) {
230 checks.add(checkProvides);
231 }
232
233 // The following passes are more like "preprocessor" passes.
234 // It's important that they run before most checking passes.
235 // Perhaps this method should be renamed?
236 if (options.generateExports) {
237 checks.add(generateExports);
238 }
239
240 if (options.exportTestFunctions) {
241 checks.add(exportTestFunctions);
242 }
243
244 if (options.closurePass) {
245 checks.add(closurePrimitives);
246 }
247
248 if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) {
249 checks.add(closureCheckGetCssName);
250 }
251
252 if (options.syntheticBlockStartMarker != null) {
253 // This pass must run before the first fold constants pass.
254 checks.add(createSyntheticBlocks);
255 }
256
257 checks.add(checkVars);
258 if (options.computeFunctionSideEffects) {
259 checks.add(checkRegExp);
260 }
261
262 if (options.aggressiveVarCheck.isOn()) {
263 checks.add(checkVariableReferences);
264 }
265
266 // This pass should run before types are assigned.
267 if (options.processObjectPropertyString) {
268 checks.add(objectPropertyStringPreprocess);
269 }
270
271 if (options.checkTypes || options.inferTypes) {
272 checks.add(resolveTypes);
273 checks.add(inferTypes);
274 if (options.checkTypes) {
275 checks.add(checkTypes);
276 } else {
277 checks.add(inferJsDocInfo);
278 }
279
280 // We assume that only IDE-mode clients will try to query the
281 // typed scope creator after the compile job.
282 if (!options.ideMode && !options.saveDataStructures) {
283 checks.add(clearTypedScopePass);
284 }
285 }
286
287 if (options.checkUnreachableCode.isOn() ||
288 (options.checkTypes && options.checkMissingReturn.isOn())) {
289 checks.add(checkControlFlow);
290 }
291
292 // CheckAccessControls only works if check types is on.
293 if (options.checkTypes &&
294 (options.enables(DiagnosticGroups.ACCESS_CONTROLS)
295 || options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) {
296 checks.add(checkAccessControls);
297 }
298
299 if (options.checkGlobalNamesLevel.isOn()) {
300 checks.add(checkGlobalNames);
301 }
302
303 if (options.enables(DiagnosticGroups.ES5_STRICT) || options.checkCaja) {
304 checks.add(checkStrictMode);
305 }
306
307 // Replace 'goog.getCssName' before processing defines but after the
308 // other checks have been done.
309 if (options.closurePass) {
310 checks.add(closureReplaceGetCssName);
311 }
312
313 // i18n
314 // If you want to customize the compiler to use a different i18n pass,
315 // you can create a PassConfig that calls replacePassFactory
316 // to replace this.
317 if (options.replaceMessagesWithChromeI18n) {
318 checks.add(replaceMessagesForChrome);
319 } else if (options.messageBundle != null) {
320 checks.add(replaceMessages);
321 }
322
323 if (options.getTweakProcessing().isOn()) {
324 checks.add(processTweaks);
325 }
326
327 // Defines in code always need to be processed.
328 checks.add(processDefines);
329
330 if (options.instrumentationTemplate != null ||
331 options.recordFunctionInformation) {
332 checks.add(computeFunctionNames);
333 }
334
335 if (options.nameReferenceGraphPath != null &&
336 !options.nameReferenceGraphPath.isEmpty()) {
337 checks.add(printNameReferenceGraph);
338 }
339
340 if (options.nameReferenceReportPath != null &&
341 !options.nameReferenceReportPath.isEmpty()) {
342 checks.add(printNameReferenceReport);
343 }
344
345 checks.add(createEmptyPass("afterStandardChecks"));
346
347 assertAllOneTimePasses(checks);
348 return checks;
349 }
350
351 @Override
352 protected List<PassFactory> getOptimizations() {
353 List<PassFactory> passes = Lists.newArrayList();
354 passes.add(garbageCollectChecks);
355
356 // TODO(nicksantos): The order of these passes makes no sense, and needs
357 // to be re-arranged.
358
359 if (options.runtimeTypeCheck) {
360 passes.add(runtimeTypeCheck);
361 }
362
363 passes.add(createEmptyPass("beforeStandardOptimizations"));
364
365 if (options.replaceIdGenerators) {
366 passes.add(replaceIdGenerators);
367 }
368
369 // Optimizes references to the arguments variable.
370 if (options.optimizeArgumentsArray) {
371 passes.add(optimizeArgumentsArray);
372 }
373
374 // Abstract method removal works best on minimally modified code, and also
375 // only needs to run once.
376 if (options.closurePass &&
377 (options.removeAbstractMethods || options.removeClosureAsserts)) {
378 passes.add(closureCodeRemoval);
379 }
380
381 // Collapsing properties can undo constant inlining, so we do this before
382 // the main optimization loop.
383 if (options.collapseProperties) {
384 passes.add(collapseProperties);
385 }
386
387 // ReplaceStrings runs after CollapseProperties in order to simplify
388 // pulling in values of constants defined in enums structures.
389 if (!options.replaceStringsFunctionDescriptions.isEmpty()) {
390 passes.add(replaceStrings);
391 }
392
393 // Tighten types based on actual usage.
394 if (options.tightenTypes) {
395 passes.add(tightenTypesBuilder);
396 }
397
398 // Property disambiguation should only run once and needs to be done
399 // soon after type checking, both so that it can make use of type
400 // information and so that other passes can take advantage of the renamed
401 // properties.
402 if (options.disambiguateProperties) {
403 passes.add(disambiguateProperties);
404 }
405
406 if (options.computeFunctionSideEffects) {
407 passes.add(markPureFunctions);
408 } else if (options.markNoSideEffectCalls) {
409 // TODO(user) The properties that this pass adds to CALL and NEW
410 // AST nodes increase the AST's in-memory size. Given that we are
411 // already running close to our memory limits, we could run into
412 // trouble if we end up using the @nosideeffects annotation a lot
413 // or compute @nosideeffects annotations by looking at function
414 // bodies. It should be easy to propagate @nosideeffects
415 // annotations as part of passes that depend on this property and
416 // store the result outside the AST (which would allow garbage
417 // collection once the pass is done).
418 passes.add(markNoSideEffectCalls);
419 }
420
421 if (options.chainCalls) {
422 passes.add(chainCalls);
423 }
424
425 // Constant checking must be done after property collapsing because
426 // property collapsing can introduce new constants (e.g. enum values).
427 // TODO(johnlenz): make checkConsts namespace aware so it can be run
428 // as during the checks phase.
429 passes.add(checkConsts);
430
431 // The Caja library adds properties to Object.prototype, which breaks
432 // most for-in loops. This adds a check to each loop that skips
433 // any property matching /___$/.
434 if (options.ignoreCajaProperties) {
435 passes.add(ignoreCajaProperties);
436 }
437
438 assertAllOneTimePasses(passes);
439
440 if (options.smartNameRemoval || options.reportPath != null) {
441 passes.addAll(getCodeRemovingPasses());
442 passes.add(smartNamePass);
443 }
444
445 // This needs to come after the inline constants pass, which is run within
446 // the code removing passes.
447 if (options.closurePass) {
448 passes.add(closureOptimizePrimitives);
449 }
450
451 // TODO(user): This forces a first crack at crossModuleCodeMotion
452 // before devirtualization. Once certain functions are devirtualized,
453 // it confuses crossModuleCodeMotion ability to recognized that
454 // it is recursive.
455
456 // TODO(user): This is meant for a temporary quick win.
457 // In the future, we might want to improve our analysis in
458 // CrossModuleCodeMotion so we don't need to do this.
459 if (options.crossModuleCodeMotion) {
460 passes.add(crossModuleCodeMotion);
461 }
462
463 // Method devirtualization benefits from property disambiguation so
464 // it should run after that pass but before passes that do
465 // optimizations based on global names (like cross module code motion
466 // and inline functions). Smart Name Removal does better if run before
467 // this pass.
468 if (options.devirtualizePrototypeMethods) {
469 passes.add(devirtualizePrototypeMethods);
470 }
471
472 if (options.customPasses != null) {
473 passes.add(getCustomPasses(
474 CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
475 }
476
477 passes.add(createEmptyPass("beforeMainOptimizations"));
478
479 passes.addAll(getMainOptimizationLoop());
480
481 if (options.specializeInitialModule) {
482 // When specializing the initial module, we want our fixups to be
483 // as lean as possible, so we run the entire optimization loop to a
484 // fixed point before specializing, then specialize, and then run the
485 // main optimization loop again.
486
487 if (options.crossModuleCodeMotion) {
488 passes.add(crossModuleCodeMotion);
489 }
490
491 if (options.crossModuleMethodMotion) {
492 passes.add(crossModuleMethodMotion);
493 }
494
495 passes.add(specializeInitialModule);
496 passes.addAll(getMainOptimizationLoop());
497 }
498
499 passes.add(createEmptyPass("beforeModuleMotion"));
500
501 if (options.crossModuleCodeMotion) {
502 passes.add(crossModuleCodeMotion);
503 }
504
505 if (options.crossModuleMethodMotion) {
506 passes.add(crossModuleMethodMotion);
507 }
508
509 passes.add(createEmptyPass("afterModuleMotion"));
510
511 // Some optimizations belong outside the loop because running them more
512 // than once would either have no benefit or be incorrect.
513 if (options.customPasses != null) {
514 passes.add(getCustomPasses(
515 CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
516 }
517
518 if (options.flowSensitiveInlineVariables) {
519 passes.add(flowSensitiveInlineVariables);
520
521 // After inlining some of the variable uses, some variables are unused.
522 // Re-run remove unused vars to clean it up.
523 if (options.removeUnusedVars || options.removeUnusedLocalVars) {
524 passes.add(removeUnusedVars);
525 }
526 }
527
528 // Running this pass again is required to have goog.events compile down to
529 // nothing when compiled on its own.
530 if (options.smartNameRemoval) {
531 passes.add(smartNamePass2);
532 }
533
534 if (options.collapseAnonymousFunctions) {
535 passes.add(collapseAnonymousFunctions);
536 }
537
538 // Move functions before extracting prototype member declarations.
539 if (options.moveFunctionDeclarations ||
540 // renamePrefixNamescape relies on moveFunctionDeclarations
541 // to preserve semantics.
542 options.renamePrefixNamespace != null) {
543 passes.add(moveFunctionDeclarations);
544 }
545
546 if (options.anonymousFunctionNaming ==
547 AnonymousFunctionNamingPolicy.MAPPED) {
548 passes.add(nameMappedAnonymousFunctions);
549 }
550
551 // The mapped name anonymous function pass makes use of information that
552 // the extract prototype member declarations pass removes so the former
553 // happens before the latter.
554 //
555 // Extracting prototype properties screws up the heuristic renaming
556 // policies, so never run it when those policies are requested.
557 if (options.extractPrototypeMemberDeclarations &&
558 (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC &&
559 options.propertyRenaming !=
560 PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) {
561 passes.add(extractPrototypeMemberDeclarations);
562 }
563
564 if (options.ambiguateProperties &&
565 (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) {
566 passes.add(ambiguateProperties);
567 }
568
569 if (options.propertyRenaming != PropertyRenamingPolicy.OFF) {
570 passes.add(renameProperties);
571 }
572
573 // Reserve global names added to the "windows" object.
574 if (options.reserveRawExports) {
575 passes.add(gatherRawExports);
576 }
577
578 // This comes after property renaming because quoted property names must
579 // not be renamed.
580 if (options.convertToDottedProperties) {
581 passes.add(convertToDottedProperties);
582 }
583
584 // Property renaming must happen before this pass runs since this
585 // pass may convert dotted properties into quoted properties. It
586 // is beneficial to run before alias strings, alias keywords and
587 // variable renaming.
588 if (options.rewriteFunctionExpressions) {
589 passes.add(rewriteFunctionExpressions);
590 }
591
592 // This comes after converting quoted property accesses to dotted property
593 // accesses in order to avoid aliasing property names.
594 if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
595 passes.add(aliasStrings);
596 }
597
598 if (options.aliasExternals) {
599 passes.add(aliasExternals);
600 }
601
602 if (options.aliasKeywords) {
603 passes.add(aliasKeywords);
604 }
605
606 // Passes after this point can no longer depend on normalized AST
607 // assumptions.
608 passes.add(markUnnormalized);
609
610 if (options.coalesceVariableNames) {
611 passes.add(coalesceVariableNames);
612
613 // coalesceVariables creates identity assignments and more redundant code
614 // that can be removed, rerun the peephole optimizations to clean them
615 // up.
616 if (options.foldConstants) {
617 passes.add(peepholeOptimizations);
618 }
619 }
620
621 if (options.collapseVariableDeclarations) {
622 passes.add(exploitAssign);
623 passes.add(collapseVariableDeclarations);
624 }
625
626 // This pass works best after collapseVariableDeclarations.
627 passes.add(denormalize);
628
629 if (options.instrumentationTemplate != null) {
630 passes.add(instrumentFunctions);
631 }
632
633 if (options.variableRenaming != VariableRenamingPolicy.ALL) {
634 // If we're leaving some (or all) variables with their old names,
635 // then we need to undo any of the markers we added for distinguishing
636 // local variables ("$$1").
637 passes.add(invertContextualRenaming);
638 }
639
640 if (options.variableRenaming != VariableRenamingPolicy.OFF) {
641 passes.add(renameVars);
642 }
643
644 if (options.groupVariableDeclarations) {
645 passes.add(groupVariableDeclarations);
646 }
647
648 // This pass should run after names stop changing.
649 if (options.processObjectPropertyString) {
650 passes.add(objectPropertyStringPostprocess);
651 }
652
653 if (options.labelRenaming) {
654 passes.add(renameLabels);
655 }
656
657 if (options.foldConstants) {
658 passes.add(latePeepholeOptimizations);
659 }
660
661 if (options.anonymousFunctionNaming ==
662 AnonymousFunctionNamingPolicy.UNMAPPED) {
663 passes.add(nameUnmappedAnonymousFunctions);
664 }
665
666 passes.add(stripSideEffectProtection);
667
668 if (options.renamePrefixNamespace != null) {
669 if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(
670 options.renamePrefixNamespace).matches()) {
671 throw new IllegalArgumentException(
672 "Illegal character in renamePrefixNamespace name: "
673 + options.renamePrefixNamespace);
674 }
675 passes.add(rescopeGlobalSymbols);
676 }
677
678 // Safety checks
679 passes.add(sanityCheckAst);
680 passes.add(sanityCheckVars);
681
682 return passes;
683 }
684
685 /** Creates the passes for the main optimization loop. */
686 private List<PassFactory> getMainOptimizationLoop() {
687 List<PassFactory> passes = Lists.newArrayList();
688 if (options.inlineGetters) {
689 passes.add(inlineSimpleMethods);
690 }
691
692 passes.addAll(getCodeRemovingPasses());
693
694 if (options.inlineFunctions || options.inlineLocalFunctions) {
695 passes.add(inlineFunctions);
696 }
697
698 if (options.inlineProperties) {
699 passes.add(inlineProperties);
700 }
701
702 boolean runOptimizeCalls = options.optimizeCalls
703 || options.optimizeParameters
704 || options.optimizeReturns;
705
706 if (options.removeUnusedVars || options.removeUnusedLocalVars) {
707 if (options.deadAssignmentElimination) {
708 passes.add(deadAssignmentsElimination);
709 }
710 if (!runOptimizeCalls) {
711 passes.add(removeUnusedVars);
712 }
713 }
714 if (runOptimizeCalls) {
715 passes.add(optimizeCallsAndRemoveUnusedVars);
716 }
717 assertAllLoopablePasses(passes);
718 return passes;
719 }
720
721 /** Creates several passes aimed at removing code. */
722 private List<PassFactory> getCodeRemovingPasses() {
723 List<PassFactory> passes = Lists.newArrayList();
724 if (options.collapseObjectLiterals && !isInliningForbidden()) {
725 passes.add(collapseObjectLiterals);
726 }
727
728 if (options.inlineVariables || options.inlineLocalVariables) {
729 passes.add(inlineVariables);
730 } else if (options.inlineConstantVars) {
731 passes.add(inlineConstants);
732 }
733
734 if (options.foldConstants) {
735 // These used to be one pass.
736 passes.add(minimizeExitPoints);
737 passes.add(peepholeOptimizations);
738 }
739
740 if (options.removeDeadCode) {
741 passes.add(removeUnreachableCode);
742 }
743
744 if (options.removeUnusedPrototypeProperties) {
745 passes.add(removeUnusedPrototypeProperties);
746 }
747
748 if (options.removeUnusedClassProperties && !isInliningForbidden()) {
749 passes.add(removeUnusedClassProperties);
750 }
751
752 assertAllLoopablePasses(passes);
753 return passes;
754 }
755
756 /**
757 * Checks for code that is probably wrong (such as stray expressions).
758 */
759 final HotSwapPassFactory checkSideEffects =
760 new HotSwapPassFactory("checkSideEffects", true) {
761 @Override
762 protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
763 // The current approach to protecting "hidden" side-effects is to
764 // wrap them in a function call that is stripped later, this shouldn't
765 // be done in IDE mode where AST changes may be unexpected.
766 boolean protectHiddenSideEffects =
767 options.protectHiddenSideEffects && !options.ideMode;
768 return new CheckSideEffects(compiler,
769 options.checkSuspiciousCode ? CheckLevel.WARNING : CheckLevel.OFF,
770 protectHiddenSideEffects);
771 }
772 };
773
774 /**
775 * Checks for code that is probably wrong (such as stray expressions).
776 */
777 final PassFactory stripSideEffectProtection =
778 new PassFactory("stripSideEffectProtection", true) {
779 @Override
780 protected CompilerPass create(final AbstractCompiler
781 compiler) {
782 return new CheckSideEffects.StripProtection(compiler);
783 }
784 };
785
786 /**
787 * Checks for code that is probably wrong (such as stray expressions).
788 */
789 final HotSwapPassFactory suspiciousCode =
790 new HotSwapPassFactory("suspiciousCode", true) {
791 @Override
792 protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
793 List<Callback> sharedCallbacks = Lists.newArrayList();
794 if (options.checkSuspiciousCode) {
795 sharedCallbacks.add(new CheckSuspiciousCode());
796 }
797
798 if (options.enables(DiagnosticGroups.GLOBAL_THIS)) {
799 sharedCallbacks.add(new CheckGlobalThis(compiler));
800 }
801
802 if (options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
803 sharedCallbacks.add(new CheckDebuggerStatement(compiler));
804 }
805
806 return combineChecks(compiler, sharedCallbacks);
807 }
808
809 };
810
811 /** Verify that all the passes are one-time passes. */
812 private void assertAllOneTimePasses(List<PassFactory> passes) {
813 for (PassFactory pass : passes) {
814 Preconditions.checkState(pass.isOneTimePass());
815 }
816 }
817
818 /** Verify that all the passes are multi-run passes. */
819 private void assertAllLoopablePasses(List<PassFactory> passes) {
820 for (PassFactory pass : passes) {
821 Preconditions.checkState(!pass.isOneTimePass());
822 }
823 }
824
825 /** Checks for validity of the control structures. */
826 final HotSwapPassFactory checkControlStructures =
827 new HotSwapPassFactory("checkControlStructures", true) {
828 @Override
829 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
830 return new ControlStructureCheck(compiler);
831 }
832 };
833
834 /** Checks that all constructed classes are goog.require()d. */
835 final HotSwapPassFactory checkRequires =
836 new HotSwapPassFactory("checkRequires", true) {
837 @Override
838 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
839 return new CheckRequiresForConstructors(compiler, options.checkRequires);
840 }
841 };
842
843 /** Makes sure @constructor is paired with goog.provides(). */
844 final HotSwapPassFactory checkProvides =
845 new HotSwapPassFactory("checkProvides", true) {
846 @Override
847 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
848 return new CheckProvides(compiler, options.checkProvides);
849 }
850 };
851
852 private static final DiagnosticType GENERATE_EXPORTS_ERROR =
853 DiagnosticType.error(
854 "JSC_GENERATE_EXPORTS_ERROR",
855 "Exports can only be generated if export symbol/property " +
856 "functions are set.");
857
858 /** Generates exports for @export annotations. */
859 final PassFactory generateExports = new PassFactory("generateExports", true) {
860 @Override
861 protected CompilerPass create(AbstractCompiler compiler) {
862 CodingConvention convention = compiler.getCodingConvention();
863 if (convention.getExportSymbolFunction() != null &&
864 convention.getExportPropertyFunction() != null) {
865 return new GenerateExports(compiler,
866 convention.getExportSymbolFunction(),
867 convention.getExportPropertyFunction());
868 } else {
869 return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
870 }
871 }
872 };
873
874 /** Generates exports for functions associated with JsUnit. */
875 final PassFactory exportTestFunctions =
876 new PassFactory("exportTestFunctions", true) {
877 @Override
878 protected CompilerPass create(AbstractCompiler compiler) {
879 CodingConvention convention = compiler.getCodingConvention();
880 if (convention.getExportSymbolFunction() != null) {
881 return new ExportTestFunctions(compiler,
882 convention.getExportSymbolFunction(),
883 convention.getExportPropertyFunction());
884 } else {
885 return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
886 }
887 }
888 };
889
890 /** Raw exports processing pass. */
891 final PassFactory gatherRawExports =
892 new PassFactory("gatherRawExports", true) {
893 @Override
894 protected CompilerPass create(AbstractCompiler compiler) {
895 final GatherRawExports pass = new GatherRawExports(
896 compiler);
897
898 return new CompilerPass() {
899 @Override
900 public void process(Node externs, Node root) {
901 pass.process(externs, root);
902 if (exportedNames == null) {
903 exportedNames = Sets.newHashSet();
904 }
905 exportedNames.addAll(pass.getExportedVariableNames());
906 }
907 };
908 }
909 };
910
911 /** Closure pre-processing pass. */
912 @SuppressWarnings("deprecation")
913 final HotSwapPassFactory closurePrimitives =
914 new HotSwapPassFactory("closurePrimitives", true) {
915 @Override
916 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
917 maybeInitializePreprocessorSymbolTable(compiler);
918 final ProcessClosurePrimitives pass = new ProcessClosurePrimitives(
919 compiler,
920 preprocessorSymbolTable,
921 options.brokenClosureRequiresLevel);
922
923 return new HotSwapCompilerPass() {
924 @Override
925 public void process(Node externs, Node root) {
926 pass.process(externs, root);
927 exportedNames = pass.getExportedVariableNames();
928 }
929 @Override
930 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
931 pass.hotSwapScript(scriptRoot, originalRoot);
932 }
933 };
934 }
935 };
936
937 /** Expand jQuery Primitives and Aliases pass. */
938 final PassFactory jqueryAliases = new PassFactory("jqueryAliases", true) {
939 @Override
940 protected CompilerPass create(AbstractCompiler compiler) {
941 return new ExpandJqueryAliases(compiler);
942 }
943 };
944
945 /** Process AngularJS-specific annotations. */
946 final PassFactory angularPass =
947 new PassFactory("angularPass", true) {
948 @Override
949 protected CompilerPass create(AbstractCompiler compiler) {
950 return new AngularPass(compiler);
951 }
952 };
953
954 /**
955 * The default i18n pass.
956 * A lot of the options are not configurable, because ReplaceMessages
957 * has a lot of legacy logic.
958 */
959 final PassFactory replaceMessages = new PassFactory("replaceMessages", true) {
960 @Override
961 protected CompilerPass create(final AbstractCompiler compiler) {
962 return new ReplaceMessages(compiler,
963 options.messageBundle,
964 /* warn about message dupes */
965 true,
966 /* allow messages with goog.getMsg */
967 JsMessage.Style.getFromParams(true, false),
968 /* if we can't find a translation, don't worry about it. */
969 false);
970 }
971 };
972
973 final PassFactory replaceMessagesForChrome =
974 new PassFactory("replaceMessages", true) {
975 @Override
976 protected CompilerPass create(final AbstractCompiler compiler) {
977 return new ReplaceMessagesForChrome(compiler,
978 new GoogleJsMessageIdGenerator(options.tcProjectId),
979 /* warn about message dupes */
980 true,
981 /* allow messages with goog.getMsg */
982 JsMessage.Style.getFromParams(true, false));
983 }
984 };
985
986 /** Applies aliases and inlines goog.scope. */
987 final HotSwapPassFactory closureGoogScopeAliases =
988 new HotSwapPassFactory("closureGoogScopeAliases", true) {
989 @Override
990 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
991 maybeInitializePreprocessorSymbolTable(compiler);
992 return new ScopedAliases(
993 compiler,
994 preprocessorSymbolTable,
995 options.getAliasTransformationHandler());
996 }
997 };
998
999 /** Rewrites goog.class */
1000 final HotSwapPassFactory closureRewriteGoogClass =
1001 new HotSwapPassFactory("closureRewriteGoogClass", true) {
1002 @Override
1003 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
1004 return new ClosureRewriteClass(compiler);
1005 }
1006 };
1007
1008 /** Checks that CSS class names are wrapped in goog.getCssName */
1009 final PassFactory closureCheckGetCssName =
1010 new PassFactory("closureCheckGetCssName", true) {
1011 @Override
1012 protected CompilerPass create(AbstractCompiler compiler) {
1013 String blacklist = options.checkMissingGetCssNameBlacklist;
1014 Preconditions.checkState(blacklist != null && !blacklist.isEmpty(),
1015 "Not checking use of goog.getCssName because of empty blacklist.");
1016 return new CheckMissingGetCssName(
1017 compiler, options.checkMissingGetCssNameLevel, blacklist);
1018 }
1019 };
1020
1021 /**
1022 * Processes goog.getCssName. The cssRenamingMap is used to lookup
1023 * replacement values for the classnames. If null, the raw class names are
1024 * inlined.
1025 */
1026 final PassFactory closureReplaceGetCssName =
1027 new PassFactory("closureReplaceGetCssName", true) {
1028 @Override
1029 protected CompilerPass create(final AbstractCompiler compiler) {
1030 return new CompilerPass() {
1031 @Override
1032 public void process(Node externs, Node jsRoot) {
1033 Map<String, Integer> newCssNames = null;
1034 if (options.gatherCssNames) {
1035 newCssNames = Maps.newHashMap();
1036 }
1037 ReplaceCssNames pass = new ReplaceCssNames(
1038 compiler,
1039 newCssNames,
1040 options.cssRenamingWhitelist);
1041 pass.process(externs, jsRoot);
1042 cssNames = newCssNames;
1043 }
1044 };
1045 }
1046 };
1047
1048 /**
1049 * Creates synthetic blocks to prevent FoldConstants from moving code
1050 * past markers in the source.
1051 */
1052 final PassFactory createSyntheticBlocks =
1053 new PassFactory("createSyntheticBlocks", true) {
1054 @Override
1055 protected CompilerPass create(AbstractCompiler compiler) {
1056 return new CreateSyntheticBlocks(compiler,
1057 options.syntheticBlockStartMarker,
1058 options.syntheticBlockEndMarker);
1059 }
1060 };
1061
1062 /** Various peephole optimizations. */
1063 final PassFactory peepholeOptimizations =
1064 new PassFactory("peepholeOptimizations", false) {
1065 @Override
1066 protected CompilerPass create(AbstractCompiler compiler) {
1067 final boolean late = false;
1068 return new PeepholeOptimizationsPass(compiler,
1069 new PeepholeSubstituteAlternateSyntax(late),
1070 new PeepholeReplaceKnownMethods(late),
1071 new PeepholeRemoveDeadCode(),
1072 new PeepholeFoldConstants(late),
1073 new PeepholeCollectPropertyAssignments());
1074 }
1075 };
1076
1077 /** Same as peepholeOptimizations but aggressively merges code together */
1078 final PassFactory latePeepholeOptimizations =
1079 new PassFactory("latePeepholeOptimizations", true) {
1080 @Override
1081 protected CompilerPass create(AbstractCompiler compiler) {
1082 final boolean late = true;
1083 return new PeepholeOptimizationsPass(compiler,
1084 new StatementFusion(),
1085 new PeepholeRemoveDeadCode(),
1086 new PeepholeSubstituteAlternateSyntax(late),
1087 new PeepholeReplaceKnownMethods(late),
1088 new PeepholeFoldConstants(late),
1089 new ReorderConstantExpression());
1090 }
1091 };
1092
1093 /** Checks that all variables are defined. */
1094 final HotSwapPassFactory checkVars =
1095 new HotSwapPassFactory("checkVars", true) {
1096 @Override
1097 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
1098 return new VarCheck(compiler);
1099 }
1100 };
1101
1102 /** Checks for RegExp references. */
1103 final PassFactory checkRegExp =
1104 new PassFactory("checkRegExp", true) {
1105 @Override
1106 protected CompilerPass create(final AbstractCompiler compiler) {
1107 final CheckRegExp pass = new CheckRegExp(compiler);
1108
1109 return new CompilerPass() {
1110 @Override
1111 public void process(Node externs, Node root) {
1112 pass.process(externs, root);
1113 compiler.setHasRegExpGlobalReferences(
1114 pass.isGlobalRegExpPropertiesUsed());
1115 }
1116 };
1117 }
1118 };
1119
1120 /** Checks that references to variables look reasonable. */
1121 final HotSwapPassFactory checkVariableReferences =
1122 new HotSwapPassFactory("checkVariableReferences", true) {
1123 @Override
1124 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
1125 return new VariableReferenceCheck(
1126 compiler, options.aggressiveVarCheck);
1127 }
1128 };
1129
1130 /** Pre-process goog.testing.ObjectPropertyString. */
1131 final PassFactory objectPropertyStringPreprocess =
1132 new PassFactory("ObjectPropertyStringPreprocess", true) {
1133 @Override
1134 protected CompilerPass create(AbstractCompiler compiler) {
1135 return new ObjectPropertyStringPreprocess(compiler);
1136 }
1137 };
1138
1139 /** Creates a typed scope and adds types to the type registry. */
1140 final HotSwapPassFactory resolveTypes =
1141 new HotSwapPassFactory("resolveTypes", true) {
1142 @Override
1143 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
1144 return new GlobalTypeResolver(compiler);
1145 }
1146 };
1147
1148 /** Clears the typed scope when we're done. */
1149 final PassFactory clearTypedScopePass =
1150 new PassFactory("clearTypedScopePass", true) {
1151 @Override
1152 protected CompilerPass create(AbstractCompiler compiler) {
1153 return new ClearTypedScope();
1154 }
1155 };
1156
1157 /** Runs type inference. */
1158 final HotSwapPassFactory inferTypes =
1159 new HotSwapPassFactory("inferTypes", true) {
1160 @Override
1161 protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
1162 return new HotSwapCompilerPass() {
1163 @Override
1164 public void process(Node externs, Node root) {
1165 Preconditions.checkNotNull(topScope);
1166 Preconditions.checkNotNull(getTypedScopeCreator());
1167
1168 makeTypeInference(compiler).process(externs, root);
1169 }
1170 @Override
1171 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
1172 makeTypeInference(compiler).inferAllScopes(scriptRoot);
1173 }
1174 };
1175 }
1176 };
1177
1178 final HotSwapPassFactory inferJsDocInfo =
1179 new HotSwapPassFactory("inferJsDocInfo", true) {
1180 @Override
1181 protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
1182 return new HotSwapCompilerPass() {
1183 @Override
1184 public void process(Node externs, Node root) {
1185 Preconditions.checkNotNull(topScope);
1186 Preconditions.checkNotNull(getTypedScopeCreator());
1187
1188 makeInferJsDocInfo(compiler).process(externs, root);
1189 }
1190 @Override
1191 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
1192 makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot, originalRoot);
1193 }
1194 };
1195 }
1196 };
1197
1198 /** Checks type usage */
1199 final HotSwapPassFactory checkTypes =
1200 new HotSwapPassFactory("checkTypes", true) {
1201 @Override
1202 protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
1203 return new HotSwapCompilerPass() {
1204 @Override
1205 public void process(Node externs, Node root) {
1206 Preconditions.checkNotNull(topScope);
1207 Preconditions.checkNotNull(getTypedScopeCreator());
1208
1209 TypeCheck check = makeTypeCheck(compiler);
1210 check.process(externs, root);
1211 compiler.getErrorManager().setTypedPercent(check.getTypedPercent());
1212 }
1213 @Override
1214 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
1215 makeTypeCheck(compiler).check(scriptRoot, false);
1216 }
1217 };
1218 }
1219 };
1220
1221 /**
1222 * Checks possible execution paths of the program for problems: missing return
1223 * statements and dead code.
1224 */
1225 final HotSwapPassFactory checkControlFlow =
1226 new HotSwapPassFactory("checkControlFlow", true) {
1227 @Override
1228 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
1229 List<Callback> callbacks = Lists.newArrayList();
1230 if (options.checkUnreachableCode.isOn()) {
1231 callbacks.add(
1232 new CheckUnreachableCode(compiler, options.checkUnreachableCode));
1233 }
1234 if (options.checkMissingReturn.isOn() && options.checkTypes) {
1235 callbacks.add(
1236 new CheckMissingReturn(compiler, options.checkMissingReturn));
1237 }
1238 return combineChecks(compiler, callbacks);
1239 }
1240 };
1241
1242 /** Checks access controls. Depends on type-inference. */
1243 final HotSwapPassFactory checkAccessControls =
1244 new HotSwapPassFactory("checkAccessControls", true) {
1245 @Override
1246 protected HotSwapCompilerPass create(AbstractCompiler compiler) {
1247 return new CheckAccessControls(compiler);
1248 }
1249 };
1250
1251 /** Executes the given callbacks with a {@link CombinedCompilerPass}. */
1252 private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler,
1253 List<Callback> callbacks) {
1254 Preconditions.checkArgument(callbacks.size() > 0);
1255 Callback[] array = callbacks.toArray(new Callback[callbacks.size()]);
1256 return new CombinedCompilerPass(compiler, array);
1257 }
1258
1259 /** A compiler pass that resolves types in the global scope. */
1260 class GlobalTypeResolver implements HotSwapCompilerPass {
1261 private final AbstractCompiler compiler;
1262
1263 GlobalTypeResolver(AbstractCompiler compiler) {
1264 this.compiler = compiler;
1265 }
1266
1267 @Override
1268 public void process(Node externs, Node root) {
1269 if (topScope == null) {
1270 regenerateGlobalTypedScope(compiler, root.getParent());
1271 } else {
1272 compiler.getTypeRegistry().resolveTypesInScope(topScope);
1273 }
1274 }
1275 @Override
1276 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
1277 patchGlobalTypedScope(compiler, scriptRoot);
1278 }
1279 }
1280
1281 /** A compiler pass that clears the global scope. */
1282 class ClearTypedScope implements CompilerPass {
1283 @Override
1284 public void process(Node externs, Node root) {
1285 clearTypedScope();
1286 }
1287 }
1288
1289 /** Checks global name usage. */
1290 final PassFactory checkGlobalNames =
1291 new PassFactory("checkGlobalNames", true) {
1292 @Override
1293 protected CompilerPass create(final AbstractCompiler compiler) {
1294 return new CompilerPass() {
1295 @Override
1296 public void process(Node externs, Node jsRoot) {
1297 // Create a global namespace for analysis by check passes.
1298 // Note that this class does all heavy computation lazily,
1299 // so it's OK to create it here.
1300 namespaceForChecks = new GlobalNamespace(compiler, externs, jsRoot);
1301 new CheckGlobalNames(compiler, options.checkGlobalNamesLevel)
1302 .injectNamespace(namespaceForChecks).process(externs, jsRoot);
1303 }
1304 };
1305 }
1306 };
1307
1308 /** Checks that the code is ES5 or Caja compliant. */
1309 final PassFactory checkStrictMode =
1310 new PassFactory("checkStrictMode", true) {
1311 @Override
1312 protected CompilerPass create(AbstractCompiler compiler) {
1313 return new StrictModeCheck(compiler,
1314 !options.checkSymbols, // don't check variables twice
1315 !options.checkCaja); // disable eval check if not Caja
1316 }
1317 };
1318
1319 /** Process goog.tweak.getTweak() calls. */
1320 final PassFactory processTweaks = new PassFactory("processTweaks", true) {
1321 @Override
1322 protected CompilerPass create(final AbstractCompiler compiler) {
1323 return new CompilerPass() {
1324 @Override
1325 public void process(Node externs, Node jsRoot) {
1326 new ProcessTweaks(compiler,
1327 options.getTweakProcessing().shouldStrip(),
1328 options.getTweakReplacements()).process(externs, jsRoot);
1329 }
1330 };
1331 }
1332 };
1333
1334 /** Override @define-annotated constants. */
1335 final PassFactory processDefines = new PassFactory("processDefines", true) {
1336 @Override
1337 protected CompilerPass create(final AbstractCompiler compiler) {
1338 return new CompilerPass() {
1339 @Override
1340 public void process(Node externs, Node jsRoot) {
1341 Map<String, Node> replacements = getAdditionalReplacements(options);
1342 replacements.putAll(options.getDefineReplacements());
1343
1344 new ProcessDefines(compiler, replacements)
1345 .injectNamespace(namespaceForChecks).process(externs, jsRoot);
1346 }
1347 };
1348 }
1349 };
1350
1351 /** Release references to data that is only needed during checks. */
1352 final PassFactory garbageCollectChecks =
1353 new HotSwapPassFactory("garbageCollectChecks", true) {
1354 @Override
1355 protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
1356 return new HotSwapCompilerPass() {
1357 @Override
1358 public void process(Node externs, Node jsRoot) {
1359 // Kill the global namespace so that it can be garbage collected
1360 // after all passes are through with it.
1361 namespaceForChecks = null;
1362 }
1363
1364 @Override
1365 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
1366 process(null, null);
1367 }
1368 };
1369 }
1370 };
1371
1372 /** Checks that all constants are not modified */
1373 final PassFactory checkConsts = new PassFactory("checkConsts", true) {
1374 @Override
1375 protected CompilerPass create(AbstractCompiler compiler) {
1376 return new ConstCheck(compiler);
1377 }
1378 };
1379
1380 /** Computes the names of functions for later analysis. */
1381 final PassFactory computeFunctionNames =
1382 new PassFactory("computeFunctionNames", true) {
1383 @Override
1384 protected CompilerPass create(AbstractCompiler compiler) {
1385 return ((functionNames = new FunctionNames(compiler)));
1386 }
1387 };
1388
1389 /** Skips Caja-private properties in for-in loops */
1390 final PassFactory ignoreCajaProperties =
1391 new PassFactory("ignoreCajaProperties", true) {
1392 @Override
1393 protected CompilerPass create(AbstractCompiler compiler) {
1394 return new IgnoreCajaProperties(compiler);
1395 }
1396 };
1397
1398 /** Inserts run-time type assertions for debugging. */
1399 final PassFactory runtimeTypeCheck =
1400 new PassFactory("runtimeTypeCheck", true) {
1401 @Override
1402 protected CompilerPass create(AbstractCompiler compiler) {
1403 return new RuntimeTypeCheck(compiler,
1404 options.runtimeTypeCheckLogFunction);
1405 }
1406 };
1407
1408 /** Generates unique ids. */
1409 final PassFactory replaceIdGenerators =
1410 new PassFactory("replaceIdGenerators", true) {
1411 @Override
1412 protected CompilerPass create(final AbstractCompiler compiler) {
1413 return new CompilerPass() {
1414 @Override public void process(Node externs, Node root) {
1415 ReplaceIdGenerators pass =
1416 new ReplaceIdGenerators(
1417 compiler, options.idGenerators, options.generatePseudoNames,
1418 options.idGeneratorsMapSerialized);
1419 pass.process(externs, root);
1420 idGeneratorMap = pass.getSerializedIdMappings();
1421 }
1422 };
1423 }
1424 };
1425
1426 /** Replace strings. */
1427 final PassFactory replaceStrings = new PassFactory("replaceStrings", true) {
1428 @Override
1429 protected CompilerPass create(final AbstractCompiler compiler) {
1430 return new CompilerPass() {
1431 @Override public void process(Node externs, Node root) {
1432 ReplaceStrings pass = new ReplaceStrings(
1433 compiler,
1434 options.replaceStringsPlaceholderToken,
1435 options.replaceStringsFunctionDescriptions,
1436 options.replaceStringsReservedStrings,
1437 options.replaceStringsInputMap);
1438 pass.process(externs, root);
1439 stringMap = pass.getStringMap();
1440 }
1441 };
1442 }
1443 };
1444
1445 /** Optimizes the "arguments" array. */
1446 final PassFactory optimizeArgumentsArray =
1447 new PassFactory("optimizeArgumentsArray", true) {
1448 @Override
1449 protected CompilerPass create(AbstractCompiler compiler) {
1450 return new OptimizeArgumentsArray(compiler);
1451 }
1452 };
1453
1454 /** Remove variables set to goog.abstractMethod. */
1455 final PassFactory closureCodeRemoval =
1456 new PassFactory("closureCodeRemoval", true) {
1457 @Override
1458 protected CompilerPass create(final AbstractCompiler compiler) {
1459 return new ClosureCodeRemoval(compiler, options.removeAbstractMethods,
1460 options.removeClosureAsserts);
1461 }
1462 };
1463
1464 /** Special case optimizations for closure functions. */
1465 final PassFactory closureOptimizePrimitives =
1466 new PassFactory("closureOptimizePrimitives", true) {
1467 @Override
1468 protected CompilerPass create(final AbstractCompiler compiler) {
1469 return new ClosureOptimizePrimitives(compiler);
1470 }
1471 };
1472
1473 /** Puts global symbols into a single object. */
1474 final PassFactory rescopeGlobalSymbols =
1475 new PassFactory("rescopeGlobalSymbols", true) {
1476 @Override
1477 protected CompilerPass create(AbstractCompiler compiler) {
1478 return new RescopeGlobalSymbols(compiler, options.renamePrefixNamespace);
1479 }
1480 };
1481
1482 /** Collapses names in the global scope. */
1483 final PassFactory collapseProperties =
1484 new PassFactory("collapseProperties", true) {
1485 @Override
1486 protected CompilerPass create(AbstractCompiler compiler) {
1487 return new CollapseProperties(
1488 compiler, options.collapsePropertiesOnExternTypes,
1489 !isInliningForbidden());
1490 }
1491 };
1492
1493 /** Rewrite properties as variables. */
1494 final PassFactory collapseObjectLiterals =
1495 new PassFactory("collapseObjectLiterals", false) {
1496 @Override
1497 protected CompilerPass create(AbstractCompiler compiler) {
1498 return new InlineObjectLiterals(
1499 compiler, compiler.getUniqueNameIdSupplier());
1500 }
1501 };
1502
1503 /**
1504 * Try to infer the actual types, which may be narrower
1505 * than the declared types.
1506 */
1507 final PassFactory tightenTypesBuilder =
1508 new PassFactory("tightenTypes", true) {
1509 @Override
1510 protected CompilerPass create(AbstractCompiler compiler) {
1511 if (!options.checkTypes) {
1512 return new ErrorPass(compiler, TIGHTEN_TYPES_WITHOUT_TYPE_CHECK);
1513 }
1514 tightenTypes = new TightenTypes(compiler);
1515 return tightenTypes;
1516 }
1517 };
1518
1519 /** Devirtualize property names based on type information. */
1520 final PassFactory disambiguateProperties =
1521 new PassFactory("disambiguateProperties", true) {
1522 @Override
1523 protected CompilerPass create(AbstractCompiler compiler) {
1524 if (tightenTypes == null) {
1525 return DisambiguateProperties.forJSTypeSystem(compiler,
1526 options.propertyInvalidationErrors);
1527 } else {
1528 return DisambiguateProperties.forConcreteTypeSystem(
1529 compiler, tightenTypes, options.propertyInvalidationErrors);
1530 }
1531 }
1532 };
1533
1534 /**
1535 * Chain calls to functions that return this.
1536 */
1537 final PassFactory chainCalls = new PassFactory("chainCalls", true) {
1538 @Override
1539 protected CompilerPass create(AbstractCompiler compiler) {
1540 return new ChainCalls(compiler);
1541 }
1542 };
1543
1544 /**
1545 * Rewrite instance methods as static methods, to make them easier
1546 * to inline.
1547 */
1548 final PassFactory devirtualizePrototypeMethods =
1549 new PassFactory("devirtualizePrototypeMethods", true) {
1550 @Override
1551 protected CompilerPass create(AbstractCompiler compiler) {
1552 return new DevirtualizePrototypeMethods(compiler);
1553 }
1554 };
1555
1556 /**
1557 * Optimizes unused function arguments, unused return values, and inlines
1558 * constant parameters. Also runs RemoveUnusedVars.
1559 */
1560 final PassFactory optimizeCallsAndRemoveUnusedVars =
1561 new PassFactory("optimizeCalls_and_removeUnusedVars", false) {
1562 @Override
1563 protected CompilerPass create(AbstractCompiler compiler) {
1564 OptimizeCalls passes = new OptimizeCalls(compiler);
1565 if (options.optimizeReturns) {
1566 // Remove unused return values.
1567 passes.addPass(new OptimizeReturns(compiler));
1568 }
1569
1570 if (options.optimizeParameters) {
1571 // Remove all parameters that are constants or unused.
1572 passes.addPass(new OptimizeParameters(compiler));
1573 }
1574
1575 if (options.optimizeCalls) {
1576 boolean removeOnlyLocals = options.removeUnusedLocalVars
1577 && !options.removeUnusedVars;
1578 boolean preserveAnonymousFunctionNames =
1579 options.anonymousFunctionNaming !=
1580 AnonymousFunctionNamingPolicy.OFF;
1581 passes.addPass(
1582 new RemoveUnusedVars(compiler, !removeOnlyLocals,
1583 preserveAnonymousFunctionNames, true));
1584 }
1585 return passes;
1586 }
1587 };
1588
1589 /**
1590 * Look for function calls that are pure, and annotate them
1591 * that way.
1592 */
1593 final PassFactory markPureFunctions =
1594 new PassFactory("markPureFunctions", true) {
1595 @Override
1596 protected CompilerPass create(AbstractCompiler compiler) {
1597 return new PureFunctionIdentifier.Driver(
1598 compiler, options.debugFunctionSideEffectsPath, false);
1599 }
1600 };
1601
1602 /**
1603 * Look for function calls that have no side effects, and annotate them
1604 * that way.
1605 */
1606 final PassFactory markNoSideEffectCalls =
1607 new PassFactory("markNoSideEffectCalls", true) {
1608 @Override
1609 protected CompilerPass create(AbstractCompiler compiler) {
1610 return new MarkNoSideEffectCalls(compiler);
1611 }
1612 };
1613
1614 /** Inlines variables heuristically. */
1615 final PassFactory inlineVariables =
1616 new PassFactory("inlineVariables", false) {
1617 @Override
1618 protected CompilerPass create(AbstractCompiler compiler) {
1619 if (isInliningForbidden()) {
1620 // In old renaming schemes, inlining a variable can change whether
1621 // or not a property is renamed. This is bad, and those old renaming
1622 // schemes need to die.
1623 return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR);
1624 } else {
1625 InlineVariables.Mode mode;
1626 if (options.inlineVariables) {
1627 mode = InlineVariables.Mode.ALL;
1628 } else if (options.inlineLocalVariables) {
1629 mode = InlineVariables.Mode.LOCALS_ONLY;
1630 } else {
1631 throw new IllegalStateException("No variable inlining option set.");
1632 }
1633
1634 return new InlineVariables(compiler, mode, true);
1635 }
1636 }
1637 };
1638
1639 /** Inlines variables that are marked as constants. */
1640 final PassFactory inlineConstants =
1641 new PassFactory("inlineConstants", false) {
1642 @Override
1643 protected CompilerPass create(AbstractCompiler compiler) {
1644 return new InlineVariables(
1645 compiler, InlineVariables.Mode.CONSTANTS_ONLY, true);
1646 }
1647 };
1648
1649 /**
1650 * Perform local control flow optimizations.
1651 */
1652 final PassFactory minimizeExitPoints =
1653 new PassFactory("minimizeExitPoints", false) {
1654 @Override
1655 protected CompilerPass create(AbstractCompiler compiler) {
1656 return new MinimizeExitPoints(compiler);
1657 }
1658 };
1659
1660 /**
1661 * Use data flow analysis to remove dead branches.
1662 */
1663 final PassFactory removeUnreachableCode =
1664 new PassFactory("removeUnreachableCode", false) {
1665 @Override
1666 protected CompilerPass create(AbstractCompiler compiler) {
1667 return new UnreachableCodeElimination(compiler, true);
1668 }
1669 };
1670
1671 /**
1672 * Remove prototype properties that do not appear to be used.
1673 */
1674 final PassFactory removeUnusedPrototypeProperties =
1675 new PassFactory("removeUnusedPrototypeProperties", false) {
1676 @Override
1677 protected CompilerPass create(AbstractCompiler compiler) {
1678 return new RemoveUnusedPrototypeProperties(
1679 compiler, options.removeUnusedPrototypePropertiesInExterns,
1680 !options.removeUnusedVars);
1681 }
1682 };
1683
1684 /**
1685 * Remove prototype properties that do not appear to be used.
1686 */
1687 final PassFactory removeUnusedClassProperties =
1688 new PassFactory("removeUnusedClassProperties", false) {
1689 @Override
1690 protected CompilerPass create(AbstractCompiler compiler) {
1691 return new RemoveUnusedClassProperties(compiler);
1692 }
1693 };
1694
1695 /**
1696 * Process smart name processing - removes unused classes and does referencing
1697 * starting with minimum set of names.
1698 */
1699 final PassFactory smartNamePass = new PassFactory("smartNamePass", true) {
1700 @Override
1701 protected CompilerPass create(final AbstractCompiler compiler) {
1702 return new CompilerPass() {
1703 @Override
1704 public void process(Node externs, Node root) {
1705 NameAnalyzer na = new NameAnalyzer(compiler, false);
1706 na.process(externs, root);
1707
1708 String reportPath = options.reportPath;
1709 if (reportPath != null) {
1710 try {
1711 Files.write(na.getHtmlReport(), new File(reportPath),
1712 Charsets.UTF_8);
1713 } catch (IOException e) {
1714 compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath));
1715 }
1716 }
1717
1718 if (options.smartNameRemoval) {
1719 na.removeUnreferenced();
1720 }
1721 }
1722 };
1723 }
1724 };
1725
1726 /**
1727 * Process smart name processing - removes unused classes and does referencing
1728 * starting with minimum set of names.
1729 */
1730 final PassFactory smartNamePass2 = new PassFactory("smartNamePass", true) {
1731 @Override
1732 protected CompilerPass create(final AbstractCompiler compiler) {
1733 return new CompilerPass() {
1734 @Override
1735 public void process(Node externs, Node root) {
1736 NameAnalyzer na = new NameAnalyzer(compiler, false);
1737 na.process(externs, root);
1738 na.removeUnreferenced();
1739 }
1740 };
1741 }
1742 };
1743
1744 /** Inlines simple methods, like getters */
1745 final PassFactory inlineSimpleMethods =
1746 new PassFactory("inlineSimpleMethods", false) {
1747 @Override
1748 protected CompilerPass create(AbstractCompiler compiler) {
1749 return new InlineSimpleMethods(compiler);
1750 }
1751 };
1752
1753 /** Kills dead assignments. */
1754 final PassFactory deadAssignmentsElimination =
1755 new PassFactory("deadAssignmentsElimination", false) {
1756 @Override
1757 protected CompilerPass create(AbstractCompiler compiler) {
1758 return new DeadAssignmentsElimination(compiler);
1759 }
1760 };
1761
1762 /** Inlines function calls. */
1763 final PassFactory inlineFunctions =
1764 new PassFactory("inlineFunctions", false) {
1765 @Override
1766 protected CompilerPass create(AbstractCompiler compiler) {
1767 boolean enableBlockInlining = !isInliningForbidden();
1768 return new InlineFunctions(
1769 compiler,
1770 compiler.getUniqueNameIdSupplier(),
1771 options.inlineFunctions,
1772 options.inlineLocalFunctions,
1773 enableBlockInlining,
1774 options.assumeStrictThis()
1775 || options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT,
1776 options.assumeClosuresOnlyCaptureReferences);
1777 }
1778 };
1779
1780 /** Inlines constant properties. */
1781 final PassFactory inlineProperties =
1782 new PassFactory("inlineProperties", false) {
1783 @Override
1784 protected CompilerPass create(AbstractCompiler compiler) {
1785 return new InlineProperties(compiler);
1786 }
1787 };
1788
1789 /** Removes variables that are never used. */
1790 final PassFactory removeUnusedVars =
1791 new PassFactory("removeUnusedVars", false) {
1792 @Override
1793 protected CompilerPass create(AbstractCompiler compiler) {
1794 boolean removeOnlyLocals = options.removeUnusedLocalVars
1795 && !options.removeUnusedVars;
1796 boolean preserveAnonymousFunctionNames =
1797 options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
1798 return new RemoveUnusedVars(
1799 compiler,
1800 !removeOnlyLocals,
1801 preserveAnonymousFunctionNames,
1802 false);
1803 }
1804 };
1805
1806 /**
1807 * Move global symbols to a deeper common module
1808 */
1809 final PassFactory crossModuleCodeMotion =
1810 new PassFactory("crossModuleCodeMotion", false) {
1811 @Override
1812 protected CompilerPass create(AbstractCompiler compiler) {
1813 return new CrossModuleCodeMotion(compiler, compiler.getModuleGraph());
1814 }
1815 };
1816
1817 /**
1818 * Move methods to a deeper common module
1819 */
1820 final PassFactory crossModuleMethodMotion =
1821 new PassFactory("crossModuleMethodMotion", false) {
1822 @Override
1823 protected CompilerPass create(AbstractCompiler compiler) {
1824 return new CrossModuleMethodMotion(
1825 compiler, crossModuleIdGenerator,
1826 // Only move properties in externs if we're not treating
1827 // them as exports.
1828 options.removeUnusedPrototypePropertiesInExterns);
1829 }
1830 };
1831
1832 /**
1833 * Specialize the initial module at the cost of later modules
1834 */
1835 final PassFactory specializeInitialModule =
1836 new PassFactory("specializeInitialModule", true) {
1837 @Override
1838 protected CompilerPass create(AbstractCompiler compiler) {
1839 return new SpecializeModule(compiler, devirtualizePrototypeMethods,
1840 inlineFunctions, removeUnusedPrototypeProperties);
1841 }
1842 };
1843
1844 /** A data-flow based variable inliner. */
1845 final PassFactory flowSensitiveInlineVariables =
1846 new PassFactory("flowSensitiveInlineVariables", true) {
1847 @Override
1848 protected CompilerPass create(AbstractCompiler compiler) {
1849 return new FlowSensitiveInlineVariables(compiler);
1850 }
1851 };
1852
1853 /** Uses register-allocation algorithms to use fewer variables. */
1854 final PassFactory coalesceVariableNames =
1855 new PassFactory("coalesceVariableNames", true) {
1856 @Override
1857 protected CompilerPass create(AbstractCompiler compiler) {
1858 return new CoalesceVariableNames(compiler, options.generatePseudoNames);
1859 }
1860 };
1861
1862 /**
1863 * Some simple, local collapses (e.g., {@code var x; var y;} becomes
1864 * {@code var x,y;}.
1865 */
1866 final PassFactory exploitAssign = new PassFactory("exploitAssign", true) {
1867 @Override
1868 protected CompilerPass create(AbstractCompiler compiler) {
1869 return new PeepholeOptimizationsPass(compiler,
1870 new ExploitAssigns());
1871 }
1872 };
1873
1874 /**
1875 * Some simple, local collapses (e.g., {@code var x; var y;} becomes
1876 * {@code var x,y;}.
1877 */
1878 final PassFactory collapseVariableDeclarations =
1879 new PassFactory("collapseVariableDeclarations", true) {
1880 @Override
1881 protected CompilerPass create(AbstractCompiler compiler) {
1882 return new CollapseVariableDeclarations(compiler);
1883 }
1884 };
1885
1886 /**
1887 * Simple global collapses of variable declarations.
1888 */
1889 final PassFactory groupVariableDeclarations =
1890 new PassFactory("groupVariableDeclarations", true) {
1891 @Override
1892 protected CompilerPass create(AbstractCompiler compiler) {
1893 return new GroupVariableDeclarations(compiler);
1894 }
1895 };
1896
1897 /**
1898 * Extracts common sub-expressions.
1899 */
1900 final PassFactory extractPrototypeMemberDeclarations =
1901 new PassFactory("extractPrototypeMemberDeclarations", true) {
1902 @Override
1903 protected CompilerPass create(AbstractCompiler compiler) {
1904 return new ExtractPrototypeMemberDeclarations(
1905 compiler, Pattern.USE_GLOBAL_TEMP);
1906 }
1907 };
1908
1909 /** Rewrites common function definitions to be more compact. */
1910 final PassFactory rewriteFunctionExpressions =
1911 new PassFactory("rewriteFunctionExpressions", true) {
1912 @Override
1913 protected CompilerPass create(AbstractCompiler compiler) {
1914 return new FunctionRewriter(compiler);
1915 }
1916 };
1917
1918 /** Collapses functions to not use the VAR keyword. */
1919 final PassFactory collapseAnonymousFunctions =
1920 new PassFactory("collapseAnonymousFunctions", true) {
1921 @Override
1922 protected CompilerPass create(AbstractCompiler compiler) {
1923 return new CollapseAnonymousFunctions(compiler);
1924 }
1925 };
1926
1927 /** Moves function declarations to the top, to simulate actual hoisting. */
1928 final PassFactory moveFunctionDeclarations =
1929 new PassFactory("moveFunctionDeclarations", true) {
1930 @Override
1931 protected CompilerPass create(AbstractCompiler compiler) {
1932 return new MoveFunctionDeclarations(compiler);
1933 }
1934 };
1935
1936 final PassFactory nameUnmappedAnonymousFunctions =
1937 new PassFactory("nameAnonymousFunctions", true) {
1938 @Override
1939 protected CompilerPass create(AbstractCompiler compiler) {
1940 return new NameAnonymousFunctions(compiler);
1941 }
1942 };
1943
1944 final PassFactory nameMappedAnonymousFunctions =
1945 new PassFactory("nameAnonymousFunctions", true) {
1946 @Override
1947 protected CompilerPass create(final AbstractCompiler compiler) {
1948 return new CompilerPass() {
1949 @Override public void process(Node externs, Node root) {
1950 NameAnonymousFunctionsMapped naf =
1951 new NameAnonymousFunctionsMapped(
1952 compiler, options.inputAnonymousFunctionNamingMap);
1953 naf.process(externs, root);
1954 anonymousFunctionNameMap = naf.getFunctionMap();
1955 }
1956 };
1957 }
1958 };
1959
1960 /** Alias external symbols. */
1961 final PassFactory aliasExternals = new PassFactory("aliasExternals", true) {
1962 @Override
1963 protected CompilerPass create(AbstractCompiler compiler) {
1964 return new AliasExternals(compiler, compiler.getModuleGraph(),
1965 options.unaliasableGlobals, options.aliasableGlobals);
1966 }
1967 };
1968
1969 /**
1970 * Alias string literals with global variables, to avoid creating lots of
1971 * transient objects.
1972 */
1973 final PassFactory aliasStrings = new PassFactory("aliasStrings", true) {
1974 @Override
1975 protected CompilerPass create(AbstractCompiler compiler) {
1976 return new AliasStrings(
1977 compiler,
1978 compiler.getModuleGraph(),
1979 options.aliasAllStrings ? null : options.aliasableStrings,
1980 options.aliasStringsBlacklist,
1981 options.outputJsStringUsage);
1982 }
1983 };
1984
1985 /** Aliases common keywords (true, false) */
1986 final PassFactory aliasKeywords = new PassFactory("aliasKeywords", true) {
1987 @Override
1988 protected CompilerPass create(AbstractCompiler compiler) {
1989 return new AliasKeywords(compiler);
1990 }
1991 };
1992
1993 /** Handling for the ObjectPropertyString primitive. */
1994 final PassFactory objectPropertyStringPostprocess =
1995 new PassFactory("ObjectPropertyStringPostprocess", true) {
1996 @Override
1997 protected CompilerPass create(AbstractCompiler compiler) {
1998 return new ObjectPropertyStringPostprocess(compiler);
1999 }
2000 };
2001
2002 /**
2003 * Renames properties so that the two properties that never appear on
2004 * the same object get the same name.
2005 */
2006 final PassFactory ambiguateProperties =
2007 new PassFactory("ambiguateProperties", true) {
2008 @Override
2009 protected CompilerPass create(AbstractCompiler compiler) {
2010 return new AmbiguateProperties(
2011 compiler, options.anonymousFunctionNaming.getReservedCharacters());
2012 }
2013 };
2014
2015 /**
2016 * Mark the point at which the normalized AST assumptions no longer hold.
2017 */
2018 final PassFactory markUnnormalized =
2019 new PassFactory("markUnnormalized", true) {
2020 @Override
2021 protected CompilerPass create(final AbstractCompiler compiler) {
2022 return new CompilerPass() {
2023 @Override public void process(Node externs, Node root) {
2024 compiler.setLifeCycleStage(LifeCycleStage.RAW);
2025 }
2026 };
2027 }
2028 };
2029
2030 /** Denormalize the AST for code generation. */
2031 final PassFactory denormalize = new PassFactory("denormalize", true) {
2032 @Override
2033 protected CompilerPass create(AbstractCompiler compiler) {
2034 return new Denormalize(compiler);
2035 }
2036 };
2037
2038 /** Inverting name normalization. */
2039 final PassFactory invertContextualRenaming =
2040 new PassFactory("invertContextualRenaming", true) {
2041 @Override
2042 protected CompilerPass create(AbstractCompiler compiler) {
2043 return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler);
2044 }
2045 };
2046
2047 /**
2048 * Renames properties.
2049 */
2050 final PassFactory renameProperties =
2051 new PassFactory("renameProperties", true) {
2052 @Override
2053 protected CompilerPass create(final AbstractCompiler compiler) {
2054 final VariableMap prevPropertyMap = options.inputPropertyMap;
2055 return new CompilerPass() {
2056 @Override public void process(Node externs, Node root) {
2057 propertyMap = runPropertyRenaming(
2058 compiler, prevPropertyMap, externs, root);
2059 }
2060 };
2061 }
2062 };
2063
2064 private VariableMap runPropertyRenaming(
2065 AbstractCompiler compiler, VariableMap prevPropertyMap,
2066 Node externs, Node root) {
2067 char[] reservedChars =
2068 options.anonymousFunctionNaming.getReservedCharacters();
2069 switch (options.propertyRenaming) {
2070 case HEURISTIC:
2071 RenamePrototypes rproto = new RenamePrototypes(compiler, false,
2072 reservedChars, prevPropertyMap);
2073 rproto.process(externs, root);
2074 return rproto.getPropertyMap();
2075
2076 case AGGRESSIVE_HEURISTIC:
2077 RenamePrototypes rproto2 = new RenamePrototypes(compiler, true,
2078 reservedChars, prevPropertyMap);
2079 rproto2.process(externs, root);
2080 return rproto2.getPropertyMap();
2081
2082 case ALL_UNQUOTED:
2083 RenameProperties rprop = new RenameProperties(
2084 compiler, options.propertyAffinity, options.generatePseudoNames,
2085 prevPropertyMap, reservedChars);
2086 rprop.process(externs, root);
2087 return rprop.getPropertyMap();
2088
2089 default:
2090 throw new IllegalStateException(
2091 "Unrecognized property renaming policy");
2092 }
2093 }
2094
2095 /** Renames variables. */
2096 final PassFactory renameVars = new PassFactory("renameVars", true) {
2097 @Override
2098 protected CompilerPass create(final AbstractCompiler compiler) {
2099 final VariableMap prevVariableMap = options.inputVariableMap;
2100 return new CompilerPass() {
2101 @Override public void process(Node externs, Node root) {
2102 variableMap = runVariableRenaming(
2103 compiler, prevVariableMap, externs, root);
2104 }
2105 };
2106 }
2107 };
2108
2109 private VariableMap runVariableRenaming(
2110 AbstractCompiler compiler, VariableMap prevVariableMap,
2111 Node externs, Node root) {
2112 char[] reservedChars =
2113 options.anonymousFunctionNaming.getReservedCharacters();
2114 boolean preserveAnonymousFunctionNames =
2115 options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
2116 Set<String> reservedNames = Sets.newHashSet();
2117 if (exportedNames != null) {
2118 reservedNames.addAll(exportedNames);
2119 }
2120 reservedNames.addAll(ParserRunner.getReservedVars());
2121 RenameVars rn = new RenameVars(
2122 compiler,
2123 options.renamePrefix,
2124 options.variableRenaming == VariableRenamingPolicy.LOCAL,
2125 preserveAnonymousFunctionNames,
2126 options.generatePseudoNames,
2127 options.shadowVariables,
2128 prevVariableMap,
2129 reservedChars,
2130 reservedNames);
2131 rn.process(externs, root);
2132 return rn.getVariableMap();
2133 }
2134
2135 /** Renames labels */
2136 final PassFactory renameLabels = new PassFactory("renameLabels", true) {
2137 @Override
2138 protected CompilerPass create(AbstractCompiler compiler) {
2139 return new RenameLabels(compiler);
2140 }
2141 };
2142
2143 /** Convert bracket access to dot access */
2144 final PassFactory convertToDottedProperties =
2145 new PassFactory("convertToDottedProperties", true) {
2146 @Override
2147 protected CompilerPass create(AbstractCompiler compiler) {
2148 return new ConvertToDottedProperties(compiler);
2149 }
2150 };
2151
2152 /** Checks that all variables are defined. */
2153 final PassFactory sanityCheckAst = new PassFactory("sanityCheckAst", true) {
2154 @Override
2155 protected CompilerPass create(AbstractCompiler compiler) {
2156 return new AstValidator();
2157 }
2158 };
2159
2160 /** Checks that all variables are defined. */
2161 final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) {
2162 @Override
2163 protected CompilerPass create(AbstractCompiler compiler) {
2164 return new VarCheck(compiler, true);
2165 }
2166 };
2167
2168 /** Adds instrumentations according to an instrumentation template. */
2169 final PassFactory instrumentFunctions =
2170 new PassFactory("instrumentFunctions", true) {
2171 @Override
2172 protected CompilerPass create(final AbstractCompiler compiler) {
2173 return new CompilerPass() {
2174 @Override public void process(Node externs, Node root) {
2175 try {
2176 FileReader templateFile =
2177 new FileReader(options.instrumentationTemplate);
2178 (new InstrumentFunctions(
2179 compiler, functionNames,
2180 options.instrumentationTemplate,
2181 options.appNameStr,
2182 templateFile)).process(externs, root);
2183 } catch (IOException e) {
2184 compiler.report(
2185 JSError.make(AbstractCompiler.READ_ERROR,
2186 options.instrumentationTemplate));
2187 }
2188 }
2189 };
2190 }
2191 };
2192
2193 /**
2194 * Create a no-op pass that can only run once. Used to break up loops.
2195 */
2196 static PassFactory createEmptyPass(String name) {
2197 return new PassFactory(name, true) {
2198 @Override
2199 protected CompilerPass create(final AbstractCompiler compiler) {
2200 return runInSerial();
2201 }
2202 };
2203 }
2204
2205 /**
2206 * Runs custom passes that are designated to run at a particular time.
2207 */
2208 private PassFactory getCustomPasses(
2209 final CustomPassExecutionTime executionTime) {
2210 return new PassFactory("runCustomPasses", true) {
2211 @Override
2212 protected CompilerPass create(final AbstractCompiler compiler) {
2213 return runInSerial(options.customPasses.get(executionTime));
2214 }
2215 };
2216 }
2217
2218 /**
2219 * All inlining is forbidden in heuristic renaming mode, because inlining
2220 * will ruin the invariants that it depends on.
2221 */
2222 private boolean isInliningForbidden() {
2223 return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC ||
2224 options.propertyRenaming ==
2225 PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC;
2226 }
2227
2228 /** Create a compiler pass that runs the given passes in serial. */
2229 private static CompilerPass runInSerial(final CompilerPass ... passes) {
2230 return runInSerial(Lists.newArrayList(passes));
2231 }
2232
2233 /** Create a compiler pass that runs the given passes in serial. */
2234 private static CompilerPass runInSerial(
2235 final Collection<CompilerPass> passes) {
2236 return new CompilerPass() {
2237 @Override public void process(Node externs, Node root) {
2238 for (CompilerPass pass : passes) {
2239 pass.process(externs, root);
2240 }
2241 }
2242 };
2243 }
2244
2245 @VisibleForTesting
2246 static Map<String, Node> getAdditionalReplacements(
2247 CompilerOptions options) {
2248 Map<String, Node> additionalReplacements = Maps.newHashMap();
2249
2250 if (options.markAsCompiled || options.closurePass) {
2251 additionalReplacements.put(COMPILED_CONSTANT_NAME, IR.trueNode());
2252 }
2253
2254 if (options.closurePass && options.locale != null) {
2255 additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME,
2256 IR.string(options.locale));
2257 }
2258
2259 return additionalReplacements;
2260 }
2261
2262 final PassFactory printNameReferenceGraph =
2263 new PassFactory("printNameReferenceGraph", true) {
2264 @Override
2265 protected CompilerPass create(final AbstractCompiler compiler) {
2266 return new CompilerPass() {
2267 @Override
2268 public void process(Node externs, Node jsRoot) {
2269 NameReferenceGraphConstruction gc =
2270 new NameReferenceGraphConstruction(compiler);
2271 gc.process(externs, jsRoot);
2272 String graphFileName = options.nameReferenceGraphPath;
2273 try {
2274 Files.write(DotFormatter.toDot(gc.getNameReferenceGraph()),
2275 new File(graphFileName),
2276 Charsets.UTF_8);
2277 } catch (IOException e) {
2278 compiler.report(
2279 JSError.make(
2280 NAME_REF_GRAPH_FILE_ERROR, e.getMessage(), graphFileName));
2281 }
2282 }
2283 };
2284 }
2285 };
2286
2287 final PassFactory printNameReferenceReport =
2288 new PassFactory("printNameReferenceReport", true) {
2289 @Override
2290 protected CompilerPass create(final AbstractCompiler compiler) {
2291 return new CompilerPass() {
2292 @Override
2293 public void process(Node externs, Node jsRoot) {
2294 NameReferenceGraphConstruction gc =
2295 new NameReferenceGraphConstruction(compiler);
2296 String reportFileName = options.nameReferenceReportPath;
2297 try {
2298 NameReferenceGraphReport report =
2299 new NameReferenceGraphReport(gc.getNameReferenceGraph());
2300 Files.write(report.getHtmlReport(),
2301 new File(reportFileName),
2302 Charsets.UTF_8);
2303 } catch (IOException e) {
2304 compiler.report(
2305 JSError.make(
2306 NAME_REF_REPORT_FILE_ERROR,
2307 e.getMessage(),
2308 reportFileName));
2309 }
2310 }
2311 };
2312 }
2313 };
2314
2315 /**
2316 * A pass-factory that is good for {@code HotSwapCompilerPass} passes.
2317 */
2318 abstract static class HotSwapPassFactory extends PassFactory {
2319
2320 HotSwapPassFactory(String name, boolean isOneTimePass) {
2321 super(name, isOneTimePass);
2322 }
2323
2324 @Override
2325 protected abstract HotSwapCompilerPass create(AbstractCompiler compiler);
2326
2327 @Override
2328 HotSwapCompilerPass getHotSwapPass(AbstractCompiler compiler) {
2329 return this.create(compiler);
2330 }
2331 }
2332
2333 }