-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
DefaultPassConfig.java
3207 lines (2787 loc) · 108 KB
/
DefaultPassConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2009 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.javascript.jscomp.PassFactory.createEmptyPass;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES5;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES6;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES7;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8_MODULES;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.TYPESCRIPT;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.AbstractCompiler.MostRecentTypechecker;
import com.google.javascript.jscomp.CompilerOptions.ExtractPrototypeMemberDeclarationsMode;
import com.google.javascript.jscomp.CoverageInstrumentationPass.CoverageReach;
import com.google.javascript.jscomp.CoverageInstrumentationPass.InstrumentOption;
import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.jscomp.PassFactory.HotSwapPassFactory;
import com.google.javascript.jscomp.lint.CheckArrayWithGoogObject;
import com.google.javascript.jscomp.lint.CheckDuplicateCase;
import com.google.javascript.jscomp.lint.CheckEmptyStatements;
import com.google.javascript.jscomp.lint.CheckEnums;
import com.google.javascript.jscomp.lint.CheckInterfaces;
import com.google.javascript.jscomp.lint.CheckJSDocStyle;
import com.google.javascript.jscomp.lint.CheckMissingSemicolon;
import com.google.javascript.jscomp.lint.CheckNullableReturn;
import com.google.javascript.jscomp.lint.CheckPrimitiveAsObject;
import com.google.javascript.jscomp.lint.CheckPrototypeProperties;
import com.google.javascript.jscomp.lint.CheckRequiresAndProvidesSorted;
import com.google.javascript.jscomp.lint.CheckUnusedLabels;
import com.google.javascript.jscomp.lint.CheckUselessBlocks;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Pass factories and meta-data for native JSCompiler passes.
*
* @author nicksantos@google.com (Nick Santos)
*
* NOTE(dimvar): this needs some non-trivial refactoring. The pass config should
* use as little state as possible. The recommended way for a pass to leave
* behind some state for a subsequent pass is through the compiler object.
* Any other state remaining here should only be used when the pass config is
* creating the list of checks and optimizations, not after passes have started
* executing. For example, the field namespaceForChecks should be in Compiler.
*/
public final class DefaultPassConfig extends PassConfig {
/* For the --mark-as-compiled pass */
private static final String COMPILED_CONSTANT_NAME = "COMPILED";
/* Constant name for Closure's locale */
private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE";
static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR =
DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR",
"Rename prototypes and inline variables cannot be used together.");
// Miscellaneous errors.
private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN =
java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$");
/**
* A global namespace to share across checking passes.
*/
private GlobalNamespace namespaceForChecks = null;
/**
* A symbol table for registering references that get removed during
* preprocessing.
*/
private PreprocessorSymbolTable preprocessorSymbolTable = null;
/**
* Global state necessary for doing hotswap recompilation of files with references to
* processed goog.modules.
*/
private ClosureRewriteModule.GlobalRewriteState moduleRewriteState = null;
/**
* Ids for cross-module method stubbing, so that each method has
* a unique id.
*/
private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator =
new CrossModuleMethodMotion.IdGenerator();
/**
* Keys are arguments passed to getCssName() found during compilation; values
* are the number of times the key appeared as an argument to getCssName().
*/
private Map<String, Integer> cssNames = null;
/** The variable renaming map */
private VariableMap variableMap = null;
/** The property renaming map */
private VariableMap propertyMap = null;
/** The naming map for anonymous functions */
private VariableMap anonymousFunctionNameMap = null;
/** Fully qualified function names and globally unique ids */
private FunctionNames functionNames = null;
/** String replacement map */
private VariableMap stringMap = null;
/** Id generator map */
private String idGeneratorMap = null;
/**
* Whether to protect "hidden" side-effects.
* @see CheckSideEffects
*/
private final boolean protectHiddenSideEffects;
public DefaultPassConfig(CompilerOptions options) {
super(options);
// The current approach to protecting "hidden" side-effects is to
// wrap them in a function call that is stripped later, this shouldn't
// be done in IDE mode where AST changes may be unexpected.
protectHiddenSideEffects = options != null && options.shouldProtectHiddenSideEffects();
}
@Override
protected State getIntermediateState() {
return new State(
cssNames == null ? null : new HashMap<>(cssNames),
crossModuleIdGenerator, variableMap, propertyMap,
anonymousFunctionNameMap, stringMap, functionNames, idGeneratorMap);
}
GlobalNamespace getGlobalNamespace() {
return namespaceForChecks;
}
PreprocessorSymbolTable getPreprocessorSymbolTable() {
return preprocessorSymbolTable;
}
void maybeInitializePreprocessorSymbolTable(AbstractCompiler compiler) {
if (options.preservesDetailedSourceInfo()) {
Node root = compiler.getRoot();
if (preprocessorSymbolTable == null || preprocessorSymbolTable.getRootNode() != root) {
preprocessorSymbolTable = new PreprocessorSymbolTable(root);
}
}
}
void maybeInitializeModuleRewriteState() {
if (options.allowsHotswapReplaceScript() && this.moduleRewriteState == null) {
this.moduleRewriteState = new ClosureRewriteModule.GlobalRewriteState();
}
}
@Override
protected List<PassFactory> getTranspileOnlyPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.needsTranspilationFrom(TYPESCRIPT)) {
passes.add(convertEs6TypedToEs6);
}
passes.add(checkMissingSuper);
passes.add(checkVariableReferencesForTranspileOnly);
// It's important that the Dart super accessors pass run *before* es6ConvertSuper,
// which is a "late" ES6 pass. This is enforced in the assertValidOrder method.
if (options.dartPass && options.needsTranspilationFrom(ES6)) {
passes.add(dartSuperAccessorsPass);
}
if (options.needsTranspilationFrom(ES8)) {
TranspilationPasses.addEs2017Passes(passes);
passes.add(setFeatureSet(ES7));
}
// If the user has specified an input language of ES7 and an output language of ES6 or lower,
// we still need to run these "ES6" passes, because they do the transpilation of the ES7 **
// operator. If we split that into its own pass then the needsTranspilationFrom(ES7) call here
// can be removed.
if (options.needsTranspilationFrom(ES6) || options.needsTranspilationFrom(ES7)) {
TranspilationPasses.addEs6EarlyPasses(passes);
TranspilationPasses.addEs6LatePasses(passes);
TranspilationPasses.addPostCheckPasses(passes);
if (options.rewritePolyfills) {
TranspilationPasses.addRewritePolyfillPass(passes);
}
passes.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
if (!options.forceLibraryInjection.isEmpty()) {
passes.add(injectRuntimeLibraries);
}
assertAllOneTimePasses(passes);
assertValidOrderForChecks(passes);
return passes;
}
@Override
protected List<PassFactory> getWhitespaceOnlyPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.wrapGoogModulesForWhitespaceOnly) {
passes.add(whitespaceWrapGoogModules);
}
return passes;
}
private void addOldTypeCheckerPasses(
List<PassFactory> checks, CompilerOptions options) {
if (options.checkTypes || options.inferTypes) {
checks.add(resolveTypes);
checks.add(inferTypes);
if (options.checkTypes) {
checks.add(checkTypes);
} else {
checks.add(inferJsDocInfo);
}
// We assume that only clients who are going to re-compile, or do in-depth static analysis,
// will need the typed scope creator after the compile job.
if (!options.preservesDetailedSourceInfo() && !options.allowsHotswapReplaceScript()) {
checks.add(clearTypedScopePass);
}
}
}
@Override
protected List<PassFactory> getChecks() {
List<PassFactory> checks = new ArrayList<>();
if (options.shouldGenerateTypedExterns()) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
checks.add(generateIjs);
checks.add(whitespaceWrapGoogModules);
return checks;
}
checks.add(createEmptyPass("beforeStandardChecks"));
// Verify JsDoc annotations
checks.add(checkJsDoc);
if (options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(lintChecks);
}
if (options.closurePass && options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(checkRequiresAndProvidesSorted);
}
if (options.enables(DiagnosticGroups.MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.STRICT_MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.EXTRA_REQUIRE)) {
checks.add(checkRequires);
}
checks.add(checkVariableReferences);
if (options.closurePass) {
checks.add(closureCheckModule);
checks.add(closureRewriteModule);
}
if (options.needsTranspilationFrom(TYPESCRIPT)) {
checks.add(convertEs6TypedToEs6);
}
if (options.declaredGlobalExternsOnWindow) {
checks.add(declaredGlobalExternsOnWindow);
}
checks.add(checkMissingSuper);
if (options.closurePass) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
}
checks.add(checkSideEffects);
if (options.enables(DiagnosticGroups.MISSING_PROVIDE)) {
checks.add(checkProvides);
}
if (options.angularPass) {
checks.add(angularPass);
}
if (!options.generateExportsAfterTypeChecking && options.generateExports) {
checks.add(generateExports);
}
if (options.exportTestFunctions) {
checks.add(exportTestFunctions);
}
if (options.closurePass) {
checks.add(closurePrimitives);
}
if (options.isChromePassEnabled()) {
checks.add(chromePass);
}
// It's important that the PolymerPass run *after* the ClosurePrimitives and ChromePass rewrites
// and *before* the suspicious code checks. This is enforced in the assertValidOrder method.
if (options.polymerVersion != null) {
checks.add(polymerPass);
}
if (options.checkSuspiciousCode
|| options.enables(DiagnosticGroups.GLOBAL_THIS)
|| options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
checks.add(suspiciousCode);
}
if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) {
checks.add(closureCheckGetCssName);
}
if (options.syntheticBlockStartMarker != null) {
// This pass must run before the first fold constants pass.
checks.add(createSyntheticBlocks);
}
checks.add(checkVars);
if (options.inferConsts) {
checks.add(inferConsts);
}
if (options.computeFunctionSideEffects) {
checks.add(checkRegExp);
}
// This pass should run before types are assigned.
if (options.processObjectPropertyString) {
checks.add(objectPropertyStringPreprocess);
}
// It's important that the Dart super accessors pass run *before* es6ConvertSuper,
// which is a "late" ES6 pass. This is enforced in the assertValidOrder method.
if (options.dartPass && !options.getLanguageOut().toFeatureSet().contains(FeatureSet.ES6)) {
checks.add(dartSuperAccessorsPass);
}
if (options.needsTranspilationFrom(ES8)) {
TranspilationPasses.addEs2017Passes(checks);
checks.add(setFeatureSet(ES7));
}
if (options.needsTranspilationFrom(ES6) || options.needsTranspilationFrom(ES7)) {
checks.add(es6ExternsCheck);
TranspilationPasses.addEs6EarlyPasses(checks);
}
if (options.needsTranspilationFrom(ES6)) {
TranspilationPasses.addEs6LatePasses(checks);
if (options.rewritePolyfills) {
TranspilationPasses.addRewritePolyfillPass(checks);
}
// TODO(bradfordcsmith): This marking is really about how variable scoping is handled during
// type checking. It should really be handled in a more direct fashion.
checks.add(setFeatureSet(options.getLanguageOut().toFeatureSet()));
}
if (!options.forceLibraryInjection.isEmpty()) {
checks.add(injectRuntimeLibraries);
}
if (options.needsTranspilationFrom(ES6)) {
checks.add(convertStaticInheritance);
}
// End of ES6 transpilation passes.
if (!options.skipNonTranspilationPasses) {
addNonTranspilationCheckPasses(checks);
}
if (options.needsTranspilationFrom(ES6)) {
TranspilationPasses.addPostCheckPasses(checks);
}
// NOTE(dimvar): Tried to move this into the optimizations, but had to back off
// because the very first pass, normalization, rewrites the code in a way that
// causes loss of type information.
// So, I will convert the remaining optimizations to use TypeI and test that only
// in unit tests, not full builds. Once all passes are converted, then
// drop the OTI-after-NTI altogether.
// In addition, I will probably have a local edit of the repo that retains both
// types on Nodes, so I can test full builds on my machine. We can't check in such
// a change because it would greatly increase memory usage.
if (options.getNewTypeInference()) {
addOldTypeCheckerPasses(checks, options);
}
// When options.generateExportsAfterTypeChecking is true, run GenerateExports after
// both type checkers, not just after NTI.
if (options.generateExportsAfterTypeChecking && options.generateExports) {
checks.add(generateExports);
}
checks.add(createEmptyPass("afterStandardChecks"));
assertAllOneTimePasses(checks);
assertValidOrderForChecks(checks);
return checks;
}
private void addNonTranspilationCheckPasses(List<PassFactory> checks) {
checks.add(createEmptyPass("beforeTypeChecking"));
if (options.getNewTypeInference()) {
checks.add(symbolTableForNewTypeInference);
checks.add(newTypeInference);
}
if (options.j2clPassMode.equals(CompilerOptions.J2clPassMode.AUTO)) {
checks.add(j2clSourceFileChecker);
}
if (!options.allowsHotswapReplaceScript()) {
checks.add(inlineTypeAliases);
}
if (!options.getNewTypeInference()) {
addOldTypeCheckerPasses(checks, options);
}
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)
|| (!options.getNewTypeInference() && !options.disables(DiagnosticGroups.MISSING_RETURN))) {
checks.add(checkControlFlow);
}
// CheckAccessControls only works if check types is on.
if (options.checkTypes
&& (!options.disables(DiagnosticGroups.ACCESS_CONTROLS)
|| options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) {
checks.add(checkAccessControls);
}
if (!options.getNewTypeInference()) {
// NTI performs this check already
checks.add(checkConsts);
}
// Analyzer checks must be run after typechecking.
if (options.enables(DiagnosticGroups.ANALYZER_CHECKS) && options.checkTypes) {
checks.add(analyzerChecks);
}
if (options.checkEventfulObjectDisposalPolicy != CompilerOptions.DisposalCheckingPolicy.OFF) {
checks.add(checkEventfulObjectDisposal);
}
if (options.checkGlobalNamesLevel.isOn()) {
checks.add(checkGlobalNames);
}
checks.add(checkStrictMode);
if (!options.getConformanceConfigs().isEmpty()) {
checks.add(checkConformance);
}
// Replace 'goog.getCssName' before processing defines but after the
// other checks have been done.
if (options.closurePass) {
checks.add(closureReplaceGetCssName);
}
if (options.getTweakProcessing().isOn()) {
checks.add(processTweaks);
}
if (options.instrumentationTemplate != null || options.recordFunctionInformation) {
checks.add(computeFunctionNames);
}
if (options.checksOnly) {
// Run process defines here so that warnings/errors from that pass are emitted as part of
// checks.
// TODO(rluble): Split process defines into two stages, one that performs only checks to be
// run here, and the one that actually changes the AST that would run in the optimization
// phase.
checks.add(processDefines);
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
checks.add(j2clChecksPass);
}
}
@Override
protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = new ArrayList<>();
if (options.skipNonTranspilationPasses) {
return passes;
}
passes.add(garbageCollectChecks);
// i18n
// If you want to customize the compiler to use a different i18n pass,
// you can create a PassConfig that calls replacePassFactory
// to replace this.
if (options.replaceMessagesWithChromeI18n) {
passes.add(replaceMessagesForChrome);
} else if (options.messageBundle != null) {
passes.add(replaceMessages);
}
// Defines in code always need to be processed.
passes.add(processDefines);
if (options.getTweakProcessing().shouldStrip()
|| !options.stripTypes.isEmpty()
|| !options.stripNameSuffixes.isEmpty()
|| !options.stripTypePrefixes.isEmpty()
|| !options.stripNamePrefixes.isEmpty()) {
passes.add(stripCode);
}
passes.add(hoistVars);
passes.add(normalize);
// Create extern exports after the normalize because externExports depends on unique names.
if (options.isExternExportsEnabled() || options.externExportsPath != null) {
passes.add(externExports);
}
// Gather property names in externs so they can be queried by the
// optimizing passes.
passes.add(gatherExternProperties);
if (options.instrumentForCoverage) {
passes.add(instrumentForCodeCoverage);
}
// TODO(dimvar): convert this pass to use NTI. Low priority since it's
// mostly unused. Converting it shouldn't block switching to NTI.
if (options.runtimeTypeCheck && !options.getNewTypeInference()) {
passes.add(runtimeTypeCheck);
}
// Inlines functions that perform dynamic accesses to static properties of parameters that are
// typed as {Function}. This turns a dynamic access to a static property of a class definition
// into a fully qualified access and in so doing enables better dead code stripping.
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.add(j2clPass);
}
passes.add(createEmptyPass("beforeStandardOptimizations"));
if (options.replaceIdGenerators) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) {
passes.add(closureCodeRemoval);
}
if (options.removeJ2clAsserts) {
passes.add(j2clAssertRemovalPass);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguatePrivateProperties) {
passes.add(disambiguatePrivateProperties);
}
assertAllOneTimePasses(passes);
// Inline aliases so that following optimizations don't have to understand alias chains.
if (options.collapseProperties) {
passes.add(aggressiveInlineAliases);
}
// Inline getters/setters in J2CL classes so that Object.defineProperties() calls (resulting
// from desugaring) don't block class stripping.
if (options.j2clPassMode.shouldAddJ2clPasses() && options.collapseProperties) {
// Relies on collapseProperties-triggered aggressive alias inlining.
passes.add(j2clPropertyInlinerPass);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
if (options.inferConsts) {
passes.add(inferConsts);
}
if (options.reportPath != null && options.smartNameRemoval) {
passes.add(initNameAnalyzeReport);
}
// TODO(mlourenco): Ideally this would be in getChecks() instead of getOptimizations(). But
// for that it needs to understand constant properties as well. See b/31301233#10.
// Needs to happen after inferConsts and collapseProperties. Detects whether invocations of
// the method goog.string.Const.from are done with an argument which is a string literal.
passes.add(checkConstParams);
// Running smart name removal before disambiguate properties allows disambiguate properties
// to be more effective if code that would prevent disambiguation can be removed.
if (options.extraSmartNameRemoval && options.smartNameRemoval) {
// These passes remove code that is dead because of define flags.
// If the dead code is weakly typed, running these passes before property
// disambiguation results in more code removal.
// The passes are one-time on purpose. (The later runs are loopable.)
if (options.foldConstants && (options.inlineVariables || options.inlineLocalVariables)) {
passes.add(earlyInlineVariables);
passes.add(earlyPeepholeOptimizations);
}
passes.add(extraSmartNamePass);
}
// RewritePolyfills is overly generous in the polyfills it adds. After type
// checking and early smart name removal, we can use the new type information
// to figure out which polyfilled prototype methods are actually called, and
// which were "false alarms" (i.e. calling a method of the same name on a
// user-provided class). We also remove any polyfills added by code that
// was smart-name-removed. This is a one-time pass, since it does not work
// after inlining - we do not attempt to aggressively remove polyfills used
// by code that is only flow-sensitively dead.
if (options.rewritePolyfills) {
passes.add(removeUnusedPolyfills);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.shouldDisambiguateProperties()) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// This needs to come after the inline constants pass, which is run within
// the code removing passes.
if (options.closurePass) {
passes.add(closureOptimizePrimitives);
}
// ReplaceStrings runs after CollapseProperties in order to simplify
// pulling in values of constants defined in enums structures. It also runs
// after disambiguate properties and smart name removal so that it can
// correctly identify logging types and can replace references to string
// expressions.
if (!options.replaceStringsFunctionDescriptions.isEmpty()) {
passes.add(replaceStrings);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Must run after ProcessClosurePrimitives, Es6ConvertSuper, and assertion removals, but
// before OptimizeCalls (specifically, OptimizeParameters) and DevirtualizePrototypeMethods.
if (options.removeSuperMethods) {
passes.add(removeSuperMethodsPass);
}
// Method devirtualization benefits from property disambiguation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass("beforeMainOptimizations"));
// Because FlowSensitiveInlineVariables does not operate on the global scope due to compilation
// time, we need to run it once before InlineFunctions so that we don't miss inlining
// opportunities when a function will be inlined into the global scope.
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(flowSensitiveInlineVariables);
}
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass("afterMainOptimizations"));
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
passes.add(lastRemoveUnusedVars());
}
}
// Running this pass again is required to have goog.events compile down to
// nothing when compiled on its own.
if (options.smartNameRemoval) {
passes.add(smartNamePass2);
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations
// renamePrefixNamescape relies on moveFunctionDeclarations
// to preserve semantics.
|| options.renamePrefixNamespace != null) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
if (options.extractPrototypeMemberDeclarations != ExtractPrototypeMemberDeclarationsMode.OFF) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.shouldAmbiguateProperties()
&& options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
// Passes after this point can no longer depend on normalized AST
// assumptions.
passes.add(markUnnormalized);
if (options.coalesceVariableNames) {
passes.add(coalesceVariableNames);
// coalesceVariables creates identity assignments and more redundant code
// that can be removed, rerun the peephole optimizations to clean them
// up.
if (options.foldConstants) {
passes.add(peepholeOptimizationsOnce);
}
}
if (options.collapseVariableDeclarations) {
passes.add(exploitAssign);
passes.add(collapseVariableDeclarations);
}
// This pass works best after collapseVariableDeclarations.
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
// local variables ("$$1").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.foldConstants) {
passes.add(latePeepholeOptimizations);
}
if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
if (protectHiddenSideEffects) {
passes.add(stripSideEffectProtection);
}
if (options.renamePrefixNamespace != null) {
if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(
options.renamePrefixNamespace).matches()) {
throw new IllegalArgumentException(
"Illegal character in renamePrefixNamespace name: "
+ options.renamePrefixNamespace);
}
passes.add(rescopeGlobalSymbols);
}
// Safety checks
passes.add(sanityCheckAst);
passes.add(sanityCheckVars);
// Raise to ES6, if allowed
if (options.getLanguageOut().toFeatureSet().contains(FeatureSet.ES6)) {
passes.add(optimizeToEs6);
}
assertValidOrderForOptimizations(passes);
return passes;
}
/** Creates the passes for the main optimization loop. */
private List<PassFactory> getMainOptimizationLoop() {
List<PassFactory> passes = new ArrayList<>();
if (options.inlineGetters) {
passes.add(inlineSimpleMethods);
}
passes.addAll(getCodeRemovingPasses());
if (options.inlineFunctions || options.inlineLocalFunctions) {
passes.add(inlineFunctions);
}
if (options.shouldInlineProperties()) {
passes.add(inlineProperties);
}
boolean runOptimizeCalls = options.optimizeCalls
|| options.optimizeParameters
|| options.optimizeReturns;
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
if (options.deadAssignmentElimination) {
passes.add(deadAssignmentsElimination);
// The Polymer source is usually not included in the compilation, but it creates
// getters/setters for many properties in compiled code. Dead property assignment
// elimination is only safe when it knows about getters/setters. Therefore, we skip
// it if the polymer pass is enabled.
if (options.polymerVersion == null) {
passes.add(deadPropertyAssignmentElimination);
}
}
if (!runOptimizeCalls) {
passes.add(getRemoveUnusedVars("removeUnusedVars", false));
}
}
if (runOptimizeCalls) {
passes.add(optimizeCalls);
// RemoveUnusedVars cleans up after optimizeCalls, so we run it here.
// It has a special name because otherwise PhaseOptimizer would change its
// position in the optimization loop.
if (options.optimizeCalls) {
passes.add(
getRemoveUnusedVars("removeUnusedVars_afterOptimizeCalls", true));
}
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.add(j2clOptBundlePass);
}
assertAllLoopablePasses(passes);
return passes;
}