/
DefaultPassConfig.java
2940 lines (2558 loc) · 114 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.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.jscomp.PassFactory.createEmptyPass;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES2015;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.CompilerOptions.AliasStringsMode;
import com.google.javascript.jscomp.CompilerOptions.ChunkOutputType;
import com.google.javascript.jscomp.CompilerOptions.ExtractPrototypeMemberDeclarationsMode;
import com.google.javascript.jscomp.CompilerOptions.InstrumentOption;
import com.google.javascript.jscomp.CompilerOptions.PropertyCollapseLevel;
import com.google.javascript.jscomp.CompilerOptions.Reach;
import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern;
import com.google.javascript.jscomp.LocaleDataPasses.ProtectGoogLocale;
import com.google.javascript.jscomp.ScopedAliases.InvalidModuleGetHandling;
import com.google.javascript.jscomp.disambiguate.AmbiguateProperties;
import com.google.javascript.jscomp.disambiguate.DisambiguateProperties;
import com.google.javascript.jscomp.ijs.ConvertToTypedInterface;
import com.google.javascript.jscomp.instrumentation.CoverageInstrumentationPass;
import com.google.javascript.jscomp.instrumentation.CoverageInstrumentationPass.CoverageReach;
import com.google.javascript.jscomp.lint.CheckArrayWithGoogObject;
import com.google.javascript.jscomp.lint.CheckConstPrivateProperties;
import com.google.javascript.jscomp.lint.CheckConstantCaseNames;
import com.google.javascript.jscomp.lint.CheckDefaultExportOfGoogModule;
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.CheckEs6ModuleFileStructure;
import com.google.javascript.jscomp.lint.CheckEs6Modules;
import com.google.javascript.jscomp.lint.CheckExtraRequires;
import com.google.javascript.jscomp.lint.CheckGoogModuleTypeScriptName;
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.CheckNestedNames;
import com.google.javascript.jscomp.lint.CheckNoMutatedEs6Exports;
import com.google.javascript.jscomp.lint.CheckNullabilityModifiers;
import com.google.javascript.jscomp.lint.CheckPrimitiveAsObject;
import com.google.javascript.jscomp.lint.CheckPrototypeProperties;
import com.google.javascript.jscomp.lint.CheckProvidesSorted;
import com.google.javascript.jscomp.lint.CheckRequiresSorted;
import com.google.javascript.jscomp.lint.CheckUnusedLabels;
import com.google.javascript.jscomp.lint.CheckUnusedPrivateProperties;
import com.google.javascript.jscomp.lint.CheckUselessBlocks;
import com.google.javascript.jscomp.lint.CheckVar;
import com.google.javascript.jscomp.modules.ModuleMapCreator;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.jscomp.serialization.ConvertTypesToColors;
import com.google.javascript.jscomp.serialization.SerializationOptions;
import com.google.javascript.jscomp.serialization.SerializeTypedAstPass;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.jspecify.nullness.Nullable;
/**
* Pass factories and meta-data for native JSCompiler passes.
*
* <p>NOTE(johnlenz): 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.
*
* <p>The general goal is for this class to be as minimal as possible. Option validation should
* occur before this class configures the compiler, business logic should live here (passes should
* not be inlined, etc).
*/
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";
// Miscellaneous errors.
private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN =
java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$");
/** A symbol table for registering references that get removed during preprocessing. */
private final transient PreprocessorSymbolTable.CachedInstanceFactory
preprocessorSymbolTableFactory = new PreprocessorSymbolTable.CachedInstanceFactory();
public DefaultPassConfig(CompilerOptions options) {
super(options);
}
@Nullable PreprocessorSymbolTable getPreprocessorSymbolTable() {
return preprocessorSymbolTableFactory.getInstanceOrNull();
}
@Override
protected PassListBuilder getTranspileOnlyPasses() {
PassListBuilder passes = new PassListBuilder(options);
// Certain errors in block-scoped variable declarations will prevent correct transpilation
passes.maybeAdd(checkVariableReferences);
passes.maybeAdd(checkVars);
passes.maybeAdd(gatherModuleMetadataPass);
passes.maybeAdd(createModuleMapPass);
if (options.getLanguageIn().toFeatureSet().has(Feature.MODULES)) {
passes.maybeAdd(rewriteGoogJsImports);
switch (options.getEs6ModuleTranspilation()) {
case COMPILE:
TranspilationPasses.addEs6ModulePass(passes, preprocessorSymbolTableFactory);
break;
case TO_COMMON_JS_LIKE_MODULES:
TranspilationPasses.addEs6ModuleToCjsPass(passes);
break;
case RELATIVIZE_IMPORT_PATHS:
TranspilationPasses.addEs6RewriteImportPathPass(passes);
break;
case NONE:
// nothing
break;
}
}
passes.maybeAdd(checkSuper);
TranspilationPasses.addTranspilationRuntimeLibraries(passes);
if (options.needsTranspilationFrom(ES2015)) {
if (options.getRewritePolyfills()) {
if (options.getIsolatePolyfills()) {
throw new IllegalStateException(
"Polyfill isolation cannot be used in transpileOnly mode");
}
TranspilationPasses.addRewritePolyfillPass(passes);
}
}
passes.maybeAdd(injectRuntimeLibraries);
// NOTE: Any new transpiler passes added outside of
// {@code addEarlyOptimizationTranspilationPasses} also need to update
// {@code CompilerTestCase.transpileToEs5}
TranspilationPasses.addEarlyOptimizationTranspilationPasses(passes, options);
// Passes below this point may rely on normalization and must maintain normalization.
passes.maybeAdd(normalize);
TranspilationPasses.addPostNormalizationTranspilationPasses(passes, options);
// The transpilation passes may rely on normalize making all variables unique,
// but we're doing only transpilation, so we want to put back the original variable names
// wherever we can to meet user expectations.
//
// Also, if we don't do this, we could end up breaking runtime behavior that depends on specific
// variable names.
//
// The primary concern is function parameter names, because some frameworks, like Angular,
// do runtime injection of function call arguments based on the function parameter names.
passes.maybeAdd(invertContextualRenaming);
passes.assertAllOneTimePasses();
assertValidOrderForChecks(passes);
return passes;
}
@Override
protected PassListBuilder getWhitespaceOnlyPasses() {
PassListBuilder passes = new PassListBuilder(options);
if (options.getProcessCommonJSModules()) {
passes.maybeAdd(rewriteCommonJsModules);
} else if (options.getLanguageIn().toFeatureSet().has(Feature.MODULES)) {
passes.maybeAdd(rewriteScriptsToEs6Modules);
}
if (options.wrapGoogModulesForWhitespaceOnly) {
passes.maybeAdd(whitespaceWrapGoogModules);
}
return passes;
}
private void addModuleRewritingPasses(PassListBuilder checks, CompilerOptions options) {
if (options.getLanguageIn().toFeatureSet().has(Feature.MODULES)) {
checks.maybeAdd(rewriteGoogJsImports);
TranspilationPasses.addEs6ModulePass(checks, preprocessorSymbolTableFactory);
}
if (options.closurePass) {
checks.maybeAdd(closureRewriteModule);
}
}
@Override
protected PassListBuilder getChecks() {
PassListBuilder checks = new PassListBuilder(options);
checkState(
!options.skipNonTranspilationPasses,
"options.skipNonTranspilationPasses cannot be mixed with PassConfig::getChecks. Call"
+ " PassConfig::getTranspileOnlyPasses instead.");
if (options.isPropertyRenamingOnlyCompilationMode()) {
checks.maybeAdd(addSyntheticScript);
checks.maybeAdd(gatherGettersAndSetters);
checks.maybeAdd(gatherModuleMetadataPass);
checks.maybeAdd(createModuleMapPass);
checks.maybeAdd(declaredGlobalExternsOnWindow);
checks.maybeAdd(closureRewriteClass);
checks.maybeAdd(checkSideEffects);
checks.maybeAdd(angularPass);
checks.maybeAdd(closureGoogScopeAliases);
checks.maybeAdd(closurePrimitives);
addModuleRewritingPasses(checks, options);
checks.maybeAdd(clearTypedScopeCreatorPass);
checks.maybeAdd(clearTopTypedScopePass);
checks.maybeAdd(generateExports);
checks.maybeAdd(createEmptyPass(PassNames.AFTER_STANDARD_CHECKS));
checks.maybeAdd(mergeSyntheticScript);
checks.maybeAdd(gatherExternPropertiesCheck);
checks.maybeAdd(createEmptyPass(PassNames.BEFORE_SERIALIZATION));
return checks;
}
if (options.shouldGenerateTypedExterns()) {
checks.maybeAdd(addSyntheticScript);
checks.maybeAdd(closureGoogScopeAliasesForIjs);
checks.maybeAdd(closureRewriteClass);
checks.maybeAdd(generateIjs);
if (options.wrapGoogModulesForWhitespaceOnly) {
checks.maybeAdd(whitespaceWrapGoogModules);
}
checks.maybeAdd(removeSyntheticScript);
return checks;
}
// Run this pass before any pass tries to inject new runtime libraries
checks.maybeAdd(addSyntheticScript);
checks.maybeAdd(gatherGettersAndSetters);
if (options.getLanguageIn().toFeatureSet().contains(Feature.DYNAMIC_IMPORT)
&& !options.shouldAllowDynamicImport()) {
checks.maybeAdd(forbidDynamicImportUsage);
}
checks.maybeAdd(createEmptyPass("beforeStandardChecks"));
if (!options.getProcessCommonJSModules()
&& options.getLanguageIn().toFeatureSet().has(Feature.MODULES)) {
checks.maybeAdd(rewriteScriptsToEs6Modules);
}
// Run these passes after promoting scripts to modules, but before rewriting any other modules.
checks.maybeAdd(gatherModuleMetadataPass);
checks.maybeAdd(createModuleMapPass);
if (options.getProcessCommonJSModules()) {
checks.maybeAdd(rewriteCommonJsModules);
}
// Note: ChromePass can rewrite invalid @type annotations into valid ones, so should run before
// JsDoc checks.
if (options.isChromePassEnabled()) {
checks.maybeAdd(chromePass);
}
// Verify JsDoc annotations and check ES modules
checks.maybeAdd(checkJsDocAndEs6Modules);
checks.maybeAdd(checkTypeImportCodeReferences);
if (options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.maybeAdd(lintChecks);
}
if (options.closurePass && options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.maybeAdd(checkRequiresAndProvidesSorted);
}
if (options.enables(DiagnosticGroups.EXTRA_REQUIRE)) {
checks.maybeAdd(extraRequires);
}
if (options.enables(DiagnosticGroups.MISSING_REQUIRE)) {
checks.maybeAdd(checkMissingRequires);
}
checks.maybeAdd(declaredGlobalExternsOnWindow);
if (!options.getProcessCommonJSModules()) {
// TODO(ChadKillingsworth): move CommonJS module rewriting after VarCheck
checks.maybeAdd(checkVariableReferences);
checks.maybeAdd(checkVars);
}
if (options.closurePass) {
checks.maybeAdd(checkClosureImports);
}
checks.maybeAdd(checkStrictMode);
if (options.closurePass) {
checks.maybeAdd(closureCheckModule);
}
checks.maybeAdd(checkSuper);
if (options.closurePass) {
checks.maybeAdd(closureRewriteClass);
}
checks.maybeAdd(checkSideEffects);
if (options.angularPass) {
checks.maybeAdd(angularPass);
}
if (options.closurePass) {
checks.maybeAdd(closureGoogScopeAliases);
}
if (options.closurePass) {
checks.maybeAdd(closurePrimitives);
}
// TODO(b/141389184): Move this after the Polymer pass
if (options.shouldRewriteModulesBeforeTypechecking()) {
addModuleRewritingPasses(checks, options);
}
// 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.maybeAdd(polymerPass);
}
if (options.syntheticBlockStartMarker != null) {
// This pass must run before the first fold constants pass.
checks.maybeAdd(createSyntheticBlocks);
}
if (options.getProcessCommonJSModules()) {
// TODO(ChadKillingsworth): remove this branch.
checks.maybeAdd(checkVariableReferences);
checks.maybeAdd(checkVars);
}
if (options.inferConsts) {
checks.maybeAdd(inferConsts);
}
if (options.computeFunctionSideEffects) {
checks.maybeAdd(checkRegExp);
}
checks.maybeAdd(createEmptyPass(PassNames.BEFORE_TYPE_CHECKING));
if (options.checkTypes || options.inferTypes) {
checks.maybeAdd(inferTypes);
if (options.checkTypes) {
checks.maybeAdd(checkTypes);
} else {
checks.maybeAdd(inferJsDocInfo);
}
}
// Analyzer checks must be run after typechecking but before module rewriting.
if (options.enables(DiagnosticGroups.ANALYZER_CHECKS) && options.isTypecheckingEnabled()) {
checks.maybeAdd(analyzerChecks);
}
// 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()) {
checks.maybeAdd(clearTypedScopeCreatorPass);
}
if (options.shouldRewriteModulesAfterTypechecking()) {
addModuleRewritingPasses(checks, options);
}
// Dynamic import rewriting must always occur after type checking
if (options.shouldAllowDynamicImport()
&& options.getLanguageIn().toFeatureSet().has(Feature.DYNAMIC_IMPORT)) {
checks.maybeAdd(rewriteDynamicImports);
}
// 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()) {
checks.maybeAdd(clearTopTypedScopePass);
}
// CheckSuspiciousCode requires type information, so must run after the type checker.
if (options.checkSuspiciousCode
|| options.enables(DiagnosticGroups.GLOBAL_THIS)
|| options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
checks.maybeAdd(suspiciousCode);
}
if (options.j2clPassMode.shouldAddJ2clPasses()) {
checks.maybeAdd(j2clSourceFileChecker);
}
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)
|| !options.disables(DiagnosticGroups.MISSING_RETURN)) {
checks.maybeAdd(checkControlFlow);
}
// CheckAccessControls only works if check types is on.
if (options.isTypecheckingEnabled()
&& (!options.disables(DiagnosticGroups.ACCESS_CONTROLS)
|| options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) {
checks.maybeAdd(checkAccessControls);
}
checks.maybeAdd(checkConsts);
if (!options.getConformanceConfigs().isEmpty()) {
checks.maybeAdd(checkConformance);
}
if (options.getTweakProcessing().isOn()) {
checks.maybeAdd(processTweaks);
}
checks.maybeAdd(processDefinesCheck);
if (options.j2clPassMode.shouldAddJ2clPasses()) {
checks.maybeAdd(j2clChecksPass);
}
if (options.shouldRunTypeSummaryChecksLate()) {
checks.maybeAdd(generateIjs);
}
if (options.generateExports) {
checks.maybeAdd(generateExports);
}
checks.maybeAdd(createEmptyPass(PassNames.AFTER_STANDARD_CHECKS));
checks.maybeAdd(mergeSyntheticScript);
// At this point all checks have been done.
if (!options.checksOnly && options.exportTestFunctions) {
checks.maybeAdd(exportTestFunctions);
}
// Create extern exports after the normalize because externExports depends on unique names.
if (options.getExternExportsPath() != null) {
checks.maybeAdd(externExports);
}
if (!options.checksOnly) {
checks.maybeAdd(removeWeakSources);
}
// Gather property names in externs so they can be queried by the optimizing passes.
// See b/180424427 for why this runs in stage 1 and not stage 2.
checks.maybeAdd(gatherExternPropertiesCheck);
checks.maybeAdd(createEmptyPass(PassNames.BEFORE_SERIALIZATION));
if (options.getTypedAstOutputFile() != null) {
checks.maybeAdd(serializeTypedAst);
}
// Validation should be after all pass additions
checks.assertAllOneTimePasses();
assertValidOrderForChecks(checks);
return checks;
}
@Override
protected PassListBuilder getOptimizations() {
PassListBuilder passes = new PassListBuilder(options);
if (options.isPropertyRenamingOnlyCompilationMode()) {
passes.maybeAdd(removeUnnecessarySyntheticExterns);
TranspilationPasses.addTranspilationRuntimeLibraries(passes);
passes.maybeAdd(closureProvidesRequires);
passes.maybeAdd(processDefinesOptimize);
TranspilationPasses.addEarlyOptimizationTranspilationPasses(passes, options);
passes.maybeAdd(normalize);
TranspilationPasses.addPostNormalizationTranspilationPasses(passes, options);
passes.maybeAdd(gatherExternPropertiesOptimize);
passes.maybeAdd(createEmptyPass(PassNames.BEFORE_STANDARD_OPTIMIZATIONS));
passes.maybeAdd(inlineAndCollapseProperties);
passes.maybeAdd(closureOptimizePrimitives);
return passes;
}
if (options.skipNonTranspilationPasses) {
// Reaching this if-condition means the 'getChecks()' phase has been skipped in favor of
// 'getTranspileOnlyPasses'.
return passes;
}
if (options.getMergedPrecompiledLibraries()) {
// Weak sources aren't removed at the library level
passes.maybeAdd(removeWeakSources);
// it would be safe to always recompute side effects even if not using precompiled libraries
// (the else case) but it's unecessary so skip it to improve build times.
passes.maybeAdd(checkRegExpForOptimizations);
// This runs during getChecks(), so only needs to be run here if using precompiled .typedasts
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.maybeAdd(j2clSourceFileChecker);
}
} else {
addNonTypedAstNormalizationPasses(passes);
}
// Remove synthetic extern declarations of names that are now defined in source
// This is expected to do nothing when in a monolithic build
passes.maybeAdd(removeUnnecessarySyntheticExterns);
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.maybeAdd(j2clPass);
}
TranspilationPasses.addTranspilationRuntimeLibraries(passes);
if (options.rewritePolyfills || options.getIsolatePolyfills()) {
TranspilationPasses.addRewritePolyfillPass(passes);
}
passes.maybeAdd(injectRuntimeLibraries);
if (options.closurePass) {
passes.maybeAdd(closureProvidesRequires);
}
if (options.shouldRunReplaceMessagesForChrome()) {
passes.maybeAdd(replaceMessagesForChrome);
} else if (options.shouldRunReplaceMessagesPass()) {
if (options.doLateLocalization()) {
// With late localization we protect the messages from mangling by optimizations now,
// then actually replace them after optimizations.
// The purpose of doing this is to separate localization from optimization so we can
// optimize just once for all locales.
passes.maybeAdd(getProtectMessagesPass());
} else {
// TODO(bradfordcsmith): At the moment we expect the optimized output may be slightly
// smaller if you replace messages before optimizing, but if we can change that, it would
// be good to drop this early replacement entirely.
passes.maybeAdd(getFullReplaceMessagesPass());
}
}
if (options.doLateLocalization()) {
passes.maybeAdd(protectLocaleData);
}
// Replace 'goog.getCssName' before processing defines
if (options.closurePass && !options.shouldPreserveGoogLibraryPrimitives()) {
passes.maybeAdd(closureReplaceGetCssName);
}
// Defines in code always need to be processed.
passes.maybeAdd(processDefinesOptimize);
passes.maybeAdd(createEmptyPass(PassNames.BEFORE_EARLY_OPTIMIZATIONS_TRANSPILATION));
TranspilationPasses.addEarlyOptimizationTranspilationPasses(passes, options);
passes.maybeAdd(normalize);
TranspilationPasses.addPostNormalizationTranspilationPasses(passes, options);
passes.maybeAdd(gatherGettersAndSetters);
if (options.j2clPassMode.shouldAddJ2clPasses()) {
passes.maybeAdd(j2clUtilGetDefineRewriterPass);
}
if (options.getInstrumentForCoverageOption() != InstrumentOption.NONE) {
passes.maybeAdd(instrumentForCodeCoverage);
}
passes.maybeAdd(gatherExternPropertiesOptimize);
passes.maybeAdd(createEmptyPass(PassNames.BEFORE_STANDARD_OPTIMIZATIONS));
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.maybeAdd(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.maybeAdd(closureCodeRemoval);
}
if (options.removeJ2clAsserts) {
passes.maybeAdd(j2clAssertRemovalPass);
}
passes.maybeAdd(replaceToggles);
passes.maybeAdd(inlineAndCollapseProperties);
if (options.getTweakProcessing().shouldStrip()
|| !options.stripTypes.isEmpty()
|| !options.stripNameSuffixes.isEmpty()
|| !options.stripNamePrefixes.isEmpty()) {
passes.maybeAdd(stripCode);
}
if (options.replaceIdGenerators) {
passes.maybeAdd(replaceIdGenerators);
}
// Inline getters/setters in J2CL classes so that Object.defineProperties() calls (resulting
// from desugaring) don't block class stripping.
if (options.j2clPassMode.shouldAddJ2clPasses()
&& options.getPropertyCollapseLevel() == PropertyCollapseLevel.ALL) {
// Relies on collapseProperties-triggered aggressive alias inlining.
passes.maybeAdd(j2clPropertyInlinerPass);
}
if (options.inferConsts) {
passes.maybeAdd(inferConsts);
}
// Detects whether invocations of the method goog.string.Const.from are done with an argument
// which is a string literal. Needs to happen after inferConsts and collapseProperties.
// TODO(b/160616664): this should be in getChecks() instead of getOptimizations(). But
// for that the pass needs to understand constant properties as well. See b/31301233#comment10
passes.maybeAdd(checkConstParams);
// Running RemoveUnusedCode before disambiguate properties allows disambiguate properties to be
// more effective if code that would prevent disambiguation can be removed.
// TODO(b/66971163): Rename options since we're not actually using smartNameRemoval here now.
if (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.maybeAdd(earlyInlineVariables);
passes.maybeAdd(earlyPeepholeOptimizations);
}
passes.maybeAdd(removeUnusedCodeOnce);
}
// 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() && options.isTypecheckingEnabled()) {
passes.maybeAdd(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.maybeAdd(markPureFunctions);
}
passes.assertAllOneTimePasses();
if (options.smartNameRemoval) {
// Place one-time marker passes around this loop to prevent the addition of a looping pass
// above or below from accidentally becoming part of the loop.
passes.maybeAdd(createEmptyPass(PassNames.BEFORE_EARLY_OPTIMIZATION_LOOP));
passes.addAll(getEarlyOptimizationLoopPasses());
// TODO(): Remove this early loop or rename the option that enables it
// to something more appropriate.
passes.maybeAdd(createEmptyPass(PassNames.AFTER_EARLY_OPTIMIZATION_LOOP));
}
// This needs to come after the inline constants pass, which is run within
// the code removing passes.
if (options.closurePass) {
passes.maybeAdd(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.maybeAdd(replaceStrings);
}
// TODO(user): This forces a first crack at crossChunkCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossChunkCodeMotion 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
// CrossChunkCodeMotion so we don't need to do this.
if (options.shouldRunCrossChunkCodeMotion()) {
passes.maybeAdd(crossModuleCodeMotion);
}
// 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.devirtualizeMethods) {
passes.maybeAdd(devirtualizeMethods);
}
if (options.customPasses != null) {
passes.maybeAdd(getCustomPasses(CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.maybeAdd(createEmptyPass(PassNames.BEFORE_MAIN_OPTIMIZATIONS));
// 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.maybeAdd(flowSensitiveInlineVariables);
}
passes.addAll(getMainOptimizationLoop());
passes.maybeAdd(createEmptyPass(PassNames.AFTER_MAIN_OPTIMIZATIONS));
// 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.maybeAdd(getCustomPasses(CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
assertValidOrderForOptimizations(passes);
return passes;
}
@Override
protected PassListBuilder getFinalizations() {
PassListBuilder passes = new PassListBuilder(options);
if (options.isPropertyRenamingOnlyCompilationMode()) {
if (options.rewriteGlobalDeclarationsForTryCatchWrapping
|| options.renamePrefixNamespace != null) {
passes.maybeAdd(rewriteGlobalDeclarationsForTryCatchWrapping);
}
passes.maybeAdd(renameProperties);
if (options.renamePrefixNamespace != null
&& options.chunkOutputType == ChunkOutputType.GLOBAL_NAMESPACE) {
if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(options.renamePrefixNamespace).matches()) {
throw new IllegalArgumentException(
"Illegal character in renamePrefixNamespace name: " + options.renamePrefixNamespace);
}
passes.maybeAdd(rescopeGlobalSymbols);
}
return passes;
}
if (options.doLateLocalization()) {
if (options.shouldRunReplaceMessagesPass()) {
passes.maybeAdd(getReplaceProtectedMessagesPass());
}
passes.maybeAdd(substituteLocaleData);
passes.maybeAdd(peepholeOptimizationsOnce);
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.maybeAdd(flowSensitiveInlineVariables);
// After inlining variable uses, some variables may be unused.
// If we're doing late localization, the simple code removal pass runs added below will clean
// those up. Otherwise, clean them up now.
if (!options.doLateLocalization() && shouldRunRemoveUnusedCode()) {
passes.maybeAdd(removeUnusedCodeOnce);
}
}
if (options.doLateLocalization()) {
passes.addAll(getPostL10nOptimizations());
}
passes.maybeAdd(createEmptyPass("beforeModuleMotion"));
if (options.shouldRunCrossChunkCodeMotion()) {
passes.maybeAdd(crossModuleCodeMotion);
}
if (options.shouldRunCrossChunkMethodMotion()) {
passes.maybeAdd(crossModuleMethodMotion);
}
passes.maybeAdd(createEmptyPass("afterModuleMotion"));
if (options.optimizeESClassConstructors && options.getOutputFeatureSet().contains(ES2015)) {
passes.maybeAdd(optimizeConstructors);
}
// Isolate injected polyfills from the global scope. Runs late in the optimization loop
// to take advantage of property renaming & RemoveUnusedCode, as this pass will increase code
// size by wrapping all potential polyfill usages.
if (options.getIsolatePolyfills()) {
passes.maybeAdd(isolatePolyfills);
}
if (options.collapseAnonymousFunctions) {
// TODO: b/197349249 - Maybe we should just move this pass after denormalization. It seems
// weird to convert from function expression to function declaration while we're still
// supposed to be in a normalized state. But it requires testing as perhaps some optimizations
// in that range will get affected if we skip this rewriting.
passes.maybeAdd(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.rewriteGlobalDeclarationsForTryCatchWrapping
// renamePrefixNamescape relies on rewriteGlobalDeclarationsForTryCatchWrapping
// to preserve semantics.
|| options.renamePrefixNamespace != null) {
passes.maybeAdd(rewriteGlobalDeclarationsForTryCatchWrapping);
}
// 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.maybeAdd(extractPrototypeMemberDeclarations);
}
if (options.shouldAmbiguateProperties()
&& options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED
&& options.isTypecheckingEnabled()) {
passes.maybeAdd(ambiguateProperties);
}
if (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED) {
passes.maybeAdd(renameProperties);
} else {
passes.maybeAdd(removePropertyRenamingCalls);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.maybeAdd(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.maybeAdd(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.maybeAdd(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (options.getAliasStringsMode() != AliasStringsMode.NONE) {
passes.maybeAdd(aliasStrings);
}
if (options.coalesceVariableNames) {
// Passes after this point can no longer depend on normalized AST
// assumptions because the code is marked as un-normalized
passes.maybeAdd(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.maybeAdd(peepholeOptimizationsOnce);
}
}
// Passes after this point can no longer depend on normalized AST assumptions.
passes.maybeAdd(markUnnormalized);
if (options.collapseVariableDeclarations) {
passes.maybeAdd(exploitAssign);
passes.maybeAdd(collapseVariableDeclarations);
}
// This pass works best after collapseVariableDeclarations.
passes.maybeAdd(denormalize);
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 ("x" -> "x$jscomp$1").
passes.maybeAdd(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.maybeAdd(renameVars);
}
if (options.labelRenaming) {
passes.maybeAdd(renameLabels);
}
if (options.foldConstants) {
passes.maybeAdd(latePeepholeOptimizations);
}
// If side-effects were protected, remove the protection now.
// Note that when using precompiled libraries we always run this pass regardless of the
// 'shouldProtectHiddenSideEffects' option: the library compilation may have run
// with side effect protection enabled even if the binary disables it, so we assume we may
// always need to strip side effect protection.
if (options.shouldProtectHiddenSideEffects() || options.getMergedPrecompiledLibraries()) {
passes.maybeAdd(stripSideEffectProtection);
}
if (options.renamePrefixNamespace != null
&& options.chunkOutputType == ChunkOutputType.GLOBAL_NAMESPACE) {
if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(options.renamePrefixNamespace).matches()) {
throw new IllegalArgumentException(
"Illegal character in renamePrefixNamespace name: " + options.renamePrefixNamespace);
}
passes.maybeAdd(rescopeGlobalSymbols);
}
// Raise to ES2015, if allowed
if (options.getOutputFeatureSet().contains(ES2015)) {
passes.maybeAdd(optimizeToEs6);
}
// Must run after all non-safety-check passes as the optimizations do not support modules.
if (options.chunkOutputType == ChunkOutputType.ES_MODULES) {
passes.maybeAdd(convertChunksToESModules);
}
// Safety checks. These should always be the last passes.
passes.maybeAdd(checkAstValidity);
passes.maybeAdd(varCheckValidity);
return passes;
}
private PassListBuilder getEarlyOptimizationLoopPasses() {
PassListBuilder earlyLoopPasses = new PassListBuilder(options);
if (options.inlineVariables || options.inlineLocalVariables) {
earlyLoopPasses.maybeAdd(inlineVariables);
} else if (options.inlineConstantVars) {
earlyLoopPasses.maybeAdd(inlineConstants);
}
if (options.collapseObjectLiterals) {
earlyLoopPasses.maybeAdd(collapseObjectLiterals);
}
if (shouldRunRemoveUnusedCode()) {
earlyLoopPasses.maybeAdd(removeUnusedCode);
}
if (options.foldConstants) {
earlyLoopPasses.maybeAdd(peepholeOptimizations);
}
if (options.removeUnreachableCode) {
earlyLoopPasses.maybeAdd(removeUnreachableCode);
}
earlyLoopPasses.assertAllLoopablePasses();
return earlyLoopPasses;
}
/**
* Add optimization passes that need to run after late localization has been done.
*
* <p>Once we've replaced message references with string constants and `goog.LOCALE` with a
* constant value, we need to re-run some optimizations, so they can throw away code for locales