Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Charsets;
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Supplier;
23 import com.google.common.base.Throwables;
24 import com.google.common.collect.Lists;
25 import com.google.common.collect.Maps;
26 import com.google.common.io.CharStreams;
27 import com.google.javascript.jscomp.CompilerOptions.DevMode;
28 import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
29 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection;
30 import com.google.javascript.jscomp.Scope.Var;
31 import com.google.javascript.jscomp.deps.SortedDependencies;
32 import com.google.javascript.jscomp.deps.SortedDependencies.CircularDependencyException;
33 import com.google.javascript.jscomp.deps.SortedDependencies.MissingProvideException;
34 import com.google.javascript.jscomp.parsing.Config;
35 import com.google.javascript.jscomp.parsing.ParserRunner;
36 import com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter;
37 import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter;
38 import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
39 import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter;
40 import com.google.javascript.rhino.IR;
41 import com.google.javascript.rhino.InputId;
42 import com.google.javascript.rhino.JSDocInfo;
43 import com.google.javascript.rhino.Node;
44 import com.google.javascript.rhino.Token;
45 import com.google.javascript.rhino.head.ErrorReporter;
46 import com.google.javascript.rhino.head.ast.AstRoot;
47 import com.google.javascript.rhino.jstype.JSTypeRegistry;
48
49 import java.io.IOException;
50 import java.io.InputStreamReader;
51 import java.io.PrintStream;
52 import java.io.Serializable;
53 import java.util.Collections;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Map;
57 import java.util.ResourceBundle;
58 import java.util.Set;
59 import java.util.concurrent.Callable;
60 import java.util.concurrent.ExecutionException;
61 import java.util.concurrent.ExecutorService;
62 import java.util.concurrent.Executors;
63 import java.util.concurrent.ThreadFactory;
64 import java.util.logging.Level;
65 import java.util.logging.Logger;
66 import java.util.regex.Matcher;
67
68 /**
69 * Compiler (and the other classes in this package) does the following:
70 * <ul>
71 * <li>parses JS code
72 * <li>checks for undefined variables
73 * <li>performs optimizations such as constant folding and constants inlining
74 * <li>renames variables (to short names)
75 * <li>outputs compact JavaScript code
76 * </ul>
77 *
78 * External variables are declared in 'externs' files. For instance, the file
79 * may include definitions for global javascript/browser objects such as
80 * window, document.
81 *
82 */
83 public class Compiler extends AbstractCompiler {
84 static final String SINGLETON_MODULE_NAME = "[singleton]";
85
86 static final DiagnosticType MODULE_DEPENDENCY_ERROR =
87 DiagnosticType.error("JSC_MODULE_DEPENDENCY_ERROR",
88 "Bad dependency: {0} -> {1}. "
89 + "Modules must be listed in dependency order.");
90
91 static final DiagnosticType MISSING_ENTRY_ERROR = DiagnosticType.error(
92 "JSC_MISSING_ENTRY_ERROR",
93 "required entry point \"{0}\" never provided");
94
95 static final DiagnosticType MISSING_MODULE_ERROR = DiagnosticType.error(
96 "JSC_MISSING_ENTRY_ERROR",
97 "unknown module \"{0}\" specified in entry point spec");
98
99 // Used in PerformanceTracker
100 static final String PARSING_PASS_NAME = "parseInputs";
101
102 private static final String CONFIG_RESOURCE =
103 "com.google.javascript.jscomp.parsing.ParserConfig";
104
105 CompilerOptions options = null;
106
107 private PassConfig passes = null;
108
109 // The externs inputs
110 private List<CompilerInput> externs;
111
112 // The JS source modules
113 private List<JSModule> modules;
114
115 // The graph of the JS source modules. Must be null if there are less than
116 // 2 modules, because we use this as a signal for which passes to run.
117 private JSModuleGraph moduleGraph;
118
119 // The JS source inputs
120 private List<CompilerInput> inputs;
121
122 // error manager to which error management is delegated
123 private ErrorManager errorManager;
124
125 // Warnings guard for filtering warnings.
126 private WarningsGuard warningsGuard;
127
128 // Compile-time injected libraries. The node points to the last node of
129 // the library, so code can be inserted after.
130 private final Map<String, Node> injectedLibraries = Maps.newLinkedHashMap();
131
132 // Parse tree root nodes
133 Node externsRoot;
134 Node jsRoot;
135 Node externAndJsRoot;
136
137 private Map<InputId, CompilerInput> inputsById;
138
139 /** The source code map */
140 private SourceMap sourceMap;
141
142 /** The externs created from the exports. */
143 private String externExports = null;
144
145 /**
146 * Ids for function inlining so that each declared name remains
147 * unique.
148 */
149 private int uniqueNameId = 0;
150
151 /**
152 * Whether to assume there are references to the RegExp Global object
153 * properties.
154 */
155 private boolean hasRegExpGlobalReferences = true;
156
157 /** The function information map */
158 private FunctionInformationMap functionInformationMap;
159
160 /** Debugging information */
161 private final StringBuilder debugLog = new StringBuilder();
162
163 /** Detects Google-specific coding conventions. */
164 CodingConvention defaultCodingConvention = new ClosureCodingConvention();
165
166 private JSTypeRegistry typeRegistry;
167 private Config parserConfig = null;
168
169 private ReverseAbstractInterpreter abstractInterpreter;
170 private TypeValidator typeValidator;
171
172 public PerformanceTracker tracker;
173
174 // The oldErrorReporter exists so we can get errors from the JSTypeRegistry.
175 private final com.google.javascript.rhino.ErrorReporter oldErrorReporter =
176 RhinoErrorReporter.forOldRhino(this);
177
178 // This error reporter gets the messages from the current Rhino parser.
179 private final ErrorReporter defaultErrorReporter =
180 RhinoErrorReporter.forNewRhino(this);
181
182 /** Error strings used for reporting JSErrors */
183 public static final DiagnosticType OPTIMIZE_LOOP_ERROR = DiagnosticType.error(
184 "JSC_OPTIMIZE_LOOP_ERROR",
185 "Exceeded max number of optimization iterations: {0}");
186 public static final DiagnosticType MOTION_ITERATIONS_ERROR =
187 DiagnosticType.error("JSC_OPTIMIZE_LOOP_ERROR",
188 "Exceeded max number of code motion iterations: {0}");
189
190 // We use many recursive algorithms that use O(d) memory in the depth
191 // of the tree.
192 private static final long COMPILER_STACK_SIZE = (1 << 21); // About 2MB
193
194 /**
195 * Under JRE 1.6, the JS Compiler overflows the stack when running on some
196 * large or complex JS code. When threads are available, we run all compile
197 * jobs on a separate thread with a larger stack.
198 *
199 * That way, we don't have to increase the stack size for *every* thread
200 * (which is what -Xss does).
201 */
202 private static final ExecutorService compilerExecutor =
203 Executors.newCachedThreadPool(new ThreadFactory() {
204 @Override public Thread newThread(Runnable r) {
205 return new Thread(null, r, "jscompiler", COMPILER_STACK_SIZE);
206 }
207 });
208
209 /**
210 * Use a dedicated compiler thread per Compiler instance.
211 */
212 private Thread compilerThread = null;
213
214 /** Whether to use threads. */
215 private boolean useThreads = true;
216
217
218 /**
219 * Logger for the whole com.google.javascript.jscomp domain -
220 * setting configuration for this logger affects all loggers
221 * in other classes within the compiler.
222 */
223 private static final Logger logger =
224 Logger.getLogger("com.google.javascript.jscomp");
225
226 private final PrintStream outStream;
227
228 private GlobalVarReferenceMap globalRefMap = null;
229
230 private volatile double progress = 0.0;
231 private String lastPassName;
232
233 /**
234 * Creates a Compiler that reports errors and warnings to its logger.
235 */
236 public Compiler() {
237 this((PrintStream) null);
238 }
239
240 /**
241 * Creates a Compiler that reports errors and warnings to an output stream.
242 */
243 public Compiler(PrintStream stream) {
244 addChangeHandler(recentChange);
245 outStream = stream;
246 }
247
248 /**
249 * Creates a Compiler that uses a custom error manager.
250 */
251 public Compiler(ErrorManager errorManager) {
252 this();
253 setErrorManager(errorManager);
254 }
255
256 /**
257 * Sets the error manager.
258 *
259 * @param errorManager the error manager, it cannot be {@code null}
260 */
261 public void setErrorManager(ErrorManager errorManager) {
262 Preconditions.checkNotNull(
263 errorManager, "the error manager cannot be null");
264 this.errorManager = errorManager;
265 }
266
267 /**
268 * Creates a message formatter instance corresponding to the value of
269 * {@link CompilerOptions}.
270 */
271 private MessageFormatter createMessageFormatter() {
272 boolean colorize = options.shouldColorizeErrorOutput();
273 return options.errorFormat.toFormatter(this, colorize);
274 }
275
276 /**
277 * Initialize the compiler options. Only necessary if you're not doing
278 * a normal compile() job.
279 */
280 public void initOptions(CompilerOptions options) {
281 this.options = options;
282 if (errorManager == null) {
283 if (outStream == null) {
284 setErrorManager(
285 new LoggerErrorManager(createMessageFormatter(), logger));
286 } else {
287 PrintStreamErrorManager printer =
288 new PrintStreamErrorManager(createMessageFormatter(), outStream);
289 printer.setSummaryDetailLevel(options.summaryDetailLevel);
290 setErrorManager(printer);
291 }
292 }
293
294 reconcileOptionsWithGuards();
295
296 // Initialize the warnings guard.
297 List<WarningsGuard> guards = Lists.newArrayList();
298 guards.add(
299 new SuppressDocWarningsGuard(
300 getDiagnosticGroups().getRegisteredGroups()));
301 guards.add(options.getWarningsGuard());
302
303 this.warningsGuard = new ComposeWarningsGuard(guards);
304 }
305
306 /**
307 * When the CompilerOptions and its WarningsGuard overlap, reconcile
308 * any discrepencies.
309 */
310 protected void reconcileOptionsWithGuards() {
311 // DiagnosticGroups override the plain checkTypes option.
312 if (options.enables(DiagnosticGroups.CHECK_TYPES)) {
313 options.checkTypes = true;
314 } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {
315 options.checkTypes = false;
316 } else if (!options.checkTypes) {
317 // If DiagnosticGroups did not override the plain checkTypes
318 // option, and checkTypes is enabled, then turn off the
319 // parser type warnings.
320 options.setWarningLevel(
321 DiagnosticGroup.forType(
322 RhinoErrorReporter.TYPE_PARSE_ERROR),
323 CheckLevel.OFF);
324 }
325
326 if (options.checkGlobalThisLevel.isOn() &&
327 !options.disables(DiagnosticGroups.GLOBAL_THIS)) {
328 options.setWarningLevel(
329 DiagnosticGroups.GLOBAL_THIS,
330 options.checkGlobalThisLevel);
331 }
332
333 if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) {
334 options.setWarningLevel(
335 DiagnosticGroups.ES5_STRICT,
336 CheckLevel.ERROR);
337 }
338
339 // All passes must run the variable check. This synthesizes
340 // variables later so that the compiler doesn't crash. It also
341 // checks the externs file for validity. If you don't want to warn
342 // about missing variable declarations, we shut that specific
343 // error off.
344 if (!options.checkSymbols &&
345 !options.enables(DiagnosticGroups.CHECK_VARIABLES)) {
346 options.setWarningLevel(
347 DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF);
348 }
349 }
350
351 /**
352 * Initializes the instance state needed for a compile job.
353 * @deprecated Convert your arrays to lists and use the list-based API.
354 */
355 @Deprecated
356 public void init(JSSourceFile[] externs, JSSourceFile[] inputs,
357 CompilerOptions options) {
358 init(Lists.<JSSourceFile>newArrayList(externs),
359 Lists.<JSSourceFile>newArrayList(inputs), options);
360 }
361
362 /**
363 * Initializes the instance state needed for a compile job.
364 */
365 public <T1 extends SourceFile, T2 extends SourceFile> void init(
366 List<T1> externs,
367 List<T2> inputs,
368 CompilerOptions options) {
369 JSModule module = new JSModule(SINGLETON_MODULE_NAME);
370 for (SourceFile input : inputs) {
371 module.add(input);
372 }
373
374 initModules(externs, Lists.newArrayList(module), options);
375 }
376
377 /**
378 * Initializes the instance state needed for a compile job if the sources
379 * are in modules.
380 * @deprecated Convert your arrays to lists and use the list-based API.
381 */
382 @Deprecated
383 public void init(JSSourceFile[] externs, JSModule[] modules,
384 CompilerOptions options) {
385 initModules(Lists.<SourceFile>newArrayList(externs),
386 Lists.<JSModule>newArrayList(modules), options);
387 }
388
389 /**
390 * Initializes the instance state needed for a compile job if the sources
391 * are in modules.
392 */
393 public <T extends SourceFile> void initModules(
394 List<T> externs, List<JSModule> modules, CompilerOptions options) {
395 initOptions(options);
396
397 checkFirstModule(modules);
398 fillEmptyModules(modules);
399
400 this.externs = makeCompilerInput(externs, true);
401
402 // Generate the module graph, and report any errors in the module
403 // specification as errors.
404 this.modules = modules;
405 if (modules.size() > 1) {
406 try {
407 this.moduleGraph = new JSModuleGraph(modules);
408 } catch (JSModuleGraph.ModuleDependenceException e) {
409 // problems with the module format. Report as an error. The
410 // message gives all details.
411 report(JSError.make(MODULE_DEPENDENCY_ERROR,
412 e.getModule().getName(), e.getDependentModule().getName()));
413 return;
414 }
415 } else {
416 this.moduleGraph = null;
417 }
418
419 this.inputs = getAllInputsFromModules(modules);
420 initBasedOnOptions();
421
422 initInputsByIdMap();
423 }
424
425 /**
426 * Do any initialization that is dependent on the compiler options.
427 */
428 private void initBasedOnOptions() {
429 // Create the source map if necessary.
430 if (options.sourceMapOutputPath != null) {
431 sourceMap = options.sourceMapFormat.getInstance();
432 sourceMap.setPrefixMappings(options.sourceMapLocationMappings);
433 }
434 }
435
436 private <T extends SourceFile> List<CompilerInput> makeCompilerInput(
437 List<T> files, boolean isExtern) {
438 List<CompilerInput> inputs = Lists.newArrayList();
439 for (T file : files) {
440 inputs.add(new CompilerInput(file, isExtern));
441 }
442 return inputs;
443 }
444
445 private static final DiagnosticType EMPTY_MODULE_LIST_ERROR =
446 DiagnosticType.error("JSC_EMPTY_MODULE_LIST_ERROR",
447 "At least one module must be provided");
448
449 private static final DiagnosticType EMPTY_ROOT_MODULE_ERROR =
450 DiagnosticType.error("JSC_EMPTY_ROOT_MODULE_ERROR",
451 "Root module '{0}' must contain at least one source code input");
452
453 /**
454 * Verifies that at least one module has been provided and that the first one
455 * has at least one source code input.
456 */
457 private void checkFirstModule(List<JSModule> modules) {
458 if (modules.isEmpty()) {
459 report(JSError.make(EMPTY_MODULE_LIST_ERROR));
460 } else if (modules.get(0).getInputs().isEmpty() && modules.size() > 1) {
461 // The root module may only be empty if there is exactly 1 module.
462 report(JSError.make(EMPTY_ROOT_MODULE_ERROR,
463 modules.get(0).getName()));
464 }
465 }
466
467 /**
468 * Empty modules get an empty "fill" file, so that we can move code into
469 * an empty module.
470 */
471 static String createFillFileName(String moduleName) {
472 return "[" + moduleName + "]";
473 }
474
475 /**
476 * Fill any empty modules with a place holder file. It makes any cross module
477 * motion easier.
478 */
479 private static void fillEmptyModules(List<JSModule> modules) {
480 for (JSModule module : modules) {
481 if (module.getInputs().isEmpty()) {
482 module.add(SourceFile.fromCode(
483 createFillFileName(module.getName()), ""));
484 }
485 }
486 }
487
488 /**
489 * Rebuilds the internal list of inputs by iterating over all modules.
490 * This is necessary if inputs have been added to or removed from a module
491 * after the {@link #init(List, List, CompilerOptions)} call.
492 */
493 public void rebuildInputsFromModules() {
494 inputs = getAllInputsFromModules(modules);
495 initInputsByIdMap();
496 }
497
498 /**
499 * Builds a single list of all module inputs. Verifies that it contains no
500 * duplicates.
501 */
502 private static List<CompilerInput> getAllInputsFromModules(
503 List<JSModule> modules) {
504 List<CompilerInput> inputs = Lists.newArrayList();
505 Map<String, JSModule> inputMap = Maps.newHashMap();
506 for (JSModule module : modules) {
507 for (CompilerInput input : module.getInputs()) {
508 String inputName = input.getName();
509
510 // NOTE(nicksantos): If an input is in more than one module,
511 // it will show up twice in the inputs list, and then we
512 // will get an error down the line.
513 inputs.add(input);
514 inputMap.put(inputName, module);
515 }
516 }
517 return inputs;
518 }
519
520 static final DiagnosticType DUPLICATE_INPUT =
521 DiagnosticType.error("JSC_DUPLICATE_INPUT", "Duplicate input: {0}");
522 static final DiagnosticType DUPLICATE_EXTERN_INPUT =
523 DiagnosticType.error("JSC_DUPLICATE_EXTERN_INPUT",
524 "Duplicate extern input: {0}");
525
526 /**
527 * Creates a map to make looking up an input by name fast. Also checks for
528 * duplicate inputs.
529 */
530 void initInputsByIdMap() {
531 inputsById = new HashMap<InputId, CompilerInput>();
532 for (CompilerInput input : externs) {
533 InputId id = input.getInputId();
534 CompilerInput previous = putCompilerInput(id, input);
535 if (previous != null) {
536 report(JSError.make(DUPLICATE_EXTERN_INPUT, input.getName()));
537 }
538 }
539 for (CompilerInput input : inputs) {
540 InputId id = input.getInputId();
541 CompilerInput previous = putCompilerInput(id, input);
542 if (previous != null) {
543 report(JSError.make(DUPLICATE_INPUT, input.getName()));
544 }
545 }
546 }
547
548 public Result compile(
549 SourceFile extern, SourceFile input, CompilerOptions options) {
550 return compile(Lists.newArrayList(extern), Lists.newArrayList(input), options);
551 }
552
553 /**
554 * @deprecated Convert your arrays to lists and use the list-based API.
555 */
556 @Deprecated
557 public Result compile(
558 SourceFile extern, JSSourceFile[] input, CompilerOptions options) {
559 return compile(Lists.newArrayList(extern), Lists.newArrayList(input), options);
560 }
561
562 /**
563 * @deprecated Convert your arrays to lists and use the list-based
564 * compileModules method.
565 */
566 @Deprecated
567 public Result compile(
568 JSSourceFile extern, JSModule[] modules, CompilerOptions options) {
569 return compileModules(
570 Lists.newArrayList(extern), Lists.newArrayList(modules), options);
571 }
572
573 /**
574 * Compiles a list of inputs.
575 * @deprecated Convert your arrays to lists and use the list-based compile
576 * method.
577 */
578 @Deprecated
579 public Result compile(JSSourceFile[] externs,
580 JSSourceFile[] inputs,
581 CompilerOptions options) {
582 return compile(Lists.<SourceFile>newArrayList(externs),
583 Lists.<SourceFile>newArrayList(inputs),
584 options);
585 }
586
587 /**
588 * Compiles a list of inputs.
589 */
590 public <T1 extends SourceFile, T2 extends SourceFile> Result compile(
591 List<T1> externs, List<T2> inputs, CompilerOptions options) {
592 // The compile method should only be called once.
593 Preconditions.checkState(jsRoot == null);
594
595 try {
596 init(externs, inputs, options);
597 if (hasErrors()) {
598 return getResult();
599 }
600 return compile();
601 } finally {
602 Tracer t = newTracer("generateReport");
603 errorManager.generateReport();
604 stopTracer(t, "generateReport");
605 }
606 }
607
608 /**
609 * Compiles a list of modules.
610 * @deprecated Convert your arrays to lists and use the list-based
611 * compileModules method.
612 */
613 @Deprecated
614 public Result compile(JSSourceFile[] externs,
615 JSModule[] modules,
616 CompilerOptions options) {
617 return compileModules(Lists.<SourceFile>newArrayList(externs),
618 Lists.<JSModule>newArrayList(modules),
619 options);
620 }
621
622 /**
623 * Compiles a list of modules.
624 */
625 public <T extends SourceFile> Result compileModules(List<T> externs,
626 List<JSModule> modules, CompilerOptions options) {
627 // The compile method should only be called once.
628 Preconditions.checkState(jsRoot == null);
629
630 try {
631 initModules(externs, modules, options);
632 if (hasErrors()) {
633 return getResult();
634 }
635 return compile();
636 } finally {
637 Tracer t = newTracer("generateReport");
638 errorManager.generateReport();
639 stopTracer(t, "generateReport");
640 }
641 }
642
643 private Result compile() {
644 return runInCompilerThread(new Callable<Result>() {
645 @Override
646 public Result call() throws Exception {
647 compileInternal();
648 return getResult();
649 }
650 });
651 }
652
653 /**
654 * Disable threads. This is for clients that run on AppEngine and
655 * don't have threads.
656 */
657 public void disableThreads() {
658 useThreads = false;
659 }
660
661 @SuppressWarnings("unchecked")
662 <T> T runInCompilerThread(final Callable<T> callable) {
663 final boolean dumpTraceReport = options != null && options.tracer.isOn();
664 T result = null;
665 final Throwable[] exception = new Throwable[1];
666 Callable<T> bootCompilerThread = new Callable<T>() {
667 @Override
668 public T call() {
669 try {
670 compilerThread = Thread.currentThread();
671 if (dumpTraceReport) {
672 Tracer.initCurrentThreadTrace();
673 }
674 return callable.call();
675 } catch (Throwable e) {
676 exception[0] = e;
677 } finally {
678 compilerThread = null;
679 if (dumpTraceReport) {
680 Tracer.logAndClearCurrentThreadTrace();
681 tracker.outputTracerReport(outStream == null ?
682 System.out : outStream);
683 }
684 }
685 return null;
686 }
687 };
688
689 Preconditions.checkState(
690 compilerThread == null || compilerThread == Thread.currentThread(),
691 "Please do not share the Compiler across threads");
692
693 // If the compiler thread is available, use it.
694 if (useThreads && compilerThread == null) {
695 try {
696 result = compilerExecutor.submit(bootCompilerThread).get();
697 } catch (InterruptedException e) {
698 throw Throwables.propagate(e);
699 } catch (ExecutionException e) {
700 throw Throwables.propagate(e);
701 }
702 } else {
703 try {
704 result = callable.call();
705 } catch (Exception e) {
706 exception[0] = e;
707 }
708 }
709
710 // Pass on any exception caught by the runnable object.
711 if (exception[0] != null) {
712 throw new RuntimeException(exception[0]);
713 }
714
715 return result;
716 }
717
718 private void compileInternal() {
719 setProgress(0.0, null);
720 parse();
721 // 15 percent of the work is assumed to be for parsing (based on some
722 // minimal analysis on big JS projects, of course this depends on options)
723 setProgress(0.15, "parse");
724 if (hasErrors()) {
725 return;
726 }
727
728 if (!precheck()) {
729 return;
730 }
731
732 if (options.nameAnonymousFunctionsOnly) {
733 // TODO(nicksantos): Move this into an instrument() phase maybe?
734 check();
735 return;
736 }
737
738 if (!options.skipAllPasses) {
739 check();
740 if (hasErrors()) {
741 return;
742 }
743
744 if (options.isExternExportsEnabled()
745 || options.externExportsPath != null) {
746 externExports();
747 }
748
749 // IDE-mode is defined to stop here, before the heavy rewriting begins.
750 if (!options.ideMode) {
751 optimize();
752 }
753 }
754
755 if (options.recordFunctionInformation) {
756 recordFunctionInformation();
757 }
758
759 if (options.devMode == DevMode.START_AND_END) {
760 runSanityCheck();
761 }
762 setProgress(1.0, "recordFunctionInformation");
763 }
764
765 public void parse() {
766 parseInputs();
767 }
768
769 PassConfig getPassConfig() {
770 if (passes == null) {
771 passes = createPassConfigInternal();
772 }
773 return passes;
774 }
775
776 /**
777 * Create the passes object. Clients should use setPassConfig instead of
778 * overriding this.
779 */
780 PassConfig createPassConfigInternal() {
781 return new DefaultPassConfig(options);
782 }
783
784 /**
785 * @param passes The PassConfig to use with this Compiler.
786 * @throws NullPointerException if passes is null
787 * @throws IllegalStateException if this.passes has already been assigned
788 */
789 public void setPassConfig(PassConfig passes) {
790 // Important to check for null because if setPassConfig(null) is
791 // called before this.passes is set, getPassConfig() will create a
792 // new PassConfig object and use that, which is probably not what
793 // the client wanted since he or she probably meant to use their
794 // own PassConfig object.
795 Preconditions.checkNotNull(passes);
796
797 if (this.passes != null) {
798 throw new IllegalStateException("this.passes has already been assigned");
799 }
800 this.passes = passes;
801 }
802
803 /**
804 * Carry out any special checks or procedures that need to be done before
805 * proceeding with rest of the compilation process.
806 *
807 * @return true, to continue with compilation
808 */
809 boolean precheck() {
810 return true;
811 }
812
813 public void check() {
814 runCustomPasses(CustomPassExecutionTime.BEFORE_CHECKS);
815
816 // We are currently only interested in check-passes for progress reporting
817 // as it is used for IDEs, that's why the maximum progress is set to 1.0.
818 PhaseOptimizer phaseOptimizer = new PhaseOptimizer(this, tracker,
819 new PhaseOptimizer.ProgressRange(getProgress(), 1.0));
820 if (options.devMode == DevMode.EVERY_PASS) {
821 phaseOptimizer.setSanityCheck(sanityCheck);
822 }
823 if (options.getCheckDeterminism()) {
824 phaseOptimizer.setPrintAstHashcodes(true);
825 }
826 phaseOptimizer.consume(getPassConfig().getChecks());
827 phaseOptimizer.process(externsRoot, jsRoot);
828 if (hasErrors()) {
829 return;
830 }
831
832 // TODO(nicksantos): clean this up. The flow here is too hard to follow.
833 if (options.nameAnonymousFunctionsOnly) {
834 return;
835 }
836
837 if (options.removeTryCatchFinally) {
838 removeTryCatchFinally();
839 }
840
841 if (options.getTweakProcessing().shouldStrip() ||
842 !options.stripTypes.isEmpty() ||
843 !options.stripNameSuffixes.isEmpty() ||
844 !options.stripTypePrefixes.isEmpty() ||
845 !options.stripNamePrefixes.isEmpty()) {
846 stripCode(options.stripTypes, options.stripNameSuffixes,
847 options.stripTypePrefixes, options.stripNamePrefixes);
848 }
849
850 runCustomPasses(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS);
851 }
852
853 private void externExports() {
854 logger.fine("Creating extern file for exports");
855 startPass("externExports");
856
857 ExternExportsPass pass = new ExternExportsPass(this);
858 process(pass);
859
860 externExports = pass.getGeneratedExterns();
861
862 endPass();
863 }
864
865 @Override
866 void process(CompilerPass p) {
867 p.process(externsRoot, jsRoot);
868 }
869
870 private final PassFactory sanityCheck =
871 new PassFactory("sanityCheck", false) {
872 @Override
873 protected CompilerPass create(AbstractCompiler compiler) {
874 return new SanityCheck(compiler);
875 }
876 };
877
878 private void maybeSanityCheck() {
879 if (options.devMode == DevMode.EVERY_PASS) {
880 runSanityCheck();
881 }
882 }
883
884 private void runSanityCheck() {
885 sanityCheck.create(this).process(externsRoot, jsRoot);
886 }
887
888 /**
889 * Removes try/catch/finally statements for easier debugging.
890 */
891 void removeTryCatchFinally() {
892 logger.fine("Remove try/catch/finally");
893 startPass("removeTryCatchFinally");
894 RemoveTryCatch r = new RemoveTryCatch(this);
895 process(r);
896 endPass();
897 }
898
899 /**
900 * Strips code for smaller compiled code. This is useful for removing debug
901 * statements to prevent leaking them publicly.
902 */
903 void stripCode(Set<String> stripTypes, Set<String> stripNameSuffixes,
904 Set<String> stripTypePrefixes, Set<String> stripNamePrefixes) {
905 logger.fine("Strip code");
906 startPass("stripCode");
907 StripCode r = new StripCode(this, stripTypes, stripNameSuffixes,
908 stripTypePrefixes, stripNamePrefixes);
909 if (options.getTweakProcessing().shouldStrip()) {
910 r.enableTweakStripping();
911 }
912 process(r);
913 endPass();
914 }
915
916 /**
917 * Runs custom passes that are designated to run at a particular time.
918 */
919 private void runCustomPasses(CustomPassExecutionTime executionTime) {
920 if (options.customPasses != null) {
921 Tracer t = newTracer("runCustomPasses");
922 try {
923 for (CompilerPass p : options.customPasses.get(executionTime)) {
924 process(p);
925 }
926 } finally {
927 stopTracer(t, "runCustomPasses");
928 }
929 }
930 }
931
932 private Tracer currentTracer = null;
933 private String currentPassName = null;
934
935 /**
936 * Marks the beginning of a pass.
937 */
938 void startPass(String passName) {
939 Preconditions.checkState(currentTracer == null);
940 currentPassName = passName;
941 currentTracer = newTracer(passName);
942 }
943
944 /**
945 * Marks the end of a pass.
946 */
947 void endPass() {
948 Preconditions.checkState(currentTracer != null,
949 "Tracer should not be null at the end of a pass.");
950 stopTracer(currentTracer, currentPassName);
951 currentPassName = null;
952 currentTracer = null;
953
954 maybeSanityCheck();
955 }
956
957 /**
958 * Returns a new tracer for the given pass name.
959 */
960 Tracer newTracer(String passName) {
961 String comment = passName
962 + (recentChange.hasCodeChanged() ? " on recently changed AST" : "");
963 if (options.tracer.isOn()) {
964 tracker.recordPassStart(passName, true);
965 }
966 return new Tracer("Compiler", comment);
967 }
968
969 void stopTracer(Tracer t, String passName) {
970 long result = t.stop();
971 if (options.tracer.isOn()) {
972 tracker.recordPassStop(passName, result);
973 }
974 }
975
976 /**
977 * Returns the result of the compilation.
978 */
979 public Result getResult() {
980 PassConfig.State state = getPassConfig().getIntermediateState();
981 return new Result(getErrors(), getWarnings(), debugLog.toString(),
982 state.variableMap, state.propertyMap,
983 state.anonymousFunctionNameMap, state.stringMap, functionInformationMap,
984 sourceMap, externExports, state.cssNames, state.idGeneratorMap);
985 }
986
987 /**
988 * Returns an array constructed from errors + temporary warnings.
989 */
990 public JSError[] getMessages() {
991 return getErrors();
992 }
993
994 /**
995 * Returns the array of errors (never null).
996 */
997 public JSError[] getErrors() {
998 return errorManager.getErrors();
999 }
1000
1001 /**
1002 * Returns the array of warnings (never null).
1003 */
1004 public JSError[] getWarnings() {
1005 return errorManager.getWarnings();
1006 }
1007
1008 @Override
1009 public Node getRoot() {
1010 return externAndJsRoot;
1011 }
1012
1013 /**
1014 * Creates a new id for making unique names.
1015 */
1016 private int nextUniqueNameId() {
1017 return uniqueNameId++;
1018 }
1019
1020 /**
1021 * Resets the unique name id counter
1022 */
1023 @VisibleForTesting
1024 void resetUniqueNameId() {
1025 uniqueNameId = 0;
1026 }
1027
1028 @Override
1029 Supplier<String> getUniqueNameIdSupplier() {
1030 final Compiler self = this;
1031 return new Supplier<String>() {
1032 @Override
1033 public String get() {
1034 return String.valueOf(self.nextUniqueNameId());
1035 }
1036 };
1037 }
1038
1039 @Override
1040 boolean areNodesEqualForInlining(Node n1, Node n2) {
1041 if (options.ambiguateProperties ||
1042 options.disambiguateProperties) {
1043 // The type based optimizations require that type information is preserved
1044 // during other optimizations.
1045 return n1.isEquivalentToTyped(n2);
1046 } else {
1047 return n1.isEquivalentTo(n2);
1048 }
1049 }
1050
1051 //------------------------------------------------------------------------
1052 // Inputs
1053 //------------------------------------------------------------------------
1054
1055 // TODO(nicksantos): Decide which parts of these belong in an AbstractCompiler
1056 // interface, and which ones should always be injected.
1057
1058 @Override
1059 public CompilerInput getInput(InputId id) {
1060 return inputsById.get(id);
1061 }
1062
1063 /**
1064 * Removes an input file from AST.
1065 * @param id The id of the input to be removed.
1066 */
1067 protected void removeExternInput(InputId id) {
1068 CompilerInput input = getInput(id);
1069 if (input == null) {
1070 return;
1071 }
1072 Preconditions.checkState(input.isExtern(), "Not an extern input: %s", input.getName());
1073 inputsById.remove(id);
1074 externs.remove(input);
1075 Node root = input.getAstRoot(this);
1076 if (root != null) {
1077 root.detachFromParent();
1078 }
1079 }
1080
1081 @Override
1082 public CompilerInput newExternInput(String name) {
1083 SourceAst ast = new SyntheticAst(name);
1084 if (inputsById.containsKey(ast.getInputId())) {
1085 throw new IllegalArgumentException("Conflicting externs name: " + name);
1086 }
1087 CompilerInput input = new CompilerInput(ast, true);
1088 putCompilerInput(input.getInputId(), input);
1089 externsRoot.addChildToFront(ast.getAstRoot(this));
1090 externs.add(0, input);
1091 return input;
1092 }
1093
1094 private CompilerInput putCompilerInput(InputId id, CompilerInput input) {
1095 input.setCompiler(this);
1096 return inputsById.put(id, input);
1097 }
1098
1099 /** Add a source input dynamically. Intended for incremental compilation. */
1100 void addIncrementalSourceAst(JsAst ast) {
1101 InputId id = ast.getInputId();
1102 Preconditions.checkState(getInput(id) == null, "Duplicate input %s", id.getIdName());
1103 putCompilerInput(id, new CompilerInput(ast));
1104 }
1105
1106 /**
1107 * Replace a source input dynamically. Intended for incremental
1108 * re-compilation.
1109 *
1110 * If the new source input doesn't parse, then keep the old input
1111 * in the AST and return false.
1112 *
1113 * @return Whether the new AST was attached successfully.
1114 */
1115 boolean replaceIncrementalSourceAst(JsAst ast) {
1116 CompilerInput oldInput = getInput(ast.getInputId());
1117 Preconditions.checkNotNull(oldInput, "No input to replace: %s", ast.getInputId().getIdName());
1118 Node newRoot = ast.getAstRoot(this);
1119 if (newRoot == null) {
1120 return false;
1121 }
1122
1123 Node oldRoot = oldInput.getAstRoot(this);
1124 if (oldRoot != null) {
1125 oldRoot.getParent().replaceChild(oldRoot, newRoot);
1126 } else {
1127 getRoot().getLastChild().addChildToBack(newRoot);
1128 }
1129
1130 CompilerInput newInput = new CompilerInput(ast);
1131 putCompilerInput(ast.getInputId(), newInput);
1132
1133 JSModule module = oldInput.getModule();
1134 if (module != null) {
1135 module.addAfter(newInput, oldInput);
1136 module.remove(oldInput);
1137 }
1138
1139 // Verify the input id is set properly.
1140 Preconditions.checkState(
1141 newInput.getInputId().equals(oldInput.getInputId()));
1142 InputId inputIdOnAst = newInput.getAstRoot(this).getInputId();
1143 Preconditions.checkState(newInput.getInputId().equals(inputIdOnAst));
1144
1145 inputs.remove(oldInput);
1146 return true;
1147 }
1148
1149 /**
1150 * Add a new source input dynamically. Intended for incremental compilation.
1151 * <p>
1152 * If the new source input doesn't parse, it will not be added, and a false
1153 * will be returned.
1154 *
1155 * @param ast the JS Source to add.
1156 * @return true if the source was added successfully, false otherwise.
1157 * @throws IllegalStateException if an input for this ast already exists.
1158 */
1159 boolean addNewSourceAst(JsAst ast) {
1160 CompilerInput oldInput = getInput(ast.getInputId());
1161 if (oldInput != null) {
1162 throw new IllegalStateException(
1163 "Input already exists: " + ast.getInputId().getIdName());
1164 }
1165 Node newRoot = ast.getAstRoot(this);
1166 if (newRoot == null) {
1167 return false;
1168 }
1169
1170 getRoot().getLastChild().addChildToBack(newRoot);
1171
1172 CompilerInput newInput = new CompilerInput(ast);
1173
1174 // TODO(tylerg): handle this for multiple modules at some point.
1175 if (moduleGraph == null && !modules.isEmpty()) {
1176 // singleton module
1177 modules.get(0).add(newInput);
1178 }
1179
1180 putCompilerInput(ast.getInputId(), newInput);
1181
1182 return true;
1183 }
1184
1185 @Override
1186 JSModuleGraph getModuleGraph() {
1187 return moduleGraph;
1188 }
1189
1190 /**
1191 * Gets a module graph. This will always return a module graph, even
1192 * in the degenerate case when there's only one module.
1193 */
1194 JSModuleGraph getDegenerateModuleGraph() {
1195 return moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph;
1196 }
1197
1198 @Override
1199 public JSTypeRegistry getTypeRegistry() {
1200 if (typeRegistry == null) {
1201 typeRegistry = new JSTypeRegistry(oldErrorReporter, options.looseTypes);
1202 }
1203 return typeRegistry;
1204 }
1205
1206 @Override
1207 public MemoizedScopeCreator getTypedScopeCreator() {
1208 return getPassConfig().getTypedScopeCreator();
1209 }
1210
1211 @SuppressWarnings("unchecked")
1212 DefaultPassConfig ensureDefaultPassConfig() {
1213 PassConfig passes = getPassConfig().getBasePassConfig();
1214 Preconditions.checkState(passes instanceof DefaultPassConfig,
1215 "PassConfigs must eventually delegate to the DefaultPassConfig");
1216 return (DefaultPassConfig) passes;
1217 }
1218
1219 public SymbolTable buildKnownSymbolTable() {
1220 SymbolTable symbolTable = new SymbolTable(getTypeRegistry());
1221
1222 MemoizedScopeCreator typedScopeCreator = getTypedScopeCreator();
1223 if (typedScopeCreator != null) {
1224 symbolTable.addScopes(typedScopeCreator.getAllMemoizedScopes());
1225 symbolTable.addSymbolsFrom(typedScopeCreator);
1226 } else {
1227 symbolTable.findScopes(this, externsRoot, jsRoot);
1228 }
1229
1230 GlobalNamespace globalNamespace =
1231 ensureDefaultPassConfig().getGlobalNamespace();
1232 if (globalNamespace != null) {
1233 symbolTable.addSymbolsFrom(globalNamespace);
1234 }
1235
1236 ReferenceCollectingCallback refCollector =
1237 new ReferenceCollectingCallback(
1238 this, ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR);
1239 NodeTraversal.traverse(this, getRoot(), refCollector);
1240 symbolTable.addSymbolsFrom(refCollector);
1241
1242 PreprocessorSymbolTable preprocessorSymbolTable =
1243 ensureDefaultPassConfig().getPreprocessorSymbolTable();
1244 if (preprocessorSymbolTable != null) {
1245 symbolTable.addSymbolsFrom(preprocessorSymbolTable);
1246 }
1247
1248 symbolTable.fillNamespaceReferences();
1249 symbolTable.fillPropertyScopes();
1250 symbolTable.fillThisReferences(this, externsRoot, jsRoot);
1251 symbolTable.fillPropertySymbols(this, externsRoot, jsRoot);
1252 symbolTable.fillJSDocInfo(this, externsRoot, jsRoot);
1253
1254 return symbolTable;
1255 }
1256
1257 @Override
1258 public Scope getTopScope() {
1259 return getPassConfig().getTopScope();
1260 }
1261
1262 @Override
1263 public ReverseAbstractInterpreter getReverseAbstractInterpreter() {
1264 if (abstractInterpreter == null) {
1265 ChainableReverseAbstractInterpreter interpreter =
1266 new SemanticReverseAbstractInterpreter(
1267 getCodingConvention(), getTypeRegistry());
1268 if (options.closurePass) {
1269 interpreter = new ClosureReverseAbstractInterpreter(
1270 getCodingConvention(), getTypeRegistry())
1271 .append(interpreter).getFirst();
1272 }
1273 abstractInterpreter = interpreter;
1274 }
1275 return abstractInterpreter;
1276 }
1277
1278 @Override
1279 TypeValidator getTypeValidator() {
1280 if (typeValidator == null) {
1281 typeValidator = new TypeValidator(this);
1282 }
1283 return typeValidator;
1284 }
1285
1286 //------------------------------------------------------------------------
1287 // Parsing
1288 //------------------------------------------------------------------------
1289
1290 /**
1291 * Parses the externs and main inputs.
1292 *
1293 * @return A synthetic root node whose two children are the externs root
1294 * and the main root
1295 */
1296 Node parseInputs() {
1297 boolean devMode = options.devMode != DevMode.OFF;
1298
1299 // If old roots exist (we are parsing a second time), detach each of the
1300 // individual file parse trees.
1301 if (externsRoot != null) {
1302 externsRoot.detachChildren();
1303 }
1304 if (jsRoot != null) {
1305 jsRoot.detachChildren();
1306 }
1307
1308 // Parse main JS sources.
1309 jsRoot = IR.block();
1310 jsRoot.setIsSyntheticBlock(true);
1311
1312 externsRoot = IR.block();
1313 externsRoot.setIsSyntheticBlock(true);
1314
1315 externAndJsRoot = IR.block(externsRoot, jsRoot);
1316 externAndJsRoot.setIsSyntheticBlock(true);
1317
1318 if (options.tracer.isOn()) {
1319 tracker = new PerformanceTracker(jsRoot, options.tracer);
1320 addChangeHandler(tracker.getCodeChangeHandler());
1321 }
1322
1323 Tracer tracer = newTracer(PARSING_PASS_NAME);
1324
1325 try {
1326 // Parse externs sources.
1327 for (CompilerInput input : externs) {
1328 Node n = input.getAstRoot(this);
1329 if (hasErrors()) {
1330 return null;
1331 }
1332 externsRoot.addChildToBack(n);
1333 }
1334
1335 // Modules inferred in ProcessCommonJS pass.
1336 if (options.transformAMDToCJSModules || options.processCommonJSModules) {
1337 processAMDAndCommonJSModules();
1338 }
1339
1340 hoistExterns(externsRoot);
1341
1342 // Check if the sources need to be re-ordered.
1343 boolean staleInputs = false;
1344 if (options.dependencyOptions.needsManagement()) {
1345 for (CompilerInput input : inputs) {
1346 // Forward-declare all the provided types, so that they
1347 // are not flagged even if they are dropped from the process.
1348 for (String provide : input.getProvides()) {
1349 getTypeRegistry().forwardDeclareType(provide);
1350 }
1351 }
1352
1353 try {
1354 inputs =
1355 (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)
1356 .manageDependencies(options.dependencyOptions, inputs);
1357 staleInputs = true;
1358 } catch (CircularDependencyException e) {
1359 report(JSError.make(
1360 JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));
1361 } catch (MissingProvideException e) {
1362 report(JSError.make(
1363 MISSING_ENTRY_ERROR, e.getMessage()));
1364 } catch (JSModuleGraph.MissingModuleException e) {
1365 report(JSError.make(
1366 MISSING_MODULE_ERROR, e.getMessage()));
1367 }
1368
1369 // If in IDE mode, we ignore the error and keep going.
1370 if (hasErrors()) {
1371 return null;
1372 }
1373 }
1374
1375 hoistNoCompileFiles();
1376
1377 if (staleInputs) {
1378 repartitionInputs();
1379 }
1380
1381 // Build the AST.
1382 for (CompilerInput input : inputs) {
1383 Node n = input.getAstRoot(this);
1384 if (n == null) {
1385 continue;
1386 }
1387
1388 if (devMode) {
1389 runSanityCheck();
1390 if (hasErrors()) {
1391 return null;
1392 }
1393 }
1394
1395 if (options.sourceMapOutputPath != null ||
1396 options.nameReferenceReportPath != null) {
1397
1398 // Annotate the nodes in the tree with information from the
1399 // input file. This information is used to construct the SourceMap.
1400 SourceInformationAnnotator sia =
1401 new SourceInformationAnnotator(
1402 input.getName(), options.devMode != DevMode.OFF);
1403 NodeTraversal.traverse(this, n, sia);
1404 }
1405
1406 jsRoot.addChildToBack(n);
1407 }
1408
1409 if (hasErrors()) {
1410 return null;
1411 }
1412 return externAndJsRoot;
1413 } finally {
1414 stopTracer(tracer, PARSING_PASS_NAME);
1415 }
1416 }
1417
1418 /**
1419 * Hoists inputs with the @externs annotation into the externs list.
1420 */
1421 private void hoistExterns(Node externsRoot) {
1422 boolean staleInputs = false;
1423 for (CompilerInput input : inputs) {
1424 if (options.dependencyOptions.needsManagement()) {
1425 // If we're doing scanning dependency info anyway, use that
1426 // information to skip sources that obviously aren't externs.
1427 if (!input.getProvides().isEmpty() || !input.getRequires().isEmpty()) {
1428 continue;
1429 }
1430 }
1431
1432 Node n = input.getAstRoot(this);
1433
1434 // Inputs can have a null AST on a parse error.
1435 if (n == null) {
1436 continue;
1437 }
1438
1439 JSDocInfo info = n.getJSDocInfo();
1440 if (info != null && info.isExterns()) {
1441 // If the input file is explicitly marked as an externs file, then
1442 // assume the programmer made a mistake and throw it into
1443 // the externs pile anyways.
1444 externsRoot.addChildToBack(n);
1445 input.setIsExtern(true);
1446
1447 input.getModule().remove(input);
1448
1449 externs.add(input);
1450 staleInputs = true;
1451 }
1452 }
1453
1454 if (staleInputs) {
1455 repartitionInputs();
1456 }
1457 }
1458
1459 /**
1460 * Hoists inputs with the @nocompiler annotation out of the inputs.
1461 */
1462 private void hoistNoCompileFiles() {
1463 boolean staleInputs = false;
1464 for (CompilerInput input : inputs) {
1465 Node n = input.getAstRoot(this);
1466
1467 // Inputs can have a null AST on a parse error.
1468 if (n == null) {
1469 continue;
1470 }
1471
1472 JSDocInfo info = n.getJSDocInfo();
1473 if (info != null && info.isNoCompile()) {
1474 input.getModule().remove(input);
1475 staleInputs = true;
1476 }
1477 }
1478
1479 if (staleInputs) {
1480 repartitionInputs();
1481 }
1482 }
1483
1484 private void repartitionInputs() {
1485 fillEmptyModules(modules);
1486 rebuildInputsFromModules();
1487 }
1488
1489 /**
1490 * Transforms AMD and CJS modules to something closure compiler can
1491 * process and creates JSModules and the corresponding dependency tree
1492 * on the way.
1493 */
1494 void processAMDAndCommonJSModules() {
1495 Map<String, JSModule> modulesByName = Maps.newLinkedHashMap();
1496 Map<CompilerInput, JSModule> modulesByInput = Maps.newLinkedHashMap();
1497 // TODO(nicksantos): Refactor module dependency resolution to work nicely
1498 // with multiple ways to express dependencies. Directly support JSModules
1499 // that are equivalent to a signal file and which express their deps
1500 // directly in the source.
1501 for (CompilerInput input : inputs) {
1502 input.setCompiler(this);
1503 Node root = input.getAstRoot(this);
1504 if (root == null) {
1505 continue;
1506 }
1507 if (options.transformAMDToCJSModules) {
1508 new TransformAMDToCJSModule(this).process(null, root);
1509 }
1510 if (options.processCommonJSModules) {
1511 ProcessCommonJSModules cjs = new ProcessCommonJSModules(this,
1512 options.commonJSModulePathPrefix);
1513 cjs.process(null, root);
1514 JSModule m = cjs.getModule();
1515 if (m != null) {
1516 modulesByName.put(m.getName(), m);
1517 modulesByInput.put(input, m);
1518 }
1519 }
1520 }
1521 if (options.processCommonJSModules) {
1522 List<JSModule> modules = Lists.newArrayList(modulesByName.values());
1523 if (!modules.isEmpty()) {
1524 this.modules = modules;
1525 this.moduleGraph = new JSModuleGraph(this.modules);
1526 }
1527 for (JSModule module : modules) {
1528 for (CompilerInput input : module.getInputs()) {
1529 for (String require : input.getRequires()) {
1530 JSModule dependency = modulesByName.get(require);
1531 if (dependency == null) {
1532 report(JSError.make(MISSING_ENTRY_ERROR, require));
1533 } else {
1534 module.addDependency(dependency);
1535 }
1536 }
1537 }
1538 }
1539 try {
1540 modules = Lists.newArrayList();
1541 for (CompilerInput input : this.moduleGraph.manageDependencies(
1542 options.dependencyOptions, inputs)) {
1543 modules.add(modulesByInput.get(input));
1544 }
1545 JSModule root = new JSModule("root");
1546 for (JSModule m : modules) {
1547 m.addDependency(root);
1548 }
1549 modules.add(0, root);
1550 SortedDependencies<JSModule> sorter =
1551 new SortedDependencies<JSModule>(modules);
1552 modules = sorter.getDependenciesOf(modules, true);
1553 this.modules = modules;
1554
1555 this.moduleGraph = new JSModuleGraph(modules);
1556 } catch (Exception e) {
1557 Throwables.propagate(e);
1558 }
1559 }
1560 }
1561
1562 public Node parse(SourceFile file) {
1563 initCompilerOptionsIfTesting();
1564 addToDebugLog("Parsing: " + file.getName());
1565 return new JsAst(file).getAstRoot(this);
1566 }
1567
1568 private int syntheticCodeId = 0;
1569
1570 @Override
1571 Node parseSyntheticCode(String js) {
1572 CompilerInput input = new CompilerInput(
1573 SourceFile.fromCode(" [synthetic:" + (++syntheticCodeId) + "] ", js));
1574 putCompilerInput(input.getInputId(), input);
1575 return input.getAstRoot(this);
1576 }
1577
1578 /**
1579 * Allow subclasses to override the default CompileOptions object.
1580 */
1581 protected CompilerOptions newCompilerOptions() {
1582 return new CompilerOptions();
1583 }
1584
1585 void initCompilerOptionsIfTesting() {
1586 if (options == null) {
1587 // initialization for tests that don't initialize the compiler
1588 // by the normal mechanisms.
1589 initOptions(newCompilerOptions());
1590 }
1591 }
1592
1593 @Override
1594 Node parseSyntheticCode(String fileName, String js) {
1595 initCompilerOptionsIfTesting();
1596 return parse(SourceFile.fromCode(fileName, js));
1597 }
1598
1599 @Override
1600 Node parseTestCode(String js) {
1601 initCompilerOptionsIfTesting();
1602 CompilerInput input = new CompilerInput(
1603 SourceFile.fromCode("[testcode]", js));
1604 if (inputsById == null) {
1605 inputsById = Maps.newHashMap();
1606 }
1607 putCompilerInput(input.getInputId(), input);
1608 return input.getAstRoot(this);
1609 }
1610
1611 @Override
1612 ErrorReporter getDefaultErrorReporter() {
1613 return defaultErrorReporter;
1614 }
1615
1616 //------------------------------------------------------------------------
1617 // Convert back to source code
1618 //------------------------------------------------------------------------
1619
1620 /**
1621 * Converts the main parse tree back to JS code.
1622 */
1623 public String toSource() {
1624 return runInCompilerThread(new Callable<String>() {
1625 @Override
1626 public String call() throws Exception {
1627 Tracer tracer = newTracer("toSource");
1628 try {
1629 CodeBuilder cb = new CodeBuilder();
1630 if (jsRoot != null) {
1631 int i = 0;
1632 for (Node scriptNode = jsRoot.getFirstChild();
1633 scriptNode != null;
1634 scriptNode = scriptNode.getNext()) {
1635 toSource(cb, i++, scriptNode);
1636 }
1637 }
1638 return cb.toString();
1639 } finally {
1640 stopTracer(tracer, "toSource");
1641 }
1642 }
1643 });
1644 }
1645
1646 /**
1647 * Converts the parse tree for each input back to JS code.
1648 */
1649 public String[] toSourceArray() {
1650 return runInCompilerThread(new Callable<String[]>() {
1651 @Override
1652 public String[] call() throws Exception {
1653 Tracer tracer = newTracer("toSourceArray");
1654 try {
1655 int numInputs = inputs.size();
1656 String[] sources = new String[numInputs];
1657 CodeBuilder cb = new CodeBuilder();
1658 for (int i = 0; i < numInputs; i++) {
1659 Node scriptNode = inputs.get(i).getAstRoot(Compiler.this);
1660 cb.reset();
1661 toSource(cb, i, scriptNode);
1662 sources[i] = cb.toString();
1663 }
1664 return sources;
1665 } finally {
1666 stopTracer(tracer, "toSourceArray");
1667 }
1668 }
1669 });
1670 }
1671
1672 /**
1673 * Converts the parse tree for a module back to JS code.
1674 */
1675 public String toSource(final JSModule module) {
1676 return runInCompilerThread(new Callable<String>() {
1677 @Override
1678 public String call() throws Exception {
1679 List<CompilerInput> inputs = module.getInputs();
1680 int numInputs = inputs.size();
1681 if (numInputs == 0) {
1682 return "";
1683 }
1684 CodeBuilder cb = new CodeBuilder();
1685 for (int i = 0; i < numInputs; i++) {
1686 Node scriptNode = inputs.get(i).getAstRoot(Compiler.this);
1687 if (scriptNode == null) {
1688 throw new IllegalArgumentException(
1689 "Bad module: " + module.getName());
1690 }
1691 toSource(cb, i, scriptNode);
1692 }
1693 return cb.toString();
1694 }
1695 });
1696 }
1697
1698
1699 /**
1700 * Converts the parse tree for each input in a module back to JS code.
1701 */
1702 public String[] toSourceArray(final JSModule module) {
1703 return runInCompilerThread(new Callable<String[]>() {
1704 @Override
1705 public String[] call() throws Exception {
1706 List<CompilerInput> inputs = module.getInputs();
1707 int numInputs = inputs.size();
1708 if (numInputs == 0) {
1709 return new String[0];
1710 }
1711
1712 String[] sources = new String[numInputs];
1713 CodeBuilder cb = new CodeBuilder();
1714 for (int i = 0; i < numInputs; i++) {
1715 Node scriptNode = inputs.get(i).getAstRoot(Compiler.this);
1716 if (scriptNode == null) {
1717 throw new IllegalArgumentException(
1718 "Bad module input: " + inputs.get(i).getName());
1719 }
1720
1721 cb.reset();
1722 toSource(cb, i, scriptNode);
1723 sources[i] = cb.toString();
1724 }
1725 return sources;
1726 }
1727 });
1728 }
1729
1730 /**
1731 * Writes out JS code from a root node. If printing input delimiters, this
1732 * method will attach a comment to the start of the text indicating which
1733 * input the output derived from. If there were any preserve annotations
1734 * within the root's source, they will also be printed in a block comment
1735 * at the beginning of the output.
1736 */
1737 public void toSource(final CodeBuilder cb,
1738 final int inputSeqNum,
1739 final Node root) {
1740 runInCompilerThread(new Callable<Void>() {
1741 @Override
1742 public Void call() throws Exception {
1743 if (options.printInputDelimiter) {
1744 if ((cb.getLength() > 0) && !cb.endsWith("\n")) {
1745 cb.append("\n"); // Make sure that the label starts on a new line
1746 }
1747 Preconditions.checkState(root.isScript());
1748
1749 String delimiter = options.inputDelimiter;
1750
1751 String inputName = root.getInputId().getIdName();
1752 String sourceName = root.getSourceFileName();
1753 Preconditions.checkState(sourceName != null);
1754 Preconditions.checkState(!sourceName.isEmpty());
1755
1756 delimiter = delimiter
1757 .replaceAll("%name%", Matcher.quoteReplacement(inputName))
1758 .replaceAll("%num%", String.valueOf(inputSeqNum));
1759
1760 cb.append(delimiter)
1761 .append("\n");
1762 }
1763 if (root.getJSDocInfo() != null &&
1764 root.getJSDocInfo().getLicense() != null) {
1765 cb.append("/*\n")
1766 .append(root.getJSDocInfo().getLicense())
1767 .append("*/\n");
1768 }
1769
1770 // If there is a valid source map, then indicate to it that the current
1771 // root node's mappings are offset by the given string builder buffer.
1772 if (options.sourceMapOutputPath != null) {
1773 sourceMap.setStartingPosition(
1774 cb.getLineIndex(), cb.getColumnIndex());
1775 }
1776
1777 // if LanguageMode is ECMASCRIPT5_STRICT, only print 'use strict'
1778 // for the first input file
1779 String code = toSource(root, sourceMap, inputSeqNum == 0);
1780 if (!code.isEmpty()) {
1781 cb.append(code);
1782
1783 // In order to avoid parse ambiguity when files are concatenated
1784 // together, all files should end in a semi-colon. Do a quick
1785 // heuristic check if there's an obvious semi-colon already there.
1786 int length = code.length();
1787 char lastChar = code.charAt(length - 1);
1788 char secondLastChar = length >= 2 ?
1789 code.charAt(length - 2) : '\0';
1790 boolean hasSemiColon = lastChar == ';' ||
1791 (lastChar == '\n' && secondLastChar == ';');
1792 if (!hasSemiColon) {
1793 cb.append(";");
1794 }
1795 }
1796 return null;
1797 }
1798 });
1799 }
1800
1801 /**
1802 * Generates JavaScript source code for an AST, doesn't generate source
1803 * map info.
1804 */
1805 @Override
1806 String toSource(Node n) {
1807 initCompilerOptionsIfTesting();
1808 return toSource(n, null, true);
1809 }
1810
1811 /**
1812 * Generates JavaScript source code for an AST.
1813 */
1814 private String toSource(Node n, SourceMap sourceMap, boolean firstOutput) {
1815 CodePrinter.Builder builder = new CodePrinter.Builder(n);
1816 builder.setCompilerOptions(options);
1817 builder.setSourceMap(sourceMap);
1818 builder.setTagAsStrict(firstOutput &&
1819 options.getLanguageOut() == LanguageMode.ECMASCRIPT5_STRICT);
1820 return builder.build();
1821 }
1822
1823 /**
1824 * Stores a buffer of text to which more can be appended. This is just like a
1825 * StringBuilder except that we also track the number of lines.
1826 */
1827 public static class CodeBuilder {
1828 private final StringBuilder sb = new StringBuilder();
1829 private int lineCount = 0;
1830 private int colCount = 0;
1831
1832 /** Removes all text, but leaves the line count unchanged. */
1833 void reset() {
1834 sb.setLength(0);
1835 }
1836
1837 /** Appends the given string to the text buffer. */
1838 CodeBuilder append(String str) {
1839 sb.append(str);
1840
1841 // Adjust the line and column information for the new text.
1842 int index = -1;
1843 int lastIndex = index;
1844 while ((index = str.indexOf('\n', index + 1)) >= 0) {
1845 ++lineCount;
1846 lastIndex = index;
1847 }
1848
1849 if (lastIndex == -1) {
1850 // No new lines, append the new characters added.
1851 colCount += str.length();
1852 } else {
1853 colCount = str.length() - (lastIndex + 1);
1854 }
1855
1856 return this;
1857 }
1858
1859 /** Returns all text in the text buffer. */
1860 @Override
1861 public String toString() {
1862 return sb.toString();
1863 }
1864
1865 /** Returns the length of the text buffer. */
1866 public int getLength() {
1867 return sb.length();
1868 }
1869
1870 /** Returns the (zero-based) index of the last line in the text buffer. */
1871 int getLineIndex() {
1872 return lineCount;
1873 }
1874
1875 /** Returns the (zero-based) index of the last column in the text buffer. */
1876 int getColumnIndex() {
1877 return colCount;
1878 }
1879
1880 /** Determines whether the text ends with the given suffix. */
1881 boolean endsWith(String suffix) {
1882 return (sb.length() > suffix.length())
1883 && suffix.equals(sb.substring(sb.length() - suffix.length()));
1884 }
1885 }
1886
1887 //------------------------------------------------------------------------
1888 // Optimizations
1889 //------------------------------------------------------------------------
1890
1891 public void optimize() {
1892 // Ideally, this pass should be the first pass run, however:
1893 // 1) VariableReferenceCheck reports unexpected warnings if Normalize
1894 // is done first.
1895 // 2) ReplaceMessages, stripCode, and potentially custom passes rely on
1896 // unmodified local names.
1897 normalize();
1898
1899 PhaseOptimizer phaseOptimizer = new PhaseOptimizer(this, tracker, null);
1900 if (options.devMode == DevMode.EVERY_PASS) {
1901 phaseOptimizer.setSanityCheck(sanityCheck);
1902 }
1903 if (options.getCheckDeterminism()) {
1904 phaseOptimizer.setPrintAstHashcodes(true);
1905 }
1906 phaseOptimizer.consume(getPassConfig().getOptimizations());
1907 phaseOptimizer.process(externsRoot, jsRoot);
1908 }
1909
1910 @Override
1911 void setCssRenamingMap(CssRenamingMap map) {
1912 options.cssRenamingMap = map;
1913 }
1914
1915 @Override
1916 CssRenamingMap getCssRenamingMap() {
1917 return options.cssRenamingMap;
1918 }
1919
1920 /**
1921 * Reprocesses the current defines over the AST. This is used by GwtCompiler
1922 * to generate N outputs for different targets from the same (checked) AST.
1923 * For each target, we apply the target-specific defines by calling
1924 * {@code processDefines} and then {@code optimize} to optimize the AST
1925 * specifically for that target.
1926 */
1927 public void processDefines() {
1928 (new DefaultPassConfig(options)).processDefines.create(this)
1929 .process(externsRoot, jsRoot);
1930 }
1931
1932 boolean isInliningForbidden() {
1933 return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC ||
1934 options.propertyRenaming ==
1935 PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC;
1936 }
1937
1938 /** Control Flow Analysis. */
1939 ControlFlowGraph<Node> computeCFG() {
1940 logger.fine("Computing Control Flow Graph");
1941 Tracer tracer = newTracer("computeCFG");
1942 ControlFlowAnalysis cfa = new ControlFlowAnalysis(this, true, false);
1943 process(cfa);
1944 stopTracer(tracer, "computeCFG");
1945 return cfa.getCfg();
1946 }
1947
1948 public void normalize() {
1949 logger.fine("Normalizing");
1950 startPass("normalize");
1951 process(new Normalize(this, false));
1952 endPass();
1953 }
1954
1955 @Override
1956 void prepareAst(Node root) {
1957 CompilerPass pass = new PrepareAst(this);
1958 pass.process(null, root);
1959 }
1960
1961 void recordFunctionInformation() {
1962 logger.fine("Recording function information");
1963 startPass("recordFunctionInformation");
1964 RecordFunctionInformation recordFunctionInfoPass =
1965 new RecordFunctionInformation(
1966 this, getPassConfig().getIntermediateState().functionNames);
1967 process(recordFunctionInfoPass);
1968 functionInformationMap = recordFunctionInfoPass.getMap();
1969 endPass();
1970 }
1971
1972 protected final CodeChangeHandler recentChange = new CodeChangeHandler();
1973 private final List<CodeChangeHandler> codeChangeHandlers =
1974 Lists.<CodeChangeHandler>newArrayList();
1975
1976 /** Name of the synthetic input that holds synthesized externs. */
1977 static final String SYNTHETIC_EXTERNS = "{SyntheticVarsDeclar}";
1978
1979 private CompilerInput synthesizedExternsInput = null;
1980
1981 @Override
1982 void addChangeHandler(CodeChangeHandler handler) {
1983 codeChangeHandlers.add(handler);
1984 }
1985
1986 @Override
1987 void removeChangeHandler(CodeChangeHandler handler) {
1988 codeChangeHandlers.remove(handler);
1989 }
1990
1991 /**
1992 * All passes should call reportCodeChange() when they alter
1993 * the JS tree structure. This is verified by CompilerTestCase.
1994 * This allows us to optimize to a fixed point.
1995 */
1996 @Override
1997 public void reportCodeChange() {
1998 for (CodeChangeHandler handler : codeChangeHandlers) {
1999 handler.reportChange();
2000 }
2001 }
2002
2003 @Override
2004 public CodingConvention getCodingConvention() {
2005 CodingConvention convention = options.getCodingConvention();
2006 convention = convention != null ? convention : defaultCodingConvention;
2007 return convention;
2008 }
2009
2010 @Override
2011 public boolean isIdeMode() {
2012 return options.ideMode;
2013 }
2014
2015 @Override
2016 public boolean acceptEcmaScript5() {
2017 switch (options.getLanguageIn()) {
2018 case ECMASCRIPT5:
2019 case ECMASCRIPT5_STRICT:
2020 return true;
2021 case ECMASCRIPT3:
2022 return false;
2023 }
2024 throw new IllegalStateException("unexpected language mode");
2025 }
2026
2027 public LanguageMode languageMode() {
2028 return options.getLanguageIn();
2029 }
2030
2031 @Override
2032 public boolean acceptConstKeyword() {
2033 return options.acceptConstKeyword;
2034 }
2035
2036 @Override
2037 Config getParserConfig() {
2038 if (parserConfig == null) {
2039 Config.LanguageMode mode;
2040 switch (options.getLanguageIn()) {
2041 case ECMASCRIPT3:
2042 mode = Config.LanguageMode.ECMASCRIPT3;
2043 break;
2044 case ECMASCRIPT5:
2045 mode = Config.LanguageMode.ECMASCRIPT5;
2046 break;
2047 case ECMASCRIPT5_STRICT:
2048 mode = Config.LanguageMode.ECMASCRIPT5_STRICT;
2049 break;
2050 default:
2051 throw new IllegalStateException("unexpected language mode");
2052 }
2053
2054 parserConfig = ParserRunner.createConfig(
2055 isIdeMode(),
2056 mode,
2057 acceptConstKeyword(),
2058 options.extraAnnotationNames);
2059 }
2060 return parserConfig;
2061 }
2062
2063 @Override
2064 public boolean isTypeCheckingEnabled() {
2065 return options.checkTypes;
2066 }
2067
2068
2069 //------------------------------------------------------------------------
2070 // Error reporting
2071 //------------------------------------------------------------------------
2072
2073 /**
2074 * The warning classes that are available from the command-line, and
2075 * are suppressible by the {@code @suppress} annotation.
2076 */
2077 protected DiagnosticGroups getDiagnosticGroups() {
2078 return new DiagnosticGroups();
2079 }
2080
2081 @Override
2082 public void report(JSError error) {
2083 CheckLevel level = error.getDefaultLevel();
2084 if (warningsGuard != null) {
2085 CheckLevel newLevel = warningsGuard.level(error);
2086 if (newLevel != null) {
2087 level = newLevel;
2088 }
2089 }
2090
2091 if (level.isOn()) {
2092 if (getOptions().errorHandler != null) {
2093 getOptions().errorHandler.report(level, error);
2094 }
2095 errorManager.report(level, error);
2096 }
2097 }
2098
2099 @Override
2100 public CheckLevel getErrorLevel(JSError error) {
2101 Preconditions.checkNotNull(options);
2102 return warningsGuard.level(error);
2103 }
2104
2105 /**
2106 * Report an internal error.
2107 */
2108 @Override
2109 void throwInternalError(String message, Exception cause) {
2110 String finalMessage =
2111 "INTERNAL COMPILER ERROR.\n" +
2112 "Please report this problem.\n" + message;
2113
2114 RuntimeException e = new RuntimeException(finalMessage, cause);
2115 if (cause != null) {
2116 e.setStackTrace(cause.getStackTrace());
2117 }
2118 throw e;
2119 }
2120
2121
2122 /**
2123 * Gets the number of errors.
2124 */
2125 public int getErrorCount() {
2126 return errorManager.getErrorCount();
2127 }
2128
2129 /**
2130 * Gets the number of warnings.
2131 */
2132 public int getWarningCount() {
2133 return errorManager.getWarningCount();
2134 }
2135
2136 @Override
2137 boolean hasHaltingErrors() {
2138 return !isIdeMode() && getErrorCount() > 0;
2139 }
2140
2141 /**
2142 * Consults the {@link ErrorManager} to see if we've encountered errors
2143 * that should halt compilation. <p>
2144 *
2145 * If {@link CompilerOptions#ideMode} is {@code true}, this function
2146 * always returns {@code false} without consulting the error manager. The
2147 * error manager will continue to be told about new errors and warnings, but
2148 * the compiler will complete compilation of all inputs.<p>
2149 */
2150 public boolean hasErrors() {
2151 return hasHaltingErrors();
2152 }
2153
2154 /** Called from the compiler passes, adds debug info */
2155 @Override
2156 void addToDebugLog(String str) {
2157 debugLog.append(str);
2158 debugLog.append('\n');
2159 logger.fine(str);
2160 }
2161
2162 @Override
2163 SourceFile getSourceFileByName(String sourceName) {
2164 // Here we assume that the source name is the input name, this
2165 // is try of JavaScript parsed from source.
2166 if (sourceName != null) {
2167 CompilerInput input = inputsById.get(new InputId(sourceName));
2168 if (input != null) {
2169 return input.getSourceFile();
2170 }
2171 }
2172 return null;
2173 }
2174
2175 @Override
2176 public String getSourceLine(String sourceName, int lineNumber) {
2177 if (lineNumber < 1) {
2178 return null;
2179 }
2180 SourceFile input = getSourceFileByName(sourceName);
2181 if (input != null) {
2182 return input.getLine(lineNumber);
2183 }
2184 return null;
2185 }
2186
2187 @Override
2188 public Region getSourceRegion(String sourceName, int lineNumber) {
2189 if (lineNumber < 1) {
2190 return null;
2191 }
2192 SourceFile input = getSourceFileByName(sourceName);
2193 if (input != null) {
2194 return input.getRegion(lineNumber);
2195 }
2196 return null;
2197 }
2198
2199 //------------------------------------------------------------------------
2200 // Package-private helpers
2201 //------------------------------------------------------------------------
2202
2203 @Override
2204 Node getNodeForCodeInsertion(JSModule module) {
2205 if (module == null) {
2206 if (inputs.isEmpty()) {
2207 throw new IllegalStateException("No inputs");
2208 }
2209
2210 return inputs.get(0).getAstRoot(this);
2211 }
2212
2213 List<CompilerInput> moduleInputs = module.getInputs();
2214 if (moduleInputs.size() > 0) {
2215 return moduleInputs.get(0).getAstRoot(this);
2216 }
2217 throw new IllegalStateException("Root module has no inputs");
2218 }
2219
2220 public SourceMap getSourceMap() {
2221 return sourceMap;
2222 }
2223
2224 VariableMap getVariableMap() {
2225 return getPassConfig().getIntermediateState().variableMap;
2226 }
2227
2228 VariableMap getPropertyMap() {
2229 return getPassConfig().getIntermediateState().propertyMap;
2230 }
2231
2232 CompilerOptions getOptions() {
2233 return options;
2234 }
2235
2236 FunctionInformationMap getFunctionalInformationMap() {
2237 return functionInformationMap;
2238 }
2239
2240 /**
2241 * Sets the logging level for the com.google.javascript.jscomp package.
2242 */
2243 public static void setLoggingLevel(Level level) {
2244 logger.setLevel(level);
2245 }
2246
2247 /** Gets the DOT graph of the AST generated at the end of compilation. */
2248 public String getAstDotGraph() throws IOException {
2249 if (jsRoot != null) {
2250 ControlFlowAnalysis cfa = new ControlFlowAnalysis(this, true, false);
2251 cfa.process(null, jsRoot);
2252 return DotFormatter.toDot(jsRoot, cfa.getCfg());
2253 } else {
2254 return "";
2255 }
2256 }
2257
2258 @Override
2259 public ErrorManager getErrorManager() {
2260 if (options == null) {
2261 initOptions(newCompilerOptions());
2262 }
2263 return errorManager;
2264 }
2265
2266 @Override
2267 List<CompilerInput> getInputsInOrder() {
2268 return Collections.<CompilerInput>unmodifiableList(inputs);
2269 }
2270
2271 /**
2272 * Returns an unmodifiable view of the compiler inputs indexed by id.
2273 */
2274 public Map<InputId, CompilerInput> getInputsById() {
2275 return Collections.unmodifiableMap(inputsById);
2276 }
2277
2278 /**
2279 * Gets the externs in the order in which they are being processed.
2280 */
2281 List<CompilerInput> getExternsInOrder() {
2282 return Collections.<CompilerInput>unmodifiableList(externs);
2283 }
2284
2285 /**
2286 * Stores the internal compiler state just before optimization is performed.
2287 * This can be saved and restored in order to efficiently optimize multiple
2288 * different output targets without having to perform checking multiple times.
2289 *
2290 * NOTE: This does not include all parts of the compiler's internal state. In
2291 * particular, SourceFiles and CompilerOptions are not recorded. In
2292 * order to recreate a Compiler instance from scratch, you would need to
2293 * call {@code init} with the same arguments as in the initial creation before
2294 * restoring intermediate state.
2295 */
2296 public static class IntermediateState implements Serializable {
2297 private static final long serialVersionUID = 1L;
2298
2299 Node externsRoot;
2300 private Node jsRoot;
2301 private List<CompilerInput> externs;
2302 private List<CompilerInput> inputs;
2303 private List<JSModule> modules;
2304 private PassConfig.State passConfigState;
2305 private JSTypeRegistry typeRegistry;
2306 private AbstractCompiler.LifeCycleStage lifeCycleStage;
2307 private Map<String, Node> injectedLibraries;
2308
2309 private IntermediateState() {}
2310 }
2311
2312 /**
2313 * Returns the current internal state, excluding the input files and modules.
2314 */
2315 public IntermediateState getState() {
2316 IntermediateState state = new IntermediateState();
2317 state.externsRoot = externsRoot;
2318 state.jsRoot = jsRoot;
2319 state.externs = externs;
2320 state.inputs = inputs;
2321 state.modules = modules;
2322 state.passConfigState = getPassConfig().getIntermediateState();
2323 state.typeRegistry = typeRegistry;
2324 state.lifeCycleStage = getLifeCycleStage();
2325 state.injectedLibraries = Maps.newLinkedHashMap(injectedLibraries);
2326
2327 return state;
2328 }
2329
2330 /**
2331 * Sets the internal state to the capture given. Note that this assumes that
2332 * the input files are already set up.
2333 */
2334 public void setState(IntermediateState state) {
2335 externsRoot = state.externsRoot;
2336 jsRoot = state.jsRoot;
2337 externs = state.externs;
2338 inputs = state.inputs;
2339 modules = state.modules;
2340 passes = createPassConfigInternal();
2341 getPassConfig().setIntermediateState(state.passConfigState);
2342 typeRegistry = state.typeRegistry;
2343 setLifeCycleStage(state.lifeCycleStage);
2344
2345 injectedLibraries.clear();
2346 injectedLibraries.putAll(state.injectedLibraries);
2347 }
2348
2349 @VisibleForTesting
2350 List<CompilerInput> getInputsForTesting() {
2351 return inputs;
2352 }
2353
2354 @VisibleForTesting
2355 List<CompilerInput> getExternsForTesting() {
2356 return externs;
2357 }
2358
2359 @Override
2360 boolean hasRegExpGlobalReferences() {
2361 return hasRegExpGlobalReferences;
2362 }
2363
2364 @Override
2365 void setHasRegExpGlobalReferences(boolean references) {
2366 hasRegExpGlobalReferences = references;
2367 }
2368
2369 @Override
2370 void updateGlobalVarReferences(Map<Var, ReferenceCollection> refMapPatch,
2371 Node collectionRoot) {
2372 Preconditions.checkState(collectionRoot.isScript()
2373 || collectionRoot.isBlock());
2374 if (globalRefMap == null) {
2375 globalRefMap = new GlobalVarReferenceMap(getInputsInOrder(),
2376 getExternsInOrder());
2377 }
2378 globalRefMap.updateGlobalVarReferences(refMapPatch, collectionRoot);
2379 }
2380
2381 @Override
2382 GlobalVarReferenceMap getGlobalVarReferences() {
2383 return globalRefMap;
2384 }
2385
2386 @Override
2387 CompilerInput getSynthesizedExternsInput() {
2388 if (synthesizedExternsInput == null) {
2389 synthesizedExternsInput = newExternInput(SYNTHETIC_EXTERNS);
2390 }
2391 return synthesizedExternsInput;
2392 }
2393
2394 @Override
2395 public double getProgress() {
2396 return progress;
2397 }
2398
2399 @Override
2400 String getLastPassName() {
2401 return lastPassName;
2402 }
2403
2404 @Override
2405 void setProgress(double newProgress, String passName) {
2406 this.lastPassName = passName;
2407 if (newProgress > 1.0) {
2408 progress = 1.0;
2409 } else {
2410 progress = newProgress;
2411 }
2412 }
2413
2414 /**
2415 * Replaces one file in a hot-swap mode. The given JsAst should be made
2416 * from a new version of a file that already was present in the last compile
2417 * call. If the file is new, this will silently ignored.
2418 *
2419 * @param ast the ast of the file that is being replaced
2420 */
2421 public void replaceScript(JsAst ast) {
2422 CompilerInput input = this.getInput(ast.getInputId());
2423 if (!replaceIncrementalSourceAst(ast)) {
2424 return;
2425 }
2426 Node originalRoot = input.getAstRoot(this);
2427
2428 processNewScript(ast, originalRoot);
2429 }
2430
2431 /**
2432 * Adds a new Script AST to the compile state. If a script for the same file
2433 * already exists the script will not be added, instead a call to
2434 * #replaceScript should be used.
2435 *
2436 * @param ast the ast of the new file
2437 */
2438 public void addNewScript(JsAst ast) {
2439 if (!addNewSourceAst(ast)) {
2440 return;
2441 }
2442 Node emptyScript = new Node(Token.SCRIPT);
2443 InputId inputId = ast.getInputId();
2444 emptyScript.setInputId(inputId);
2445 emptyScript.setStaticSourceFile(
2446 SourceFile.fromCode(inputId.getIdName(), ""));
2447
2448 processNewScript(ast, emptyScript);
2449 }
2450
2451 private void processNewScript(JsAst ast, Node originalRoot) {
2452 Node js = ast.getAstRoot(this);
2453 Preconditions.checkNotNull(js);
2454
2455 runHotSwap(originalRoot, js, this.getCleanupPassConfig());
2456 // NOTE: If hot swap passes that use GlobalNamespace are added, we will need
2457 // to revisit this approach to clearing GlobalNamespaces
2458 runHotSwapPass(null, null, ensureDefaultPassConfig().garbageCollectChecks);
2459
2460 this.getTypeRegistry().clearNamedTypes();
2461 this.removeSyntheticVarsInput();
2462
2463 runHotSwap(originalRoot, js, this.ensureDefaultPassConfig());
2464 }
2465
2466 /**
2467 * Execute the passes from a PassConfig instance over a single replaced file.
2468 */
2469 private void runHotSwap(
2470 Node originalRoot, Node js, PassConfig passConfig) {
2471 for (PassFactory passFactory : passConfig.getChecks()) {
2472 runHotSwapPass(originalRoot, js, passFactory);
2473 }
2474 }
2475
2476 private void runHotSwapPass(
2477 Node originalRoot, Node js, PassFactory passFactory) {
2478 HotSwapCompilerPass pass = passFactory.getHotSwapPass(this);
2479 if (pass != null) {
2480 logger.info("Performing HotSwap for pass " + passFactory.getName());
2481 pass.hotSwapScript(js, originalRoot);
2482 }
2483 }
2484
2485 private PassConfig getCleanupPassConfig() {
2486 return new CleanupPasses(getOptions());
2487 }
2488
2489 private void removeSyntheticVarsInput() {
2490 String sourceName = Compiler.SYNTHETIC_EXTERNS;
2491 removeExternInput(new InputId(sourceName));
2492 }
2493
2494 @Override
2495 Node ensureLibraryInjected(String resourceName) {
2496 if (injectedLibraries.containsKey(resourceName)) {
2497 return null;
2498 }
2499
2500 // All libraries depend on js/base.js
2501 boolean isBase = "base".equals(resourceName);
2502 if (!isBase) {
2503 ensureLibraryInjected("base");
2504 }
2505
2506 Node firstChild = loadLibraryCode(resourceName).removeChildren();
2507 Node lastChild = firstChild.getLastSibling();
2508
2509 Node parent = getNodeForCodeInsertion(null);
2510 if (isBase) {
2511 parent.addChildrenToFront(firstChild);
2512 } else {
2513 parent.addChildrenAfter(
2514 firstChild, injectedLibraries.get("base"));
2515 }
2516 reportCodeChange();
2517
2518 injectedLibraries.put(resourceName, lastChild);
2519 return lastChild;
2520 }
2521
2522 /** Load a library as a resource */
2523 @VisibleForTesting
2524 Node loadLibraryCode(String resourceName) {
2525 String originalCode;
2526 try {
2527 originalCode = CharStreams.toString(new InputStreamReader(
2528 Compiler.class.getResourceAsStream(
2529 String.format("js/%s.js", resourceName)),
2530 Charsets.UTF_8));
2531 } catch (IOException e) {
2532 throw new RuntimeException(e);
2533 }
2534
2535 return Normalize.parseAndNormalizeSyntheticCode(
2536 this, originalCode,
2537 String.format("jscomp_%s_", resourceName));
2538 }
2539
2540 /** Returns the compiler version baked into the jar. */
2541 public static String getReleaseVersion() {
2542 ResourceBundle config = ResourceBundle.getBundle(CONFIG_RESOURCE);
2543 return config.getString("compiler.version");
2544 }
2545
2546 /** Returns the compiler date baked into the jar. */
2547 public static String getReleaseDate() {
2548 ResourceBundle config = ResourceBundle.getBundle(CONFIG_RESOURCE);
2549 return config.getString("compiler.date");
2550 }
2551
2552 /**
2553 * {@inheritDoc}
2554 */
2555 @Override
2556 public void setOldParseTree(String sourceName, AstRoot oldAst) {
2557 }
2558
2559 /**
2560 * {@inheritDoc}
2561 */
2562 @Override
2563 public AstRoot getOldParseTreeByName(String sourceName) {
2564 return null;
2565 }
2566 }