-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Compiler.java
3737 lines (3279 loc) · 121 KB
/
Compiler.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 2004 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.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.javascript.jscomp.parsing.parser.FeatureSet.ES8_MODULES;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.debugging.sourcemap.SourceMapConsumerV3;
import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;
import com.google.javascript.jscomp.CompilerOptions.DevMode;
import com.google.javascript.jscomp.CoverageInstrumentationPass.CoverageReach;
import com.google.javascript.jscomp.CoverageInstrumentationPass.InstrumentOption;
import com.google.javascript.jscomp.SortingErrorManager.ErrorReportGenerator;
import com.google.javascript.jscomp.deps.BrowserModuleResolver;
import com.google.javascript.jscomp.deps.BrowserWithTransformedPrefixesModuleResolver;
import com.google.javascript.jscomp.deps.JsFileParser;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.jscomp.deps.ModuleLoader.ModuleResolverFactory;
import com.google.javascript.jscomp.deps.NodeModuleResolver;
import com.google.javascript.jscomp.deps.SortedDependencies.MissingProvideException;
import com.google.javascript.jscomp.deps.WebpackModuleResolver;
import com.google.javascript.jscomp.parsing.Config;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.jscomp.parsing.parser.trees.Comment;
import com.google.javascript.jscomp.resources.ResourceLoader;
import com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.InputId;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import javax.annotation.Nullable;
/**
* Compiler (and the other classes in this package) does the following:
* <ul>
* <li>parses JS code
* <li>checks for undefined variables
* <li>performs optimizations such as constant folding and constants inlining
* <li>renames variables (to short names)
* <li>outputs compact JavaScript code
* </ul>
*
* External variables are declared in 'externs' files. For instance, the file
* may include definitions for global javascript/browser objects such as
* window, document.
*
*/
// TODO(tbreisacher): Rename Compiler to JsCompiler and remove this suppression.
@SuppressWarnings("JavaLangClash")
public class Compiler extends AbstractCompiler implements ErrorHandler, SourceFileMapping {
static final DiagnosticType MODULE_DEPENDENCY_ERROR =
DiagnosticType.error("JSC_MODULE_DEPENDENCY_ERROR",
"Bad dependency: {0} -> {1}. "
+ "Modules must be listed in dependency order.");
static final DiagnosticType MISSING_ENTRY_ERROR = DiagnosticType.error(
"JSC_MISSING_ENTRY_ERROR",
"required entry point \"{0}\" never provided");
static final DiagnosticType MISSING_MODULE_ERROR = DiagnosticType.error(
"JSC_MISSING_MODULE_ERROR",
"unknown module \"{0}\" specified in entry point spec");
static final DiagnosticType INCONSISTENT_MODULE_DEFINITIONS = DiagnosticType.error(
"JSC_INCONSISTENT_MODULE_DEFINITIONS",
"Serialized module definitions are not consistent with the module definitions supplied in "
+ "the command line");
private static final String CONFIG_RESOURCE =
"com.google.javascript.jscomp.parsing.ParserConfig";
private static final String FILL_FILE_SUFFIX = "$fillFile";
CompilerOptions options = null;
private PassConfig passes = null;
// The externs inputs
private List<CompilerInput> externs;
// The source module graph, denoting dependencies between chunks.
private JSModuleGraph moduleGraph;
// The module loader for resolving paths into module URIs.
private ModuleLoader moduleLoader;
// Map of module names to module types - used for module rewriting
private final Map<String, CompilerInput.ModuleType> moduleTypesByName;
// error manager to which error management is delegated
private ErrorManager errorManager;
// Warnings guard for filtering warnings.
private WarningsGuard warningsGuard;
// Compile-time injected libraries. The node points to the last node of
// the library, so code can be inserted after.
private final Map<String, Node> injectedLibraries = new LinkedHashMap<>();
// Node of the final injected library. Future libraries will be injected
// after this node.
private Node lastInjectedLibrary;
// Parse tree root nodes
Node externsRoot;
Node jsRoot;
Node externAndJsRoot;
// Used for debugging; to see the compiled code between passes
private String lastJsSource = null;
private FeatureSet featureSet;
private final Map<InputId, CompilerInput> inputsById = new ConcurrentHashMap<>();
private transient IncrementalScopeCreator scopeCreator = null;
private ImmutableMap<String, String> inputPathByWebpackId;
/**
* Subclasses are responsible for loading sources that were not provided as explicit inputs to the
* compiler. For example, looking up sources referenced within sourcemaps.
*/
public static class ExternalSourceLoader {
public SourceFile loadSource(String filename) {
throw new RuntimeException("Cannot load without a valid loader.");
}
}
// Original sources referenced by the source maps.
private final ConcurrentHashMap<String, SourceFile> sourceMapOriginalSources =
new ConcurrentHashMap<>();
/** Configured {@link SourceMapInput}s, plus any source maps discovered in source files. */
ConcurrentHashMap<String, SourceMapInput> inputSourceMaps = new ConcurrentHashMap<>();
// Map from filenames to lists of all the comments in each file.
private Map<String, List<Comment>> commentsPerFile = new ConcurrentHashMap<>();
/** The source code map */
private SourceMap sourceMap;
/** The externs created from the exports. */
private String externExports = null;
/**
* Ids for function inlining so that each declared name remains
* unique.
*/
private int uniqueNameId = 0;
/**
* Whether to assume there are references to the RegExp Global object
* properties.
*/
private boolean hasRegExpGlobalReferences = true;
/** The function information map */
private FunctionInformationMap functionInformationMap;
/** Detects Google-specific coding conventions. */
CodingConvention defaultCodingConvention = new ClosureCodingConvention();
private JSTypeRegistry typeRegistry;
private volatile Config parserConfig = null;
private volatile Config externsParserConfig = null;
private ReverseAbstractInterpreter abstractInterpreter;
private TypeValidator typeValidator;
// The compiler can ask phaseOptimizer for things like which pass is currently
// running, or which functions have been changed by optimizations
private PhaseOptimizer phaseOptimizer = null;
public PerformanceTracker tracker;
// Types that have been forward declared
private Set<String> forwardDeclaredTypes = new HashSet<>();
private boolean typeCheckingHasRun = false;
// This error reporter gets the messages from the current Rhino parser or TypeRegistry.
private final ErrorReporter oldErrorReporter =
RhinoErrorReporter.forOldRhino(this);
/** Error strings used for reporting JSErrors */
public static final DiagnosticType OPTIMIZE_LOOP_ERROR = DiagnosticType.error(
"JSC_OPTIMIZE_LOOP_ERROR",
"Exceeded max number of optimization iterations: {0}");
public static final DiagnosticType MOTION_ITERATIONS_ERROR =
DiagnosticType.error("JSC_MOTION_ITERATIONS_ERROR",
"Exceeded max number of code motion iterations: {0}");
private final CompilerExecutor compilerExecutor = createCompilerExecutor();
/**
* Logger for the whole com.google.javascript.jscomp domain -
* setting configuration for this logger affects all loggers
* in other classes within the compiler.
*/
public static final Logger logger =
Logger.getLogger("com.google.javascript.jscomp");
private final PrintStream outStream;
private GlobalVarReferenceMap globalRefMap = null;
private volatile double progress = 0.0;
private String lastPassName;
private Set<String> externProperties = null;
private ImmutableMap<String, PropertyAccessKind> externGetterAndSetterProperties = null;
private ImmutableMap<String, PropertyAccessKind> sourceGetterAndSetterProperties = null;
private static final Joiner pathJoiner = Joiner.on(File.separator);
// Starts at 0, increases as "interesting" things happen.
// Nothing happens at time START_TIME, the first pass starts at time 1.
// The correctness of scope-change tracking relies on Node/getIntProp
// returning 0 if the custom attribute on a node hasn't been set.
private int changeStamp = 1;
private final Timeline<Node> changeTimeline = new Timeline<>();
private final Timeline<Node> deleteTimeline = new Timeline<>();
/**
* Creates a Compiler that reports errors and warnings to its logger.
*/
public Compiler() {
this((PrintStream) null);
}
/**
* Creates a Compiler that reports errors and warnings to an output stream.
*/
public Compiler(PrintStream outStream) {
addChangeHandler(recentChange);
this.outStream = outStream;
this.moduleTypesByName = new HashMap<>();
}
/**
* Creates a Compiler that uses a custom error manager.
*/
public Compiler(ErrorManager errorManager) {
this();
setErrorManager(errorManager);
}
/**
* Sets the error manager.
*
* @param errorManager the error manager, it cannot be {@code null}
*/
public void setErrorManager(ErrorManager errorManager) {
checkNotNull(errorManager, "the error manager cannot be null");
this.errorManager = new ThreadSafeDelegatingErrorManager(errorManager);
}
/**
* Creates a message formatter instance corresponding to the value of
* {@link CompilerOptions}.
*/
private MessageFormatter createMessageFormatter() {
boolean colorize = options.shouldColorizeErrorOutput();
return options.errorFormat.toFormatter(this, colorize);
}
/**
* Initializes the compiler options. It's called as part of a normal compile() job.
* Public for the callers that are not doing a normal compile() job.
*/
public void initOptions(CompilerOptions options) {
this.options = options;
this.setFeatureSet(options.getLanguageIn().toFeatureSet());
if (errorManager == null) {
if (this.outStream == null) {
setErrorManager(
new LoggerErrorManager(createMessageFormatter(), logger));
} else {
ImmutableSet.Builder<ErrorReportGenerator> builder = ImmutableSet.builder();
builder.add(
new PrintStreamErrorReportGenerator(
createMessageFormatter(), this.outStream, options.summaryDetailLevel));
builder.addAll(options.getExtraReportGenerators());
setErrorManager(new SortingErrorManager(builder.build()));
}
}
moduleLoader = ModuleLoader.EMPTY;
reconcileOptionsWithGuards();
// TODO(johnlenz): generally, the compiler should not be changing the options object
// provided by the user. This should be handled a different way.
// Turn off type-based optimizations when type checking is off
if (!options.isTypecheckingEnabled()) {
options.setUseTypesForLocalOptimization(false);
options.setUseTypesForOptimization(false);
}
if (options.legacyCodeCompile) {
options.setDisambiguateProperties(false);
options.setAmbiguateProperties(false);
options.useNonStrictWarningsGuard();
}
if (options.assumeForwardDeclaredForMissingTypes) {
this.forwardDeclaredTypes =
new AbstractSet<String>() {
@Override
public boolean contains(Object o) {
return true; // Report all types as forward declared types.
}
@Override
public boolean add(String e) {
return false;
}
@Override
public Iterator<String> iterator() {
return Collections.<String>emptySet().iterator();
}
@Override
public int size() {
return 0;
}
};
}
initWarningsGuard(options.getWarningsGuard());
}
public void printConfig(PrintStream printStream) {
printStream.println("==== Externs ====");
printStream.println(externs);
printStream.println("==== Inputs ====");
printStream.println(Iterables.toString(moduleGraph.getAllInputs()));
printStream.println("==== CompilerOptions ====");
printStream.println(options);
printStream.println("==== WarningsGuard ====");
printStream.println(warningsGuard);
}
void initWarningsGuard(WarningsGuard warningsGuard) {
this.warningsGuard =
new ComposeWarningsGuard(
new SuppressDocWarningsGuard(this, getDiagnosticGroups().getRegisteredGroups()),
warningsGuard);
}
/** When the CompilerOptions and its WarningsGuard overlap, reconcile any discrepancies. */
protected void reconcileOptionsWithGuards() {
// DiagnosticGroups override the plain checkTypes option.
if (options.enables(DiagnosticGroups.CHECK_TYPES)) {
options.checkTypes = true;
} else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {
options.checkTypes = false;
} else if (!options.checkTypes) {
// If DiagnosticGroups did not override the plain checkTypes
// option, and checkTypes is disabled, then turn off the
// parser type warnings.
options.setWarningLevel(
DiagnosticGroup.forType(
RhinoErrorReporter.TYPE_PARSE_ERROR),
CheckLevel.OFF);
}
if (options.checkGlobalThisLevel.isOn() && !options.disables(DiagnosticGroups.GLOBAL_THIS)) {
options.setWarningLevel(
DiagnosticGroups.GLOBAL_THIS,
options.checkGlobalThisLevel);
}
if (options.expectStrictModeInput()) {
options.setWarningLevel(
DiagnosticGroups.ES5_STRICT,
CheckLevel.ERROR);
}
// All passes must run the variable check. This synthesizes
// variables later so that the compiler doesn't crash. It also
// checks the externs file for validity. If you don't want to warn
// about missing variable declarations, we shut that specific
// error off.
if (!options.checkSymbols && !options.enables(DiagnosticGroups.CHECK_VARIABLES)) {
options.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF);
}
// If we're in transpile-only mode, we don't need to do checks for suspicious var usages.
// Since we still have to run VariableReferenceCheck before transpilation to check block-scoped
// variables, though, we disable the unnecessary warnings it produces relating to vars here.
if (options.skipNonTranspilationPasses && !options.enables(DiagnosticGroups.CHECK_VARIABLES)) {
options.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF);
}
}
/** Initializes the instance state needed for a compile job. */
public final <T1 extends SourceFile, T2 extends SourceFile> void init(
List<T1> externs, List<T2> sources, CompilerOptions options) {
JSModule module = new JSModule(JSModule.STRONG_MODULE_NAME);
for (SourceFile source : sources) {
module.add(new CompilerInput(source));
}
List<JSModule> modules = new ArrayList<>(1);
modules.add(module);
initModules(externs, modules, options);
addFilesToSourceMap(sources);
}
/**
* Initializes the instance state needed for a compile job if the sources
* are in modules.
*/
public <T extends SourceFile> void initModules(
List<T> externs, List<JSModule> modules, CompilerOptions options) {
initOptions(options);
checkFirstModule(modules);
modules = moveWeakSources(modules);
fillEmptyModules(modules);
this.externs = makeExternInputs(externs);
// Generate the module graph, and report any errors in the module specification as errors.
try {
this.moduleGraph = new JSModuleGraph(modules);
} catch (JSModuleGraph.ModuleDependenceException e) {
// problems with the module format. Report as an error. The
// message gives all details.
report(JSError.make(MODULE_DEPENDENCY_ERROR,
e.getModule().getName(), e.getDependentModule().getName()));
return;
}
this.commentsPerFile = new ConcurrentHashMap<>(moduleGraph.getInputCount());
initBasedOnOptions();
initInputsByIdMap();
initAST();
}
/**
* Exists only for some tests that want to reuse JSModules.
* @deprecated Fix those tests.
*/
@Deprecated
public void breakThisCompilerSoItsModulesCanBeReused() {
moduleGraph.breakThisGraphSoItsModulesCanBeReused();
moduleGraph = null;
}
/**
* Do any initialization that is dependent on the compiler options.
*/
public void initBasedOnOptions() {
inputSourceMaps.putAll(options.inputSourceMaps);
// Create the source map if necessary.
if (options.sourceMapOutputPath != null) {
sourceMap = options.sourceMapFormat.getInstance();
sourceMap.setPrefixMappings(options.sourceMapLocationMappings);
if (options.applyInputSourceMaps) {
sourceMap.setSourceFileMapping(this);
if (options.sourceMapIncludeSourcesContent) {
for (SourceMapInput inputSourceMap : inputSourceMaps.values()) {
addSourceMapSourceFiles(inputSourceMap);
}
}
}
}
}
private <T extends SourceFile> List<CompilerInput> makeExternInputs(List<T> externSources) {
List<CompilerInput> inputs = new ArrayList<>(externSources.size());
for (SourceFile file : externSources) {
inputs.add(new CompilerInput(file, /* isExtern= */ true));
}
return inputs;
}
private static final DiagnosticType EMPTY_MODULE_LIST_ERROR =
DiagnosticType.error("JSC_EMPTY_MODULE_LIST_ERROR",
"At least one module must be provided");
private static final DiagnosticType EMPTY_ROOT_MODULE_ERROR =
DiagnosticType.error("JSC_EMPTY_ROOT_MODULE_ERROR",
"Root module ''{0}'' must contain at least one source code input");
/**
* Verifies that at least one module has been provided and that the first one
* has at least one source code input.
*/
private void checkFirstModule(List<JSModule> modules) {
if (modules.isEmpty()) {
report(JSError.make(EMPTY_MODULE_LIST_ERROR));
} else if (modules.get(0).getInputs().isEmpty() && modules.size() > 1) {
// The root module may only be empty if there is exactly 1 module.
report(JSError.make(EMPTY_ROOT_MODULE_ERROR,
modules.get(0).getName()));
}
}
/** Moves all weak sources into a separate weak module that depends on every other module. */
private List<JSModule> moveWeakSources(List<JSModule> modules) {
// Collect weak sources.
List<CompilerInput> weakInputs = new ArrayList<>();
for (JSModule module : modules) {
if (module.getName().equals(JSModule.WEAK_MODULE_NAME)) {
// Skip an already existing weak module - see below.
continue;
}
for (int i = 0; i < module.getInputCount(); ) {
CompilerInput input = module.getInput(i);
if (input.getSourceFile().isWeak()) {
module.remove(input);
weakInputs.add(input);
} else {
i++;
}
}
}
// If a weak module already exists (e.g. in a stage 2 compilation), make sure it contains all
// weak sources, but leave the module graph otherwise untouched.
if (moduleGraph != null
&& moduleGraph.getModuleByName(JSModule.WEAK_MODULE_NAME) != null
&& !weakInputs.isEmpty()) {
throw new RuntimeException(
"A weak module already exists but weak sources were found in other modules.");
}
// Create the weak module and make it depend on every other module.
JSModule weakModule = new JSModule(JSModule.WEAK_MODULE_NAME);
for (JSModule module : modules) {
weakModule.addDependency(module);
}
// Move the weak sources.
for (CompilerInput input : weakInputs) {
weakModule.add(input);
}
// Make a copy in case the original list is immutable.
modules = ImmutableList.<JSModule>builder().addAll(modules).add(weakModule).build();
return modules;
}
/**
* Empty modules get an empty "fill" file, so that we can move code into
* an empty module.
*/
static String createFillFileName(String moduleName) {
return moduleName + FILL_FILE_SUFFIX;
}
/** Returns whether a file name was created by {@link createFillFileName}. */
static boolean isFillFileName(String fileName) {
return fileName.endsWith(FILL_FILE_SUFFIX);
}
/**
* Creates an OS specific path string from parts
*/
public static String joinPathParts(String... pathParts) {
return pathJoiner.join(pathParts);
}
/** Fill any empty modules with a place holder file. It makes any cross module motion easier. */
private static void fillEmptyModules(Iterable<JSModule> modules) {
for (JSModule module : modules) {
if (!module.getName().equals(JSModule.WEAK_MODULE_NAME) && module.getInputs().isEmpty()) {
module.add(SourceFile.fromCode(createFillFileName(module.getName()), ""));
}
}
}
/**
* Rebuilds the internal input map by iterating over all modules. This is necessary if inputs have
* been added to or removed from a module after an {@link #init} or {@link #initModules} call.
*/
public void rebuildInputsFromModules() {
initInputsByIdMap();
}
static final DiagnosticType DUPLICATE_INPUT =
DiagnosticType.error("JSC_DUPLICATE_INPUT", "Duplicate input: {0}");
static final DiagnosticType DUPLICATE_EXTERN_INPUT =
DiagnosticType.error("JSC_DUPLICATE_EXTERN_INPUT",
"Duplicate extern input: {0}");
/**
* Creates a map to make looking up an input by name fast. Also checks for
* duplicate inputs.
*/
void initInputsByIdMap() {
inputsById.clear();
for (CompilerInput input : externs) {
InputId id = input.getInputId();
CompilerInput previous = putCompilerInput(id, input);
if (previous != null) {
report(JSError.make(DUPLICATE_EXTERN_INPUT, input.getName()));
}
}
for (CompilerInput input : moduleGraph.getAllInputs()) {
InputId id = input.getInputId();
CompilerInput previous = putCompilerInput(id, input);
if (previous != null) {
report(JSError.make(DUPLICATE_INPUT, input.getName()));
}
}
}
/**
* Sets up the skeleton of the AST (the externs and root).
*/
private void initAST() {
jsRoot = IR.root();
externsRoot = IR.root();
externAndJsRoot = IR.root(externsRoot, jsRoot);
}
/** Compiles a single source file and a single externs file. */
public Result compile(SourceFile extern, SourceFile input, CompilerOptions options) {
return compile(ImmutableList.of(extern), ImmutableList.of(input), options);
}
/**
* Compiles a list of inputs.
*
* <p>This is a convenience method to wrap up all the work of compilation, including
* generating the error and warning report.
*
* <p>NOTE: All methods called here must be public, because client code must be able to replicate
* and customize this.
*/
public <T1 extends SourceFile, T2 extends SourceFile> Result compile(
List<T1> externs, List<T2> inputs, CompilerOptions options) {
// The compile method should only be called once.
checkState(jsRoot == null);
try {
init(externs, inputs, options);
if (options.printConfig) {
printConfig(System.err);
}
if (!hasErrors()) {
parseForCompilation();
}
if (!hasErrors()) {
if (options.getInstrumentForCoverageOnly()) {
// TODO(bradfordcsmith): The option to instrument for coverage only should belong to the
// runner, not the compiler.
instrumentForCoverage();
} else {
stage1Passes();
if (!hasErrors()) {
stage2Passes();
}
}
performPostCompilationTasks();
}
} finally {
generateReport();
}
return getResult();
}
/**
* Generates a report of all warnings and errors found during compilation to stderr.
*
* <p>Client code must call this method explicitly if it doesn't use one of the convenience
* methods that do so automatically.
* <p>Always call this method, even if the compiler throws an exception. The report will include
* information about the exception.
*/
public void generateReport() {
Tracer t = newTracer("generateReport");
errorManager.generateReport();
stopTracer(t, "generateReport");
}
/**
* Compiles a list of modules.
*
* <p>This is a convenience method to wrap up all the work of compilation, including
* generating the error and warning report.
*
* <p>NOTE: All methods called here must be public, because client code must be able to replicate
* and customize this.
*/
public <T extends SourceFile> Result compileModules(
List<T> externs, List<JSModule> modules, CompilerOptions options) {
// The compile method should only be called once.
checkState(jsRoot == null);
try {
initModules(externs, modules, options);
if (options.printConfig) {
printConfig(System.err);
}
if (!hasErrors()) {
parseForCompilation();
}
if (!hasErrors()) {
// TODO(bradfordcsmith): The option to instrument for coverage only should belong to the
// runner, not the compiler.
if (options.getInstrumentForCoverageOnly()) {
instrumentForCoverage();
} else {
stage1Passes();
if (!hasErrors()) {
stage2Passes();
}
}
performPostCompilationTasks();
}
} finally {
generateReport();
}
return getResult();
}
/**
* Perform compiler passes for stage 1 of compilation.
*
* <p>Stage 1 consists primarily of error and type checking passes.
*
* <p>{@code parseForCompilation()} must be called before this method is called.
*
* <p>The caller is responsible for also calling {@code generateReport()} to generate a report of
* warnings and errors to stderr. See the invocation in {@link #compile} for a good example.
*/
public void stage1Passes() {
checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?");
checkState(!hasErrors());
checkState(!options.getInstrumentForCoverageOnly());
runInCompilerThread(
new Callable<Void>() {
@Override
public Void call() throws Exception {
performChecksAndTranspilation();
return null;
}
});
}
/**
* Perform compiler passes for stage 2 of compilation.
*
* <p>Stage 2 consists primarily of optimization passes.
*
* <p>{@code stage1Passes()} must be called before this method is called.
*
* <p>The caller is responsible for also calling {@code generateReport()} to generate a report of
* warnings and errors to stderr. See the invocation in {@link #compile} for a good example.
*/
public void stage2Passes() {
checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?");
checkState(!hasErrors());
checkState(!options.getInstrumentForCoverageOnly());
runInCompilerThread(
new Callable<Void>() {
@Override
public Void call() throws Exception {
if (options.shouldOptimize()) {
performOptimizations();
}
return null;
}
});
}
/**
* Disable threads. This is for clients that run on AppEngine and
* don't have threads.
*/
public void disableThreads() {
compilerExecutor.disableThreads();
}
/**
* Sets the timeout when Compiler is run in a thread
* @param timeout seconds to wait before timeout
*/
public void setTimeout(int timeout) {
compilerExecutor.setTimeout(timeout);
}
/**
* The primary purpose of this method is to run the provided code with a larger than standard
* stack.
*/
<T> T runInCompilerThread(Callable<T> callable) {
return compilerExecutor.runInCompilerThread(
callable, options != null && options.getTracerMode().isOn());
}
private void performChecksAndTranspilation() {
if (options.skipNonTranspilationPasses) {
// i.e. whitespace-only mode, which will not work with goog.module without:
whitespaceOnlyPasses();
if (options.needsTranspilationFrom(options.getLanguageIn().toFeatureSet())) {
transpileAndDontCheck();
}
} else {
check(); // check() also includes transpilation
}
}
/**
* Performs all the bookkeeping required at the end of a compilation.
*
* <p>This method must be called if the compilation makes it as far as doing checks.
* <p> DON'T call it if the compiler threw an exception.
* <p> DO call it even when {@code hasErrors()} returns true.
*/
public void performPostCompilationTasks() {
runInCompilerThread(new Callable<Void>() {
@Override
public Void call() throws Exception {
performPostCompilationTasksInternal();
return null;
}
});
}
/**
* Performs all the bookkeeping required at the end of a compilation.
*/
private void performPostCompilationTasksInternal() {
if (options.recordFunctionInformation) {
recordFunctionInformation();
}
if (options.devMode == DevMode.START_AND_END) {
runValidityCheck();
}
setProgress(1.0, "recordFunctionInformation");
if (tracker != null) {
tracker.outputTracerReport();
}
}
/**
* Instrument code for coverage.
*
* <p>{@code parseForCompilation()} must be called before this method is called.
*
* <p>The caller is responsible for also calling {@code generateReport()} to generate a report of
* warnings and errors to stderr. See the invocation in {@link #compile} for a good example.
*
* <p>This method is mutually exclusive with stage1Passes() and stage2Passes().
* Either call those two methods or this one, but not both.
*/
public void instrumentForCoverage() {
checkState(moduleGraph != null, "No inputs. Did you call init() or initModules()?");
checkState(!hasErrors());
runInCompilerThread(
new Callable<Void>() {
@Override
public Void call() throws Exception {
checkState(options.getInstrumentForCoverageOnly());
checkState(!hasErrors());
instrumentForCoverageInternal(options.instrumentBranchCoverage);
return null;
}
});
}
private void instrumentForCoverageInternal(boolean instrumentBranchCoverage) {
Tracer tracer = newTracer("instrumentationPass");
InstrumentOption instrumentOption = InstrumentOption.LINE_ONLY;
if (instrumentBranchCoverage) {
instrumentOption = InstrumentOption.BRANCH_ONLY;
}
process(new CoverageInstrumentationPass(this, CoverageReach.ALL, instrumentOption));
stopTracer(tracer, "instrumentationPass");
}
/**
* Parses input files in preparation for compilation.
*
* <p>Either {@code init()} or {@code initModules()} must be called first to set up the input
* files to be read.
* <p>TODO(bradfordcsmith): Rename this to parse()
*/
public void parseForCompilation() {
runInCompilerThread(
new Callable<Void>() {
@Override
public Void call() throws Exception {
parseForCompilationInternal();
return null;
}
});
}
/**
* Parses input files in preparation for compilation.
*
* <p>Either {@code init()} or {@code initModules()} must be called first to set up the input
* files to be read.
*
* <p>TODO(bradfordcsmith): Rename this to parse()
*/
private void parseForCompilationInternal() {
setProgress(0.0, null);
CompilerOptionsPreprocessor.preprocess(options);
maybeSetTracker();
parseInputs();
// Guesstimate.
setProgress(0.15, "parse");
}
/**
* Parses input files without doing progress tracking that is part of a full compile.
*
* <p>Either {@code init()} or {@code initModules()} must be called first to set up the input
* files to be read.
* <p>TODO(bradfordcsmith): Rename this to parseIndependentOfCompilation() or similar.
*/
public void parse() {
parseInputs();
}
public Node parse(SourceFile file) {
initCompilerOptionsIfTesting();
logger.finest("Parsing: " + file.getName());
return new JsAst(file).getAstRoot(this);
}