-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Compiler.java
2897 lines (2510 loc) · 86.9 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 com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
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.debugging.sourcemap.proto.Mapping.OriginalMapping;
import com.google.javascript.jscomp.CompilerOptions.DevMode;
import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection;
import com.google.javascript.jscomp.TypeValidator.TypeMismatch;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.jscomp.deps.SortedDependencies.MissingProvideException;
import com.google.javascript.jscomp.parsing.Config;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.jscomp.parsing.parser.trees.Comment;
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.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TypeIRegistry;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
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;
/**
* 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.
*
*/
public class Compiler extends AbstractCompiler implements ErrorHandler, SourceFileMapping {
static final String SINGLETON_MODULE_NAME = "$singleton$";
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_ENTRY_ERROR",
"unknown module \"{0}\" specified in entry point spec");
// Used in PerformanceTracker
static final String PARSING_PASS_NAME = "parseInputs";
static final String CROSS_MODULE_CODE_MOTION_NAME = "crossModuleCodeMotion";
static final String CROSS_MODULE_METHOD_MOTION_NAME =
"crossModuleMethodMotion";
private static final String CONFIG_RESOURCE =
"com.google.javascript.jscomp.parsing.ParserConfig";
CompilerOptions options = null;
private PassConfig passes = null;
// The externs inputs
private List<CompilerInput> externs;
// The JS source modules
private List<JSModule> modules;
// The graph of the JS source modules. Must be null if there are less than
// 2 modules, because we use this as a signal for which passes to run.
private JSModuleGraph moduleGraph;
// The module loader for resolving paths into module URIs.
private ModuleLoader moduleLoader;
// The JS source inputs
private List<CompilerInput> inputs;
// 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;
/** @see #getLanguageMode() */
private CompilerOptions.LanguageMode languageMode =
CompilerOptions.LanguageMode.ECMASCRIPT3;
private Map<InputId, CompilerInput> inputsById;
// Function to load source files from disk or memory.
private Function<String, SourceFile> originalSourcesLoader =
new Function<String, SourceFile>() {
@Override
public SourceFile apply(String filename) {
return SourceFile.fromFile(filename);
}
};
// Original sources referenced by the source maps.
private ConcurrentHashMap<String, SourceFile> sourceMapOriginalSources
= new ConcurrentHashMap<>();
/** Configured {@link SourceMapInput}s, plus any source maps discovered in source files. */
private final 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 HashMap<>();
/** 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;
/** Debugging information */
private final StringBuilder debugLog = new StringBuilder();
/** Detects Google-specific coding conventions. */
CodingConvention defaultCodingConvention = new ClosureCodingConvention();
private JSTypeRegistry typeRegistry;
private Config parserConfig = null;
private 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;
// Used by optimize-returns, optimize-parameters and remove-unused-variables
private DefinitionUseSiteFinder defFinder = null;
// Types that have been forward declared
private final Set<String> forwardDeclaredTypes = new HashSet<>();
// For use by the new type inference
private GlobalTypeInfo symbolTable;
private MostRecentTypechecker mostRecentTypechecker = MostRecentTypechecker.NONE;
// 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_OPTIMIZE_LOOP_ERROR",
"Exceeded max number of code motion iterations: {0}");
private final CompilerExecutor compilerExecutor = new CompilerExecutor();
/**
* Logger for the whole com.google.javascript.jscomp domain -
* setting configuration for this logger affects all loggers
* in other classes within the compiler.
*/
private 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 static final Joiner pathJoiner = Joiner.on(File.separator);
/**
* 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 stream) {
addChangeHandler(recentChange);
this.outStream = stream;
}
/**
* 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) {
Preconditions.checkNotNull(
errorManager, "the error manager cannot be null");
this.errorManager = 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);
}
@VisibleForTesting
void setOriginalSourcesLoader(
Function<String, SourceFile> originalSourcesLoader) {
this.originalSourcesLoader = originalSourcesLoader;
}
/**
* 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.languageMode = options.getLanguageIn();
if (errorManager == null) {
if (this.outStream == null) {
setErrorManager(
new LoggerErrorManager(createMessageFormatter(), logger));
} else {
PrintStreamErrorManager printer =
new PrintStreamErrorManager(createMessageFormatter(), this.outStream);
printer.setSummaryDetailLevel(options.summaryDetailLevel);
setErrorManager(printer);
}
}
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.checkTypes) {
options.setDisambiguateProperties(false);
options.setAmbiguateProperties(false);
options.setInlineProperties(false);
options.setUseTypesForLocalOptimization(false);
options.setUseTypesForOptimization(false);
}
if (options.legacyCodeCompile) {
options.setDisambiguateProperties(false);
options.setAmbiguateProperties(false);
options.useNonStrictWarningsGuard();
}
initWarningsGuard(options.getWarningsGuard());
}
public void printConfig(PrintStream printStream) {
printStream.println("==== CompilerOptions ====");
printStream.println(options.toString());
printStream.println("==== WarningsGuard ====");
printStream.println(warningsGuard.toString());
}
void initWarningsGuard(WarningsGuard warningsGuard) {
this.warningsGuard = new ComposeWarningsGuard(
new SuppressDocWarningsGuard(getDiagnosticGroups().getRegisteredGroups()), warningsGuard);
}
/**
* When the CompilerOptions and its WarningsGuard overlap, reconcile
* any discrepencies.
*/
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 enabled, then turn off the
// parser type warnings.
options.setWarningLevel(
DiagnosticGroup.forType(
RhinoErrorReporter.TYPE_PARSE_ERROR),
CheckLevel.OFF);
}
// With NTI, we still need OTI to run because the later passes that use
// types only understand OTI types at the moment.
// But we do not want to see the warnings from OTI.
if (options.getNewTypeInference()) {
options.checkTypes = true;
// Supress warnings from the const checks of CheckAccessControls so as to avoid
// duplication.
options.setWarningLevel(DiagnosticGroups.ACCESS_CONTROLS_CONST, CheckLevel.OFF);
if (!options.reportOTIErrorsUnderNTI) {
options.setWarningLevel(
DiagnosticGroups.OLD_CHECK_TYPES,
CheckLevel.OFF);
options.setWarningLevel(
DiagnosticGroups.OLD_REPORT_UNKNOWN_TYPES,
CheckLevel.OFF);
options.setWarningLevel(
FunctionTypeBuilder.ALL_DIAGNOSTICS,
CheckLevel.OFF);
}
options.setWarningLevel(
DiagnosticGroup.forType(RhinoErrorReporter.TYPE_PARSE_ERROR),
CheckLevel.WARNING);
}
if (options.checkGlobalThisLevel.isOn() &&
!options.disables(DiagnosticGroups.GLOBAL_THIS)) {
options.setWarningLevel(
DiagnosticGroups.GLOBAL_THIS,
options.checkGlobalThisLevel);
}
if (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);
}
}
private boolean expectStrictModeInput() {
switch (options.getLanguageIn()) {
case ECMASCRIPT3:
case ECMASCRIPT5:
case ECMASCRIPT6:
return false;
case ECMASCRIPT5_STRICT:
case ECMASCRIPT6_STRICT:
case ECMASCRIPT6_TYPED:
return true;
default:
return options.isStrictModeInput();
}
}
/**
* Initializes the instance state needed for a compile job.
*/
public <T1 extends SourceFile, T2 extends SourceFile> void init(
List<T1> externs,
List<T2> inputs,
CompilerOptions options) {
JSModule module = new JSModule(SINGLETON_MODULE_NAME);
for (SourceFile input : inputs) {
module.add(input);
}
List<JSModule> modules = new ArrayList<>(1);
modules.add(module);
initModules(externs, modules, options);
addFilesToSourceMap(inputs);
if (options.printConfig) {
printConfig(System.err);
}
}
/**
* 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);
fillEmptyModules(modules);
this.externs = makeCompilerInput(externs, true);
// Generate the module graph, and report any errors in the module
// specification as errors.
this.modules = modules;
if (modules.size() > 1) {
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;
}
} else {
this.moduleGraph = null;
}
this.inputs = getAllInputsFromModules(modules);
initBasedOnOptions();
initInputsByIdMap();
initAST();
}
/**
* Do any initialization that is dependent on the compiler options.
*/
private 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);
}
}
}
private <T extends SourceFile> List<CompilerInput> makeCompilerInput(
List<T> files, boolean isExtern) {
List<CompilerInput> inputs = new ArrayList<>(files.size());
for (T file : files) {
inputs.add(new CompilerInput(file, isExtern));
}
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()));
}
}
/**
* Empty modules get an empty "fill" file, so that we can move code into
* an empty module.
*/
static String createFillFileName(String moduleName) {
return moduleName + "$fillFile";
}
/**
* 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(List<JSModule> modules) {
for (JSModule module : modules) {
if (module.getInputs().isEmpty()) {
module.add(SourceFile.fromCode(
createFillFileName(module.getName()), ""));
}
}
}
/**
* Rebuilds the internal list of inputs by iterating over all modules.
* This is necessary if inputs have been added to or removed from a module
* after the {@link #init(List, List, CompilerOptions)} call.
*/
public void rebuildInputsFromModules() {
inputs = getAllInputsFromModules(modules);
initInputsByIdMap();
}
/**
* Builds a single list of all module inputs. Verifies that it contains no
* duplicates.
*/
private static List<CompilerInput> getAllInputsFromModules(
List<JSModule> modules) {
List<CompilerInput> inputs = new ArrayList<>();
Map<String, JSModule> inputMap = new HashMap<>();
for (JSModule module : modules) {
for (CompilerInput input : module.getInputs()) {
String inputName = input.getName();
// NOTE(nicksantos): If an input is in more than one module,
// it will show up twice in the inputs list, and then we
// will get an error down the line.
inputs.add(input);
inputMap.put(inputName, module);
}
}
return inputs;
}
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}");
/**
* Returns the relative path, resolved relative to the base path, where the
* base path is interpreted as a filename rather than a directory. E.g.:
* getRelativeTo("../foo/bar.js", "baz/bam/qux.js") --> "baz/foo/bar.js"
*/
private static String getRelativeTo(String relative, String base) {
return FileSystems.getDefault().getPath(base)
.resolveSibling(relative)
.normalize()
.toString()
.replace(File.separator, "/");
}
/**
* Creates a map to make looking up an input by name fast. Also checks for
* duplicate inputs.
*/
void initInputsByIdMap() {
inputsById = new HashMap<>();
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 : inputs) {
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.block();
jsRoot.setIsSyntheticBlock(true);
externsRoot = IR.block();
externsRoot.setIsSyntheticBlock(true);
externAndJsRoot = IR.block(externsRoot, jsRoot);
externAndJsRoot.setIsSyntheticBlock(true);
}
public Result compile(
SourceFile extern, SourceFile input, CompilerOptions options) {
return compile(ImmutableList.of(extern), ImmutableList.of(input), options);
}
/**
* Compiles a list of inputs.
*/
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.
Preconditions.checkState(jsRoot == null);
try {
init(externs, inputs, options);
if (hasErrors()) {
return getResult();
}
return compile();
} finally {
Tracer t = newTracer("generateReport");
errorManager.generateReport();
stopTracer(t, "generateReport");
}
}
/**
* Compiles a list of modules.
*/
public <T extends SourceFile> Result compileModules(List<T> externs,
List<JSModule> modules, CompilerOptions options) {
// The compile method should only be called once.
Preconditions.checkState(jsRoot == null);
try {
initModules(externs, modules, options);
if (hasErrors()) {
return getResult();
}
return compile();
} finally {
Tracer t = newTracer("generateReport");
errorManager.generateReport();
stopTracer(t, "generateReport");
}
}
private Result compile() {
return runInCompilerThread(new Callable<Result>() {
@Override
public Result call() throws Exception {
compileInternal();
return getResult();
}
});
}
/**
* 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.tracer.isOn());
}
private void compileInternal() {
setProgress(0.0, null);
CompilerOptionsPreprocessor.preprocess(options);
parse();
// 15 percent of the work is assumed to be for parsing (based on some
// minimal analysis on big JS projects, of course this depends on options)
setProgress(0.15, "parse");
if (hasErrors()) {
return;
}
if (!precheck()) {
return;
}
if (options.skipNonTranspilationPasses) {
// i.e. whitespace-only mode, which will not work with goog.module without:
whitespaceOnlyPasses();
if (options.lowerFromEs6()) {
transpileAndDontCheck();
}
} else {
check(); // check() also includes transpilation
if (hasErrors()) {
return;
}
if (!options.checksOnly && !options.shouldGenerateTypedExterns()) {
optimize();
}
}
if (options.recordFunctionInformation) {
recordFunctionInformation();
}
if (options.devMode == DevMode.START_AND_END) {
runSanityCheck();
}
setProgress(1.0, "recordFunctionInformation");
if (tracker != null) {
tracker.outputTracerReport();
}
}
public void parse() {
parseInputs();
}
PassConfig getPassConfig() {
if (passes == null) {
passes = createPassConfigInternal();
}
return passes;
}
/**
* Create the passes object. Clients should use setPassConfig instead of
* overriding this.
*/
PassConfig createPassConfigInternal() {
return new DefaultPassConfig(options);
}
/**
* @param passes The PassConfig to use with this Compiler.
* @throws NullPointerException if passes is null
* @throws IllegalStateException if this.passes has already been assigned
*/
public void setPassConfig(PassConfig passes) {
// Important to check for null because if setPassConfig(null) is
// called before this.passes is set, getPassConfig() will create a
// new PassConfig object and use that, which is probably not what
// the client wanted since they probably meant to use their
// own PassConfig object.
Preconditions.checkNotNull(passes);
Preconditions.checkState(this.passes == null, "setPassConfig was already called");
this.passes = passes;
}
/**
* Carry out any special checks or procedures that need to be done before
* proceeding with rest of the compilation process.
*
* @return true, to continue with compilation
*/
boolean precheck() {
return true;
}
public void whitespaceOnlyPasses() {
runCustomPasses(CustomPassExecutionTime.BEFORE_CHECKS);
Tracer t = newTracer("runWhitespaceOnlyPasses");
try {
for (PassFactory pf : getPassConfig().getWhitespaceOnlyPasses()) {
pf.create(this).process(externsRoot, jsRoot);
}
} finally {
stopTracer(t, "runWhitespaceOnlyPasses");
}
}
public void transpileAndDontCheck() {
Tracer t = newTracer("runTranspileOnlyPasses");
try {
for (PassFactory pf : getPassConfig().getTranspileOnlyPasses()) {
pf.create(this).process(externsRoot, jsRoot);
}
} finally {
stopTracer(t, "runTranspileOnlyPasses");
}
}
public void check() {
runCustomPasses(CustomPassExecutionTime.BEFORE_CHECKS);
// We are currently only interested in check-passes for progress reporting
// as it is used for IDEs, that's why the maximum progress is set to 1.0.
phaseOptimizer = new PhaseOptimizer(this, tracker,
new PhaseOptimizer.ProgressRange(getProgress(), 1.0));
if (options.devMode == DevMode.EVERY_PASS) {
phaseOptimizer.setSanityCheck(sanityCheck);
}
if (options.getCheckDeterminism()) {
phaseOptimizer.setPrintAstHashcodes(true);
}
phaseOptimizer.consume(getPassConfig().getChecks());
phaseOptimizer.process(externsRoot, jsRoot);
if (hasErrors()) {
return;
}
if (options.getTweakProcessing().shouldStrip() ||
!options.stripTypes.isEmpty() ||
!options.stripNameSuffixes.isEmpty() ||
!options.stripTypePrefixes.isEmpty() ||
!options.stripNamePrefixes.isEmpty()) {
stripCode(options.stripTypes, options.stripNameSuffixes,
options.stripTypePrefixes, options.stripNamePrefixes);
}
runCustomPasses(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS);
phaseOptimizer = null;
}
private void externExports() {
logger.fine("Creating extern file for exports");
startPass("externExports");
ExternExportsPass pass = new ExternExportsPass(this);
process(pass);
externExports = pass.getGeneratedExterns();
endPass();
}
@Override
void process(CompilerPass p) {
p.process(externsRoot, jsRoot);
}
private final PassFactory sanityCheck =
new PassFactory("sanityCheck", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new SanityCheck(compiler);
}
};
private void maybeSanityCheck() {
if (options.devMode == DevMode.EVERY_PASS) {
runSanityCheck();
}
}
private void runSanityCheck() {
sanityCheck.create(this).process(externsRoot, jsRoot);
}
/**
* Strips code for smaller compiled code. This is useful for removing debug
* statements to prevent leaking them publicly.
*/
void stripCode(Set<String> stripTypes, Set<String> stripNameSuffixes,
Set<String> stripTypePrefixes, Set<String> stripNamePrefixes) {
logger.fine("Strip code");
startPass("stripCode");
StripCode r = new StripCode(this, stripTypes, stripNameSuffixes,
stripTypePrefixes, stripNamePrefixes);
if (options.getTweakProcessing().shouldStrip()) {
r.enableTweakStripping();
}
process(r);
endPass();
}
/**
* Runs custom passes that are designated to run at a particular time.
*/
private void runCustomPasses(CustomPassExecutionTime executionTime) {
if (options.customPasses != null) {
Tracer t = newTracer("runCustomPasses");
try {
for (CompilerPass p : options.customPasses.get(executionTime)) {
process(p);
}
} finally {
stopTracer(t, "runCustomPasses");
}
}
}
private Tracer currentTracer = null;
private String currentPassName = null;
/**
* Marks the beginning of a pass.
*/
void startPass(String passName) {
Preconditions.checkState(currentTracer == null);
currentPassName = passName;
currentTracer = newTracer(passName);
}
/**
* Marks the end of a pass.
*/
void endPass() {
Preconditions.checkState(currentTracer != null,
"Tracer should not be null at the end of a pass.");
stopTracer(currentTracer, currentPassName);
currentPassName = null;
currentTracer = null;
maybeSanityCheck();
}
@Override
final void beforePass(String passName) {
// does nothing for now
}
@Override
final void afterPass(String passName) {
if (options.printSourceAfterEachPass) {
String currentJsSource = getCurrentJsSource();
if (!currentJsSource.equals(this.lastJsSource)) {
System.out.println();
System.out.println("// " + passName + " yields:");
System.out.println("// ************************************");
System.out.println(currentJsSource);