Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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.Function;
22 import com.google.common.base.Joiner;
23 import com.google.common.base.Preconditions;
24 import com.google.common.base.Strings;
25 import com.google.common.base.Supplier;
26 import com.google.common.base.Throwables;
27 import com.google.common.collect.ImmutableList;
28 import com.google.common.collect.Iterables;
29 import com.google.common.collect.Lists;
30 import com.google.common.collect.Maps;
31 import com.google.common.collect.Sets;
32 import com.google.common.io.Files;
33 import com.google.javascript.jscomp.CompilerOptions.TweakProcessing;
34 import com.google.javascript.rhino.Node;
35 import com.google.javascript.rhino.TokenStream;
36 import com.google.protobuf.CodedOutputStream;
37
38 import java.io.BufferedWriter;
39 import java.io.Closeable;
40 import java.io.File;
41 import java.io.FileOutputStream;
42 import java.io.Flushable;
43 import java.io.IOException;
44 import java.io.OutputStream;
45 import java.io.OutputStreamWriter;
46 import java.io.PrintStream;
47 import java.io.StringWriter;
48 import java.io.Writer;
49 import java.nio.charset.Charset;
50 import java.util.ArrayList;
51 import java.util.Collections;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Set;
55 import java.util.logging.Level;
56
57 import javax.annotation.Nullable;
58
59 /**
60 * Implementations of AbstractCommandLineRunner translate flags into Java
61 * API calls on the Compiler. AbstractCompiler contains common flags and logic
62 * to make that happen.
63 *
64 * This class may be extended and used to create other Java classes
65 * that behave the same as running the Compiler from the command line. Example:
66 *
67 * <pre>
68 * class MyCommandLineRunner extends
69 * AbstractCommandLineRunner<MyCompiler, MyOptions> {
70 * MyCommandLineRunner(String[] args) {
71 * super(args);
72 * }
73 *
74 * &#064;Override
75 * protected MyOptions createOptions() {
76 * MyOptions options = new MyOptions();
77 * CompilerFlagTranslator.setOptionsFromFlags(options);
78 * addMyCrazyCompilerPassThatOutputsAnExtraFile(options);
79 * return options;
80 * }
81 *
82 * &#064;Override
83 * protected MyCompiler createCompiler() {
84 * return new MyCompiler();
85 * }
86 *
87 * public static void main(String[] args) {
88 * (new MyCommandLineRunner(args)).run();
89 * }
90 * }
91 * </pre>
92 *
93 * @author [email protected] (Michael Bolin)
94 */
95 abstract class AbstractCommandLineRunner<A extends Compiler,
96 B extends CompilerOptions> {
97 static final DiagnosticType OUTPUT_SAME_AS_INPUT_ERROR = DiagnosticType.error(
98 "JSC_OUTPUT_SAME_AS_INPUT_ERROR",
99 "Bad output file (already listed as input file): {0}");
100
101 private final CommandLineConfig config;
102
103 private Appendable jsOutput;
104 private final PrintStream err;
105 private A compiler;
106
107 private Charset inputCharset;
108
109 // NOTE(nicksantos): JSCompiler has always used ASCII as the default
110 // output charset. This was done to solve legacy problems with
111 // bad proxies, etc. We are not sure if these issues are still problems,
112 // and changing the encoding would require a big obnoxious migration plan.
113 //
114 // New outputs should use outputCharset2, which is how I would have
115 // designed this if I had a time machine.
116 private Charset outputCharset2;
117 private String legacyOutputCharset;
118
119 private boolean testMode = false;
120 private Supplier<List<SourceFile>> externsSupplierForTesting = null;
121 private Supplier<List<SourceFile>> inputsSupplierForTesting = null;
122 private Supplier<List<JSModule>> modulesSupplierForTesting = null;
123 private Function<Integer, Boolean> exitCodeReceiverForTesting = null;
124 private Map<String, String> rootRelativePathsMap = null;
125
126 private Map<String, String> parsedModuleWrappers = null;
127
128 // Bookkeeping to measure optimal phase orderings.
129 private static final int NUM_RUNS_TO_DETERMINE_OPTIMAL_ORDER = 100;
130
131 private static final String OUTPUT_MARKER = "%output%";
132 private static final String OUTPUT_MARKER_JS_STRING = "%output|jsstring%";
133
134 private final RunTimeStats runTimeStats = new RunTimeStats();
135
136 AbstractCommandLineRunner() {
137 this(System.out, System.err);
138 }
139
140 AbstractCommandLineRunner(PrintStream out, PrintStream err) {
141 this.config = new CommandLineConfig();
142 this.jsOutput = Preconditions.checkNotNull(out);
143 this.err = Preconditions.checkNotNull(err);
144 }
145
146 /**
147 * Put the command line runner into test mode. In test mode,
148 * all outputs will be blackholed.
149 * @param externsSupplier A provider for externs.
150 * @param inputsSupplier A provider for source inputs.
151 * @param modulesSupplier A provider for modules. Only one of inputsSupplier
152 * and modulesSupplier may be non-null.
153 * @param exitCodeReceiver A receiver for the status code that would
154 * have been passed to System.exit in non-test mode.
155 */
156 @VisibleForTesting
157 void enableTestMode(
158 Supplier<List<SourceFile>> externsSupplier,
159 Supplier<List<SourceFile>> inputsSupplier,
160 Supplier<List<JSModule>> modulesSupplier,
161 Function<Integer, Boolean> exitCodeReceiver) {
162 Preconditions.checkArgument(
163 inputsSupplier == null ^ modulesSupplier == null);
164 testMode = true;
165 this.externsSupplierForTesting = externsSupplier;
166 this.inputsSupplierForTesting = inputsSupplier;
167 this.modulesSupplierForTesting = modulesSupplier;
168 this.exitCodeReceiverForTesting = exitCodeReceiver;
169 }
170
171 /**
172 * Returns whether we're in test mode.
173 */
174 protected boolean isInTestMode() {
175 return testMode;
176 }
177
178 /**
179 * Get the command line config, so that it can be initialized.
180 */
181 protected CommandLineConfig getCommandLineConfig() {
182 return config;
183 }
184
185 /**
186 * Returns the instance of the Compiler to use when {@link #run()} is
187 * called.
188 */
189 protected abstract A createCompiler();
190
191 /**
192 * Returns the instance of the Options to use when {@link #run()} is called.
193 * createCompiler() is called before createOptions(), so getCompiler()
194 * will not return null when createOptions() is called.
195 */
196 protected abstract B createOptions();
197
198 /**
199 * The warning classes that are available from the command-line.
200 */
201 protected DiagnosticGroups getDiagnosticGroups() {
202 if (compiler == null) {
203 return new DiagnosticGroups();
204 }
205 return compiler.getDiagnosticGroups();
206 }
207
208 /**
209 * A helper function for creating the dependency options object.
210 */
211 static DependencyOptions createDependencyOptions(
212 boolean manageClosureDependencies,
213 boolean onlyClosureDependencies,
214 boolean processCommonJSModules,
215 List<String> closureEntryPoints)
216 throws FlagUsageException {
217 if (onlyClosureDependencies) {
218 if (closureEntryPoints.isEmpty()) {
219 throw new FlagUsageException("When only_closure_dependencies is "
220 + "on, you must specify at least one closure_entry_point");
221 }
222
223 return new DependencyOptions()
224 .setDependencyPruning(true)
225 .setDependencySorting(true)
226 .setMoocherDropping(true)
227 .setEntryPoints(closureEntryPoints);
228 } else if (processCommonJSModules) {
229 return new DependencyOptions()
230 .setDependencyPruning(false)
231 .setDependencySorting(true)
232 .setMoocherDropping(false)
233 .setEntryPoints(closureEntryPoints);
234 }
235 else if (manageClosureDependencies ||
236 closureEntryPoints.size() > 0) {
237 return new DependencyOptions()
238 .setDependencyPruning(true)
239 .setDependencySorting(true)
240 .setMoocherDropping(false)
241 .setEntryPoints(closureEntryPoints);
242 }
243 return null;
244 }
245
246 /**
247 * Sets options based on the configurations set flags API.
248 * Called during the run() run() method.
249 * If you want to ignore the flags API, or interpret flags your own way,
250 * then you should override this method.
251 */
252 protected void setRunOptions(CompilerOptions options)
253 throws FlagUsageException, IOException {
254 DiagnosticGroups diagnosticGroups = getDiagnosticGroups();
255
256 if (config.warningGuards != null) {
257 for (WarningGuardSpec.Entry entry : config.warningGuards.entries) {
258 diagnosticGroups.setWarningLevel(options, entry.groupName, entry.level);
259 }
260 }
261
262 if (!config.warningsWhitelistFile.isEmpty()) {
263 options.addWarningsGuard(
264 WhitelistWarningsGuard.fromFile(
265 new File(config.warningsWhitelistFile)));
266 }
267
268 createDefineOrTweakReplacements(config.define, options, false);
269
270 options.setTweakProcessing(config.tweakProcessing);
271 createDefineOrTweakReplacements(config.tweak, options, true);
272
273 DependencyOptions depOptions = createDependencyOptions(
274 config.manageClosureDependencies,
275 config.onlyClosureDependencies,
276 config.processCommonJSModules,
277 config.closureEntryPoints);
278 if (depOptions != null) {
279 options.setDependencyOptions(depOptions);
280 }
281
282 options.devMode = config.jscompDevMode;
283 options.setCodingConvention(config.codingConvention);
284 options.setSummaryDetailLevel(config.summaryDetailLevel);
285 options.setTrustedStrings(true);
286
287 legacyOutputCharset = options.outputCharset = getLegacyOutputCharset();
288 outputCharset2 = getOutputCharset2();
289 inputCharset = getInputCharset();
290
291 if (config.jsOutputFile.length() > 0) {
292 if (config.skipNormalOutputs) {
293 throw new FlagUsageException("skip_normal_outputs and js_output_file"
294 + " cannot be used together.");
295 }
296 }
297
298 if (config.skipNormalOutputs && config.printAst) {
299 throw new FlagUsageException("skip_normal_outputs and print_ast cannot"
300 + " be used together.");
301 }
302
303 if (config.skipNormalOutputs && config.printTree) {
304 throw new FlagUsageException("skip_normal_outputs and print_tree cannot"
305 + " be used together.");
306 }
307
308 if (config.createSourceMap.length() > 0) {
309 options.sourceMapOutputPath = config.createSourceMap;
310 }
311 options.sourceMapDetailLevel = config.sourceMapDetailLevel;
312 options.sourceMapFormat = config.sourceMapFormat;
313
314 if (!config.variableMapInputFile.equals("")) {
315 options.inputVariableMap =
316 VariableMap.load(config.variableMapInputFile);
317 }
318
319 if (!config.propertyMapInputFile.equals("")) {
320 options.inputPropertyMap =
321 VariableMap.load(config.propertyMapInputFile);
322 }
323
324 if (config.languageIn.length() > 0) {
325 CompilerOptions.LanguageMode languageMode =
326 CompilerOptions.LanguageMode.fromString(config.languageIn);
327 if (languageMode != null) {
328 options.setLanguageIn(languageMode);
329 } else {
330 throw new FlagUsageException("Unknown language `" + config.languageIn +
331 "' specified.");
332 }
333 }
334
335 if (!config.outputManifests.isEmpty()) {
336 Set<String> uniqueNames = Sets.newHashSet();
337 for (String filename : config.outputManifests) {
338 if (!uniqueNames.add(filename)) {
339 throw new FlagUsageException("output_manifest flags specify " +
340 "duplicate file names: " + filename);
341 }
342 }
343 }
344
345 if (!config.outputBundles.isEmpty()) {
346 Set<String> uniqueNames = Sets.newHashSet();
347 for (String filename : config.outputBundles) {
348 if (!uniqueNames.add(filename)) {
349 throw new FlagUsageException("output_bundle flags specify " +
350 "duplicate file names: " + filename);
351 }
352 }
353 }
354
355 options.acceptConstKeyword = config.acceptConstKeyword;
356 options.transformAMDToCJSModules = config.transformAMDToCJSModules;
357 options.processCommonJSModules = config.processCommonJSModules;
358 options.commonJSModulePathPrefix = config.commonJSModulePathPrefix;
359 options.angularPass = config.angularPass;
360 }
361
362 final protected A getCompiler() {
363 return compiler;
364 }
365
366 /**
367 * Runs the Compiler and calls System.exit() with the exit status of the
368 * compiler.
369 */
370 final public void run() {
371 int result = 0;
372 int runs = 1;
373 if (config.computePhaseOrdering) {
374 runs = NUM_RUNS_TO_DETERMINE_OPTIMAL_ORDER;
375 PhaseOptimizer.randomizeLoops();
376 }
377 try {
378 for (int i = 0; i < runs && result == 0; i++) {
379 runTimeStats.recordStartRun();
380 result = doRun();
381 runTimeStats.recordEndRun();
382 }
383 } catch (AbstractCommandLineRunner.FlagUsageException e) {
384 System.err.println(e.getMessage());
385 result = -1;
386 } catch (Throwable t) {
387 t.printStackTrace();
388 result = -2;
389 }
390
391 if (config.computePhaseOrdering) {
392 runTimeStats.outputBestPhaseOrdering();
393 }
394
395 try {
396 if (jsOutput instanceof Closeable) {
397 ((Closeable) jsOutput).close();
398 }
399 } catch (IOException e) {
400 throw Throwables.propagate(e);
401 }
402
403 if (testMode) {
404 exitCodeReceiverForTesting.apply(result);
405 } else {
406 System.exit(result);
407 }
408 }
409
410 /**
411 * Returns the PrintStream for writing errors associated with this
412 * AbstractCommandLineRunner.
413 */
414 protected PrintStream getErrorPrintStream() {
415 return err;
416 }
417
418 /**
419 * An exception thrown when command-line flags are used incorrectly.
420 */
421 public static class FlagUsageException extends Exception {
422 private static final long serialVersionUID = 1L;
423
424 public FlagUsageException(String message) {
425 super(message);
426 }
427 }
428
429 /**
430 * Creates inputs from a list of files.
431 *
432 * Can be overridden by subclasses who want to pull files from different
433 * places.
434 *
435 * @param files A list of filenames
436 * @param allowStdIn Whether '-' is allowed appear as a filename to represent
437 * stdin. If true, '-' is only allowed to appear once.
438 * @return An array of inputs
439 */
440 protected List<SourceFile> createInputs(List<String> files,
441 boolean allowStdIn) throws FlagUsageException, IOException {
442 List<SourceFile> inputs = new ArrayList<SourceFile>(files.size());
443 boolean usingStdin = false;
444 for (String filename : files) {
445 if (!"-".equals(filename)) {
446 SourceFile newFile = SourceFile.fromFile(filename, inputCharset);
447 inputs.add(newFile);
448 } else {
449 if (!allowStdIn) {
450 throw new FlagUsageException("Can't specify stdin.");
451 }
452 if (usingStdin) {
453 throw new FlagUsageException("Can't specify stdin twice.");
454 }
455
456 if (!config.outputManifests.isEmpty()) {
457 throw new FlagUsageException("Manifest files cannot be generated " +
458 "when the input is from stdin.");
459 }
460 if (!config.outputBundles.isEmpty()) {
461 throw new FlagUsageException("Bundle files cannot be generated " +
462 "when the input is from stdin.");
463 }
464 inputs.add(SourceFile.fromInputStream("stdin", System.in));
465 usingStdin = true;
466 }
467 }
468 return inputs;
469 }
470
471 /**
472 * Creates JS source code inputs from a list of files.
473 */
474 private List<SourceFile> createSourceInputs(List<String> files)
475 throws FlagUsageException, IOException {
476 if (isInTestMode()) {
477 return inputsSupplierForTesting.get();
478 }
479 if (files.isEmpty()) {
480 files = Collections.singletonList("-");
481 }
482 try {
483 return createInputs(files, true);
484 } catch (FlagUsageException e) {
485 throw new FlagUsageException("Bad --js flag. " + e.getMessage());
486 }
487 }
488
489 /**
490 * Creates JS extern inputs from a list of files.
491 */
492 private List<SourceFile> createExternInputs(List<String> files)
493 throws FlagUsageException, IOException {
494 if (files.isEmpty()) {
495 return ImmutableList.of(SourceFile.fromCode("/dev/null", ""));
496 }
497 try {
498 return createInputs(files, false);
499 } catch (FlagUsageException e) {
500 throw new FlagUsageException("Bad --externs flag. " + e.getMessage());
501 }
502 }
503
504 /**
505 * Creates module objects from a list of module specifications.
506 *
507 * @param specs A list of module specifications, not null or empty. The spec
508 * format is: <code>name:num-js-files[:[dep,...][:]]</code>. Module
509 * names must not contain the ':' character.
510 * @param jsFiles A list of JS file paths, not null
511 * @return An array of module objects
512 */
513 List<JSModule> createJsModules(
514 List<String> specs, List<String> jsFiles)
515 throws FlagUsageException, IOException {
516 if (isInTestMode()) {
517 return modulesSupplierForTesting.get();
518 }
519
520 Preconditions.checkState(specs != null);
521 Preconditions.checkState(!specs.isEmpty());
522 Preconditions.checkState(jsFiles != null);
523
524 final int totalNumJsFiles = jsFiles.size();
525 int nextJsFileIndex = 0;
526
527 Map<String, JSModule> modulesByName = Maps.newLinkedHashMap();
528 for (String spec : specs) {
529
530 // Format is "<name>:<num-js-files>[:[<dep>,...][:]]".
531 String[] parts = spec.split(":");
532 if (parts.length < 2 || parts.length > 4) {
533 throw new FlagUsageException("Expected 2-4 colon-delimited parts in "
534 + "module spec: " + spec);
535 }
536
537 // Parse module name.
538 String name = parts[0];
539 checkModuleName(name);
540 if (modulesByName.containsKey(name)) {
541 throw new FlagUsageException("Duplicate module name: " + name);
542 }
543 JSModule module = new JSModule(name);
544
545 // Parse module inputs.
546 int numJsFiles = -1;
547 try {
548 numJsFiles = Integer.parseInt(parts[1]);
549 } catch (NumberFormatException ignored) {
550 numJsFiles = -1;
551 }
552
553 // We will allow modules of zero input.
554 if (numJsFiles < 0) {
555 throw new FlagUsageException("Invalid JS file count '" + parts[1]
556 + "' for module: " + name);
557 }
558 if (nextJsFileIndex + numJsFiles > totalNumJsFiles) {
559 throw new FlagUsageException("Not enough JS files specified. Expected "
560 + (nextJsFileIndex + numJsFiles - totalNumJsFiles)
561 + " more in module:" + name);
562 }
563 List<String> moduleJsFiles =
564 jsFiles.subList(nextJsFileIndex, nextJsFileIndex + numJsFiles);
565 for (SourceFile input : createInputs(moduleJsFiles, false)) {
566 module.add(input);
567 }
568 nextJsFileIndex += numJsFiles;
569
570 if (parts.length > 2) {
571 // Parse module dependencies.
572 String depList = parts[2];
573 if (depList.length() > 0) {
574 String[] deps = depList.split(",");
575 for (String dep : deps) {
576 JSModule other = modulesByName.get(dep);
577 if (other == null) {
578 throw new FlagUsageException("Module '" + name
579 + "' depends on unknown module '" + dep
580 + "'. Be sure to list modules in dependency order.");
581 }
582 module.addDependency(other);
583 }
584 }
585 }
586
587 modulesByName.put(name, module);
588 }
589
590 if (nextJsFileIndex < totalNumJsFiles) {
591 throw new FlagUsageException("Too many JS files specified. Expected "
592 + nextJsFileIndex + " but found " + totalNumJsFiles);
593 }
594
595 return Lists.newArrayList(modulesByName.values());
596 }
597
598 /**
599 * Validates the module name. Can be overridden by subclasses.
600 * @param name The module name
601 * @throws FlagUsageException if the validation fails
602 */
603 protected void checkModuleName(String name)
604 throws FlagUsageException {
605 if (!TokenStream.isJSIdentifier(name)) {
606 throw new FlagUsageException("Invalid module name: '" + name + "'");
607 }
608 }
609
610 /**
611 * Parses module wrapper specifications.
612 *
613 * @param specs A list of module wrapper specifications, not null. The spec
614 * format is: <code>name:wrapper</code>. Wrappers.
615 * @param modules The JS modules whose wrappers are specified
616 * @return A map from module name to module wrapper. Modules with no wrapper
617 * will have the empty string as their value in this map.
618 */
619 static Map<String, String> parseModuleWrappers(List<String> specs,
620 List<JSModule> modules) throws FlagUsageException {
621 Preconditions.checkState(specs != null);
622
623 Map<String, String> wrappers =
624 Maps.newHashMapWithExpectedSize(modules.size());
625
626 // Prepopulate the map with module names.
627 for (JSModule m : modules) {
628 wrappers.put(m.getName(), "");
629 }
630
631 for (String spec : specs) {
632
633 // Format is "<name>:<wrapper>".
634 int pos = spec.indexOf(':');
635 if (pos == -1) {
636 throw new FlagUsageException("Expected module wrapper to have "
637 + "<name>:<wrapper> format: " + spec);
638 }
639
640 // Parse module name.
641 String name = spec.substring(0, pos);
642 if (!wrappers.containsKey(name)) {
643 throw new FlagUsageException("Unknown module: '" + name + "'");
644 }
645 String wrapper = spec.substring(pos + 1);
646 if (!wrapper.contains("%s")) {
647 throw new FlagUsageException("No %s placeholder in module wrapper: '"
648 + wrapper + "'");
649 }
650 wrappers.put(name, wrapper);
651 }
652 return wrappers;
653 }
654
655 private String getModuleOutputFileName(JSModule m) {
656 return config.moduleOutputPathPrefix + m.getName() + ".js";
657 }
658
659 @VisibleForTesting
660 void writeModuleOutput(Appendable out, JSModule m)
661 throws FlagUsageException, IOException {
662 if (parsedModuleWrappers == null) {
663 parsedModuleWrappers = parseModuleWrappers(
664 config.moduleWrapper,
665 Lists.newArrayList(
666 compiler.getDegenerateModuleGraph().getAllModules()));
667 }
668
669 String fileName = getModuleOutputFileName(m);
670 String baseName = new File(fileName).getName();
671 writeOutput(out, compiler, compiler.toSource(m),
672 parsedModuleWrappers.get(m.getName()).replace("%basename%", baseName),
673 "%s", null);
674 }
675
676 /**
677 * Writes code to an output stream, optionally wrapping it in an arbitrary
678 * wrapper that contains a placeholder where the code should be inserted.
679 */
680 static void writeOutput(Appendable out, Compiler compiler, String code,
681 String wrapper, String codePlaceholder,
682 @Nullable Function<String, String> escaper)
683 throws IOException {
684 int pos = wrapper.indexOf(codePlaceholder);
685 if (pos != -1) {
686 String prefix = "";
687
688 if (pos > 0) {
689 prefix = wrapper.substring(0, pos);
690 out.append(prefix);
691 }
692
693 out.append(escaper == null ? code : escaper.apply(code));
694
695 int suffixStart = pos + codePlaceholder.length();
696 if (suffixStart != wrapper.length()) {
697 // Something after placeholder?
698 out.append(wrapper.substring(suffixStart));
699 }
700 // Make sure we always end output with a line feed.
701 out.append('\n');
702
703 // If we have a source map, adjust its offsets to match
704 // the code WITHIN the wrapper.
705 if (compiler != null && compiler.getSourceMap() != null) {
706 compiler.getSourceMap().setWrapperPrefix(prefix);
707 }
708
709 } else {
710 out.append(code);
711 out.append('\n');
712 }
713 }
714
715 /**
716 * Creates any directories necessary to write a file that will have a given
717 * path prefix.
718 */
719 private static void maybeCreateDirsForPath(String pathPrefix) {
720 if (pathPrefix.length() > 0) {
721 String dirName =
722 pathPrefix.charAt(pathPrefix.length() - 1) == File.separatorChar
723 ? pathPrefix.substring(0, pathPrefix.length() - 1) : new File(
724 pathPrefix).getParent();
725 if (dirName != null) {
726 new File(dirName).mkdirs();
727 }
728 }
729 }
730
731 /**
732 * Parses command-line arguments and runs the compiler.
733 *
734 * @return system exit status
735 */
736 protected int doRun() throws FlagUsageException, IOException {
737 Compiler.setLoggingLevel(Level.parse(config.loggingLevel));
738
739 List<SourceFile> externs = createExterns();
740
741 compiler = createCompiler();
742 B options = createOptions();
743
744 List<JSModule> modules = null;
745 Result result = null;
746
747 setRunOptions(options);
748
749 boolean writeOutputToFile = !config.jsOutputFile.isEmpty();
750 List<String> outputFileNames = Lists.newArrayList();
751 if (writeOutputToFile) {
752 outputFileNames.add(config.jsOutputFile);
753 jsOutput = fileNameToLegacyOutputWriter(config.jsOutputFile);
754 } else if (jsOutput instanceof OutputStream) {
755 jsOutput = streamToLegacyOutputWriter((OutputStream) jsOutput);
756 }
757
758 List<String> jsFiles = config.js;
759 List<String> moduleSpecs = config.module;
760
761 boolean createCommonJsModules = false;
762 if (options.processCommonJSModules) {
763 if (moduleSpecs.size() == 1 && "auto".equals(moduleSpecs.get(0))) {
764 createCommonJsModules = true;
765 moduleSpecs.remove(0);
766 }
767 }
768 if (!moduleSpecs.isEmpty()) {
769 modules = createJsModules(moduleSpecs, jsFiles);
770 for (JSModule m : modules) {
771 outputFileNames.add(getModuleOutputFileName(m));
772 }
773
774 if (config.skipNormalOutputs) {
775 compiler.initModules(externs, modules, options);
776 } else {
777 result = compiler.compileModules(externs, modules, options);
778 }
779 } else {
780 List<SourceFile> inputs = createSourceInputs(jsFiles);
781 if (config.skipNormalOutputs) {
782 compiler.init(externs, inputs, options);
783 } else {
784 result = compiler.compile(externs, inputs, options);
785 }
786 }
787 if (createCommonJsModules) {
788 // For CommonJS modules construct modules from actual inputs.
789 modules = Lists.newArrayList(compiler.getDegenerateModuleGraph()
790 .getAllModules());
791 for (JSModule m : modules) {
792 outputFileNames.add(getModuleOutputFileName(m));
793 }
794 }
795
796 for (String outputFileName : outputFileNames) {
797 if (compiler.getSourceFileByName(outputFileName) != null) {
798 compiler.report(
799 JSError.make(OUTPUT_SAME_AS_INPUT_ERROR, outputFileName));
800 return 1;
801 }
802 }
803
804 int errCode = processResults(result, modules, options);
805 // Flush the output if we are writing to a file.
806 // We can't close yet, because we may need to write phase ordering
807 // info to it later.
808 if (jsOutput instanceof Flushable) {
809 ((Flushable) jsOutput).flush();
810 }
811 return errCode;
812 }
813
814 /**
815 * Processes the results of the compile job, and returns an error code.
816 */
817 int processResults(Result result, List<JSModule> modules, B options)
818 throws FlagUsageException, IOException {
819 if (config.computePhaseOrdering) {
820 return 0;
821 }
822
823 if (config.printPassGraph) {
824 if (compiler.getRoot() == null) {
825 return 1;
826 } else {
827 jsOutput.append(
828 DotFormatter.toDot(compiler.getPassConfig().getPassGraph()));
829 jsOutput.append('\n');
830 return 0;
831 }
832 }
833
834 if (config.printAst) {
835 if (compiler.getRoot() == null) {
836 return 1;
837 } else {
838 ControlFlowGraph<Node> cfg = compiler.computeCFG();
839 DotFormatter.appendDot(
840 compiler.getRoot().getLastChild(), cfg, jsOutput);
841 jsOutput.append('\n');
842 return 0;
843 }
844 }
845
846 if (config.printTree) {
847 if (compiler.getRoot() == null) {
848 jsOutput.append("Code contains errors; no tree was generated.\n");
849 return 1;
850 } else {
851 compiler.getRoot().appendStringTree(jsOutput);
852 jsOutput.append("\n");
853 return 0;
854 }
855 }
856
857 rootRelativePathsMap = constructRootRelativePathsMap();
858
859 if (config.skipNormalOutputs) {
860 // Output the manifest and bundle files if requested.
861 outputManifest();
862 outputBundle();
863 outputModuleGraphJson();
864 return 0;
865 } else if (result.success) {
866 outputModuleGraphJson();
867 if (modules == null) {
868 outputSingleBinary();
869
870 // Output the source map if requested.
871 outputSourceMap(options, config.jsOutputFile);
872 } else {
873 outputModuleBinaryAndSourceMaps(modules, options);
874 }
875
876 // Output the externs if required.
877 if (options.externExportsPath != null) {
878 Writer eeOut =
879 openExternExportsStream(options, config.jsOutputFile);
880 eeOut.append(result.externExport);
881 eeOut.close();
882 }
883
884 // Output the variable and property name maps if requested.
885 outputNameMaps();
886
887 // Output the manifest and bundle files if requested.
888 outputManifest();
889 outputBundle();
890 }
891
892 // return 0 if no errors, the error count otherwise
893 return Math.min(result.errors.length, 0x7f);
894 }
895
896 Function<String, String> getJavascriptEscaper() {
897 throw new UnsupportedOperationException(
898 "SourceCodeEscapers is not in the standard release of Guava yet :(");
899 }
900
901 void outputSingleBinary() throws IOException {
902 Function<String, String> escaper = null;
903 String marker = OUTPUT_MARKER;
904 if (config.outputWrapper.contains(OUTPUT_MARKER_JS_STRING)) {
905 marker = OUTPUT_MARKER_JS_STRING;
906 escaper = getJavascriptEscaper();
907 }
908
909 writeOutput(
910 jsOutput, compiler, compiler.toSource(), config.outputWrapper,
911 marker, escaper);
912 }
913
914 private void outputModuleBinaryAndSourceMaps(
915 List<JSModule> modules, B options)
916 throws FlagUsageException, IOException {
917 parsedModuleWrappers = parseModuleWrappers(
918 config.moduleWrapper, modules);
919 maybeCreateDirsForPath(config.moduleOutputPathPrefix);
920
921 // If the source map path is in fact a pattern for each
922 // module, create a stream per-module. Otherwise, create
923 // a single source map.
924 Writer mapOut = null;
925
926 if (!shouldGenerateMapPerModule(options)) {
927 mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, null));
928 }
929
930 for (JSModule m : modules) {
931 if (shouldGenerateMapPerModule(options)) {
932 mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, m));
933 }
934
935 Writer writer =
936 fileNameToLegacyOutputWriter(getModuleOutputFileName(m));
937
938 if (options.sourceMapOutputPath != null) {
939 compiler.getSourceMap().reset();
940 }
941
942 writeModuleOutput(writer, m);
943
944 if (options.sourceMapOutputPath != null) {
945 compiler.getSourceMap().appendTo(mapOut, m.getName());
946 }
947
948 writer.close();
949
950 if (shouldGenerateMapPerModule(options) && mapOut != null) {
951 mapOut.close();
952 mapOut = null;
953 }
954 }
955
956 if (mapOut != null) {
957 mapOut.close();
958 }
959 }
960
961 /**
962 * Query the flag for the input charset, and return a Charset object
963 * representing the selection.
964 *
965 * @return Charset to use when reading inputs
966 * @throws FlagUsageException if flag is not a valid Charset name.
967 */
968 private Charset getInputCharset() throws FlagUsageException {
969 if (!config.charset.isEmpty()) {
970 if (!Charset.isSupported(config.charset)) {
971 throw new FlagUsageException(config.charset +
972 " is not a valid charset name.");
973 }
974 return Charset.forName(config.charset);
975 }
976 return Charsets.UTF_8;
977 }
978
979 /**
980 * Query the flag for the output charset.
981 *
982 * Let the outputCharset be the same as the input charset... except if
983 * we're reading in UTF-8 by default. By tradition, we've always
984 * output ASCII to avoid various hiccups with different browsers,
985 * proxies and firewalls.
986 *
987 * @return Name of the charset to use when writing outputs. Guaranteed to
988 * be a supported charset.
989 * @throws FlagUsageException if flag is not a valid Charset name.
990 */
991 private String getLegacyOutputCharset() throws FlagUsageException {
992 if (!config.charset.isEmpty()) {
993 if (!Charset.isSupported(config.charset)) {
994 throw new FlagUsageException(config.charset +
995 " is not a valid charset name.");
996 }
997 return config.charset;
998 }
999 return "US-ASCII";
1000 }
1001
1002 /**
1003 * Query the flag for the output charset. Defaults to UTF-8.
1004 * @throws FlagUsageException if flag is not a valid Charset name.
1005 */
1006 private Charset getOutputCharset2() throws FlagUsageException {
1007 if (!config.charset.isEmpty()) {
1008 if (!Charset.isSupported(config.charset)) {
1009 throw new FlagUsageException(config.charset +
1010 " is not a valid charset name.");
1011 }
1012 return Charset.forName(config.charset);
1013 }
1014 return Charsets.UTF_8;
1015 }
1016
1017 protected List<SourceFile> createExterns() throws FlagUsageException,
1018 IOException {
1019 return isInTestMode() ? externsSupplierForTesting.get() :
1020 createExternInputs(config.externs);
1021 }
1022
1023 /**
1024 * Returns true if and only if a source map file should be generated for each
1025 * module, as opposed to one unified map. This is specified by having the
1026 * source map pattern include the %outname% variable.
1027 */
1028 private boolean shouldGenerateMapPerModule(B options) {
1029 return options.sourceMapOutputPath != null
1030 && options.sourceMapOutputPath.contains("%outname%");
1031 }
1032
1033 /**
1034 * Returns a stream for outputting the generated externs file.
1035 *
1036 * @param options The options to the Compiler.
1037 * @param path The path of the generated JS source file.
1038 *
1039 * @return The stream or null if no extern-ed exports are being generated.
1040 */
1041 private Writer openExternExportsStream(B options,
1042 String path) throws IOException {
1043 if (options.externExportsPath == null) {
1044 return null;
1045 }
1046
1047 String exPath = options.externExportsPath;
1048
1049 if (!exPath.contains(File.separator)) {
1050 File outputFile = new File(path);
1051 exPath = outputFile.getParent() + File.separatorChar + exPath;
1052 }
1053
1054 return fileNameToOutputWriter2(exPath);
1055 }
1056
1057 /**
1058 * Expand a file path specified on the command-line.
1059 *
1060 * Most file paths on the command-line allow an %outname% placeholder.
1061 * The placeholder will expand to a different value depending on
1062 * the current output mode. There are three scenarios:
1063 *
1064 * 1) Single JS output, single extra output: sub in jsOutputPath.
1065 * 2) Multiple JS output, single extra output: sub in the base module name.
1066 * 3) Multiple JS output, multiple extra output: sub in the module output
1067 * file.
1068 *
1069 * Passing a JSModule to this function automatically triggers case #3.
1070 * Otherwise, we'll use strategy #1 or #2 based on the current output mode.
1071 */
1072 private String expandCommandLinePath(
1073 String path, JSModule forModule) {
1074 String sub;
1075 if (forModule != null) {
1076 sub = config.moduleOutputPathPrefix + forModule.getName() + ".js";
1077 } else if (!config.module.isEmpty()) {
1078 sub = config.moduleOutputPathPrefix;
1079 } else {
1080 sub = config.jsOutputFile;
1081 }
1082 return path.replace("%outname%", sub);
1083 }
1084
1085 /** Expansion function for source map. */
1086 @VisibleForTesting
1087 String expandSourceMapPath(B options, JSModule forModule) {
1088 if (Strings.isNullOrEmpty(options.sourceMapOutputPath)) {
1089 return null;
1090 }
1091 return expandCommandLinePath(options.sourceMapOutputPath, forModule);
1092 }
1093
1094 /**
1095 * Converts a file name into a Writer taking in account the output charset.
1096 * Returns null if the file name is null.
1097 */
1098 private Writer fileNameToLegacyOutputWriter(String fileName)
1099 throws IOException {
1100 if (fileName == null) {
1101 return null;
1102 }
1103 if (testMode) {
1104 return new StringWriter();
1105 }
1106
1107 return streamToLegacyOutputWriter(filenameToOutputStream(fileName));
1108 }
1109
1110 /**
1111 * Converts a file name into a Writer taking in account the output charset.
1112 * Returns null if the file name is null.
1113 */
1114 private Writer fileNameToOutputWriter2(String fileName) throws IOException {
1115 if (fileName == null) {
1116 return null;
1117 }
1118 if (testMode) {
1119 return new StringWriter();
1120 }
1121
1122 return streamToOutputWriter2(filenameToOutputStream(fileName));
1123 }
1124
1125 /**
1126 * Converts a file name into a Outputstream.
1127 * Returns null if the file name is null.
1128 */
1129 protected OutputStream filenameToOutputStream(String fileName)
1130 throws IOException {
1131 if (fileName == null){
1132 return null;
1133 }
1134 return new FileOutputStream(fileName);
1135 }
1136
1137 /**
1138 * Create a writer with the legacy output charset.
1139 */
1140 private Writer streamToLegacyOutputWriter(OutputStream stream)
1141 throws IOException {
1142 if (legacyOutputCharset == null) {
1143 return new BufferedWriter(
1144 new OutputStreamWriter(stream));
1145 } else {
1146 return new BufferedWriter(
1147 new OutputStreamWriter(stream, legacyOutputCharset));
1148 }
1149 }
1150
1151 /**
1152 * Create a writer with the newer output charset.
1153 */
1154 private Writer streamToOutputWriter2(OutputStream stream) {
1155 if (outputCharset2 == null) {
1156 return new BufferedWriter(
1157 new OutputStreamWriter(stream));
1158 } else {
1159 return new BufferedWriter(
1160 new OutputStreamWriter(stream, outputCharset2));
1161 }
1162 }
1163
1164 /**
1165 * Outputs the source map found in the compiler to the proper path if one
1166 * exists.
1167 *
1168 * @param options The options to the Compiler.
1169 */
1170 private void outputSourceMap(B options, String associatedName)
1171 throws IOException {
1172 if (Strings.isNullOrEmpty(options.sourceMapOutputPath)) {
1173 return;
1174 }
1175
1176 String outName = expandSourceMapPath(options, null);
1177 Writer out = fileNameToOutputWriter2(outName);
1178 compiler.getSourceMap().appendTo(out, associatedName);
1179 out.close();
1180 }
1181
1182 /**
1183 * Returns the path at which to output map file(s) based on the path at which
1184 * the JS binary will be placed.
1185 *
1186 * @return The path in which to place the generated map file(s).
1187 */
1188 private String getMapPath(String outputFile) {
1189 String basePath = "";
1190
1191 if (outputFile.equals("")) {
1192 // If we have a js_module_binary rule, output the maps
1193 // at modulename_props_map.out, etc.
1194 if (!config.moduleOutputPathPrefix.equals("")) {
1195 basePath = config.moduleOutputPathPrefix;
1196 } else {
1197 basePath = "jscompiler";
1198 }
1199 } else {
1200 // Get the path of the output file.
1201 File file = new File(outputFile);
1202
1203 String outputFileName = file.getName();
1204
1205 // Strip the .js from the name.
1206 if (outputFileName.endsWith(".js")) {
1207 outputFileName =
1208 outputFileName.substring(0, outputFileName.length() - 3);
1209 }
1210
1211 basePath = file.getParent() + File.separatorChar + outputFileName;
1212 }
1213
1214 return basePath;
1215 }
1216
1217 /**
1218 * Outputs the variable and property name maps for the specified compiler if
1219 * the proper FLAGS are set.
1220 */
1221 private void outputNameMaps() throws FlagUsageException,
1222 IOException {
1223
1224 String propertyMapOutputPath = null;
1225 String variableMapOutputPath = null;
1226 String functionInformationMapOutputPath = null;
1227
1228 // Check the create_name_map_files FLAG.
1229 if (config.createNameMapFiles) {
1230 String basePath = getMapPath(config.jsOutputFile);
1231
1232 propertyMapOutputPath = basePath + "_props_map.out";
1233 variableMapOutputPath = basePath + "_vars_map.out";
1234 functionInformationMapOutputPath = basePath + "_functions_map.out";
1235 }
1236
1237 // Check the individual FLAGS.
1238 if (!config.variableMapOutputFile.equals("")) {
1239 if (variableMapOutputPath != null) {
1240 throw new FlagUsageException("The flags variable_map_output_file and "
1241 + "create_name_map_files cannot both be used simultaniously.");
1242 }
1243
1244 variableMapOutputPath = config.variableMapOutputFile;
1245 }
1246
1247 if (!config.propertyMapOutputFile.equals("")) {
1248 if (propertyMapOutputPath != null) {
1249 throw new FlagUsageException("The flags property_map_output_file and "
1250 + "create_name_map_files cannot both be used simultaniously.");
1251 }
1252
1253 propertyMapOutputPath = config.propertyMapOutputFile;
1254 }
1255
1256 // Output the maps.
1257 if (variableMapOutputPath != null) {
1258 if (compiler.getVariableMap() != null) {
1259 compiler.getVariableMap().save(variableMapOutputPath);
1260 }
1261 }
1262
1263 if (propertyMapOutputPath != null) {
1264 if (compiler.getPropertyMap() != null) {
1265 compiler.getPropertyMap().save(propertyMapOutputPath);
1266 }
1267 }
1268
1269 if (functionInformationMapOutputPath != null) {
1270 if (compiler.getFunctionalInformationMap() != null) {
1271 OutputStream file =
1272 filenameToOutputStream(functionInformationMapOutputPath);
1273 CodedOutputStream outputStream = CodedOutputStream.newInstance(file);
1274 compiler.getFunctionalInformationMap().writeTo(outputStream);
1275 outputStream.flush();
1276 file.flush();
1277 file.close();
1278 }
1279 }
1280 }
1281
1282 /**
1283 * Create a map of constant names to constant values from a textual
1284 * description of the map.
1285 *
1286 * @param definitions A list of overriding definitions for defines in
1287 * the form <name>[=<val>], where <val> is a number, boolean, or
1288 * single-quoted string without single quotes.
1289 */
1290 @VisibleForTesting
1291 static void createDefineOrTweakReplacements(List<String> definitions,
1292 CompilerOptions options, boolean tweaks) {
1293 // Parse the definitions
1294 for (String override : definitions) {
1295 String[] assignment = override.split("=", 2);
1296 String defName = assignment[0];
1297
1298 if (defName.length() > 0) {
1299 String defValue = assignment.length == 1 ? "true" : assignment[1];
1300
1301 boolean isTrue = defValue.equals("true");
1302 boolean isFalse = defValue.equals("false");
1303 if (isTrue || isFalse) {
1304 if (tweaks) {
1305 options.setTweakToBooleanLiteral(defName, isTrue);
1306 } else {
1307 options.setDefineToBooleanLiteral(defName, isTrue);
1308 }
1309 continue;
1310 } else if (defValue.length() > 1
1311 && ((defValue.charAt(0) == '\'' &&
1312 defValue.charAt(defValue.length() - 1) == '\'')
1313 || (defValue.charAt(0) == '\"' &&
1314 defValue.charAt(defValue.length() - 1) == '\"'))) {
1315 // If the value starts and ends with a single quote,
1316 // we assume that it's a string.
1317 String maybeStringVal =
1318 defValue.substring(1, defValue.length() - 1);
1319 if (maybeStringVal.indexOf(defValue.charAt(0)) == -1) {
1320 if (tweaks) {
1321 options.setTweakToStringLiteral(defName, maybeStringVal);
1322 } else {
1323 options.setDefineToStringLiteral(defName, maybeStringVal);
1324 }
1325 continue;
1326 }
1327 } else {
1328 try {
1329 double value = Double.parseDouble(defValue);
1330 if (tweaks) {
1331 options.setTweakToDoubleLiteral(defName, value);
1332 } else {
1333 options.setDefineToDoubleLiteral(defName, value);
1334 }
1335 continue;
1336 } catch (NumberFormatException e) {
1337 // do nothing, it will be caught at the end
1338 }
1339 }
1340 }
1341
1342 if (tweaks) {
1343 throw new RuntimeException(
1344 "--tweak flag syntax invalid: " + override);
1345 }
1346 throw new RuntimeException(
1347 "--define flag syntax invalid: " + override);
1348 }
1349 }
1350
1351 /**
1352 * Returns true if and only if a manifest or bundle should be generated
1353 * for each module, as opposed to one unified manifest.
1354 */
1355 private boolean shouldGenerateOutputPerModule(String output) {
1356 return !config.module.isEmpty()
1357 && output != null && output.contains("%outname%");
1358 }
1359
1360 private void outputManifest() throws IOException {
1361 outputManifestOrBundle(config.outputManifests, true);
1362 }
1363
1364 private void outputBundle() throws IOException {
1365 outputManifestOrBundle(config.outputBundles, false);
1366 }
1367
1368 /**
1369 * Writes the manifest or bundle of all compiler input files that survived
1370 * manage_closure_dependencies, if requested.
1371 */
1372 private void outputManifestOrBundle(List<String> outputFiles,
1373 boolean isManifest) throws IOException {
1374 if (outputFiles.isEmpty()) {
1375 return;
1376 }
1377
1378 for (String output : outputFiles) {
1379 if (output.isEmpty()) {
1380 continue;
1381 }
1382
1383 if (shouldGenerateOutputPerModule(output)) {
1384 // Generate per-module manifests or bundles
1385 JSModuleGraph graph = compiler.getDegenerateModuleGraph();
1386 Iterable<JSModule> modules = graph.getAllModules();
1387 for (JSModule module : modules) {
1388 Writer out = fileNameToOutputWriter2(
1389 expandCommandLinePath(output, module));
1390 if (isManifest) {
1391 printManifestTo(module.getInputs(), out);
1392 } else {
1393 printBundleTo(module.getInputs(), out);
1394 }
1395 out.close();
1396 }
1397 } else {
1398 // Generate a single file manifest or bundle.
1399 Writer out = fileNameToOutputWriter2(
1400 expandCommandLinePath(output, null));
1401 if (config.module.isEmpty()) {
1402 if (isManifest) {
1403 printManifestTo(compiler.getInputsInOrder(), out);
1404 } else {
1405 printBundleTo(compiler.getInputsInOrder(), out);
1406 }
1407 } else {
1408 printModuleGraphManifestOrBundleTo(
1409 compiler.getDegenerateModuleGraph(), out, isManifest);
1410 }
1411 out.close();
1412 }
1413 }
1414 }
1415
1416 /**
1417 * Creates a file containing the current module graph in JSON serialization.
1418 */
1419 private void outputModuleGraphJson() throws IOException {
1420 if (config.outputModuleDependencies != null &&
1421 config.outputModuleDependencies != "") {
1422 Writer out = fileNameToOutputWriter2(config.outputModuleDependencies);
1423 printModuleGraphJsonTo(out);
1424 out.close();
1425 }
1426 }
1427
1428 /**
1429 * Prints the current module graph as JSON.
1430 */
1431 @VisibleForTesting
1432 void printModuleGraphJsonTo(Appendable out) throws IOException {
1433 out.append(compiler.getDegenerateModuleGraph().toJson().toString());
1434 }
1435
1436 /**
1437 * Prints a set of modules to the manifest or bundle file.
1438 */
1439 @VisibleForTesting
1440 void printModuleGraphManifestOrBundleTo(JSModuleGraph graph,
1441 Appendable out, boolean isManifest) throws IOException {
1442 Joiner commas = Joiner.on(",");
1443 boolean requiresNewline = false;
1444 for (JSModule module : graph.getAllModules()) {
1445 if (requiresNewline) {
1446 out.append("\n");
1447 }
1448
1449 if (isManifest) {
1450 // See CommandLineRunnerTest to see what the format of this
1451 // manifest looks like.
1452 String dependencies = commas.join(module.getSortedDependencyNames());
1453 out.append(
1454 String.format("{%s%s}\n",
1455 module.getName(),
1456 dependencies.isEmpty() ? "" : ":" + dependencies));
1457 printManifestTo(module.getInputs(), out);
1458 } else {
1459 printBundleTo(module.getInputs(), out);
1460 }
1461 requiresNewline = true;
1462 }
1463 }
1464
1465 /**
1466 * Prints a list of input names (using root-relative paths), delimited by
1467 * newlines, to the manifest file.
1468 */
1469 private void printManifestTo(Iterable<CompilerInput> inputs, Appendable out)
1470 throws IOException {
1471 for (CompilerInput input : inputs) {
1472 String rootRelativePath = rootRelativePathsMap.get(input.getName());
1473 String displayName = rootRelativePath != null
1474 ? rootRelativePath
1475 : input.getName();
1476 out.append(displayName);
1477 out.append("\n");
1478 }
1479 }
1480
1481 /**
1482 * Prints all the input contents, starting with a comment that specifies
1483 * the input file name (using root-relative paths) before each file.
1484 */
1485 private void printBundleTo(Iterable<CompilerInput> inputs, Appendable out)
1486 throws IOException {
1487 for (CompilerInput input : inputs) {
1488 // Every module has an empty file in it. This makes it easier to implement
1489 // cross-module code motion.
1490 //
1491 // But it also leads to a weird edge case because
1492 // a) If we don't have a module spec, we create a singleton module, and
1493 // b) If we print a bundle file, we copy the original input files.
1494 //
1495 // This means that in the (rare) case where we have no inputs, and no
1496 // module spec, and we're printing a bundle file, we'll have a fake
1497 // input file that shouldn't be copied. So we special-case this, to
1498 // make all the other cases simpler.
1499 if (input.getName().equals(
1500 Compiler.createFillFileName(Compiler.SINGLETON_MODULE_NAME))) {
1501 Preconditions.checkState(1 == Iterables.size(inputs));
1502 return;
1503 }
1504
1505 String rootRelativePath = rootRelativePathsMap.get(input.getName());
1506 String displayName = rootRelativePath != null
1507 ? rootRelativePath
1508 : input.getName();
1509 File file = new File(input.getName());
1510 out.append("//");
1511 out.append(displayName);
1512 out.append("\n");
1513 Files.copy(file, inputCharset, out);
1514 out.append("\n");
1515 }
1516 }
1517
1518 /**
1519 * Construct and return the input root path map. The key is the exec path of
1520 * each input file, and the value is the corresponding root relative path.
1521 */
1522 private Map<String, String> constructRootRelativePathsMap() {
1523 Map<String, String> rootRelativePathsMap = Maps.newLinkedHashMap();
1524 for (String mapString : config.manifestMaps) {
1525 int colonIndex = mapString.indexOf(':');
1526 Preconditions.checkState(colonIndex > 0);
1527 String execPath = mapString.substring(0, colonIndex);
1528 String rootRelativePath = mapString.substring(colonIndex + 1);
1529 Preconditions.checkState(rootRelativePath.indexOf(':') == -1);
1530 rootRelativePathsMap.put(execPath, rootRelativePath);
1531 }
1532 return rootRelativePathsMap;
1533 }
1534
1535 private class RunTimeStats {
1536 private long bestRunTime = Long.MAX_VALUE;
1537 private long worstRunTime = Long.MIN_VALUE;
1538 private long lastStartTime = 0;
1539 private List<List<String>> loopedPassesInBestRun = null;
1540
1541 /**
1542 * Record the start of a run.
1543 */
1544 private void recordStartRun() {
1545 lastStartTime = System.currentTimeMillis();
1546 PhaseOptimizer.clearLoopsRun();
1547 }
1548
1549 /**
1550 * Record the end of a run.
1551 */
1552 private void recordEndRun() {
1553 long endTime = System.currentTimeMillis();
1554 long length = endTime - lastStartTime;
1555 worstRunTime = Math.max(length, worstRunTime);
1556 if (length < bestRunTime) {
1557 loopedPassesInBestRun = PhaseOptimizer.getLoopsRun();
1558 bestRunTime = length;
1559 }
1560 }
1561
1562 /**
1563 * Print the best phase loop to stderr.
1564 */
1565 private void outputBestPhaseOrdering() {
1566 try {
1567 jsOutput.append("Best time: " + bestRunTime + "\n");
1568 jsOutput.append("Worst time: " + worstRunTime + "\n");
1569
1570 int i = 1;
1571 for (List<String> loop : loopedPassesInBestRun) {
1572 jsOutput.append(
1573 "\nLoop " + i + ":\n" + Joiner.on("\n").join(loop)+ "\n");
1574 i++;
1575 }
1576 } catch (IOException e) {
1577 throw new RuntimeException("unexpected exception", e);
1578 }
1579 }
1580 }
1581
1582 /**
1583 * Configurations for the command line configs. Designed for easy
1584 * building, so that we can decouple the flags-parsing library from
1585 * the actual configuration options.
1586 *
1587 * By design, these configurations must match one-to-one with
1588 * command-line flags.
1589 */
1590 static class CommandLineConfig {
1591 private boolean printTree = false;
1592
1593 /** Prints out the parse tree and exits */
1594 CommandLineConfig setPrintTree(boolean printTree) {
1595 this.printTree = printTree;
1596 return this;
1597 }
1598
1599 private boolean computePhaseOrdering = false;
1600
1601 /**
1602 * Runs the compile job many times, then prints out the best phase
1603 * ordering from this run
1604 */
1605 CommandLineConfig setComputePhaseOrdering(boolean computePhaseOrdering) {
1606 this.computePhaseOrdering = computePhaseOrdering;
1607 return this;
1608 }
1609
1610 private boolean printAst = false;
1611
1612 /**
1613 * Prints a dot file describing the internal abstract syntax tree
1614 * and exits
1615 */
1616 CommandLineConfig setPrintAst(boolean printAst) {
1617 this.printAst = printAst;
1618 return this;
1619 }
1620
1621 private boolean printPassGraph = false;
1622
1623 /** Prints a dot file describing the passes that will get run and exits */
1624 CommandLineConfig setPrintPassGraph(boolean printPassGraph) {
1625 this.printPassGraph = printPassGraph;
1626 return this;
1627 }
1628
1629 private CompilerOptions.DevMode jscompDevMode = CompilerOptions.DevMode.OFF;
1630
1631 /** Turns on extra sanity checks */
1632 CommandLineConfig setJscompDevMode(CompilerOptions.DevMode jscompDevMode) {
1633 this.jscompDevMode = jscompDevMode;
1634 return this;
1635 }
1636
1637 private String loggingLevel = Level.WARNING.getName();
1638
1639 /**
1640 * The logging level (standard java.util.logging.Level
1641 * values) for Compiler progress. Does not control errors or
1642 * warnings for the JavaScript code under compilation
1643 */
1644 CommandLineConfig setLoggingLevel(String loggingLevel) {
1645 this.loggingLevel = loggingLevel;
1646 return this;
1647 }
1648
1649 private final List<String> externs = Lists.newArrayList();
1650
1651 /**
1652 * The file containing JavaScript externs. You may specify multiple.
1653 */
1654 CommandLineConfig setExterns(List<String> externs) {
1655 this.externs.clear();
1656 this.externs.addAll(externs);
1657 return this;
1658 }
1659
1660 private final List<String> js = Lists.newArrayList();
1661
1662 /**
1663 * The JavaScript filename. You may specify multiple.
1664 */
1665 CommandLineConfig setJs(List<String> js) {
1666 this.js.clear();
1667 this.js.addAll(js);
1668 return this;
1669 }
1670
1671 private String jsOutputFile = "";
1672
1673 /**
1674 * Primary output filename. If not specified, output is written to stdout
1675 */
1676 CommandLineConfig setJsOutputFile(String jsOutputFile) {
1677 this.jsOutputFile = jsOutputFile;
1678 return this;
1679 }
1680
1681 private final List<String> module = Lists.newArrayList();
1682
1683 /**
1684 * A JavaScript module specification. The format is
1685 * <name>:<num-js-files>[:[<dep>,...][:]]]. Module names must be
1686 * unique. Each dep is the name of a module that this module
1687 * depends on. Modules must be listed in dependency order, and JS
1688 * source files must be listed in the corresponding order. Where
1689 * --module flags occur in relation to --js flags is unimportant
1690 */
1691 CommandLineConfig setModule(List<String> module) {
1692 this.module.clear();
1693 this.module.addAll(module);
1694 return this;
1695 }
1696
1697 private String variableMapInputFile = "";
1698
1699 /**
1700 * File containing the serialized version of the variable renaming
1701 * map produced by a previous compilation
1702 */
1703 CommandLineConfig setVariableMapInputFile(String variableMapInputFile) {
1704 this.variableMapInputFile = variableMapInputFile;
1705 return this;
1706 }
1707
1708 private String propertyMapInputFile = "";
1709
1710 /**
1711 * File containing the serialized version of the property renaming
1712 * map produced by a previous compilation
1713 */
1714 CommandLineConfig setPropertyMapInputFile(String propertyMapInputFile) {
1715 this.propertyMapInputFile = propertyMapInputFile;
1716 return this;
1717 }
1718
1719 private String variableMapOutputFile = "";
1720
1721 /**
1722 * File where the serialized version of the variable renaming map
1723 * produced should be saved
1724 */
1725 CommandLineConfig setVariableMapOutputFile(String variableMapOutputFile) {
1726 this.variableMapOutputFile = variableMapOutputFile;
1727 return this;
1728 }
1729
1730 private boolean createNameMapFiles = false;
1731
1732 /**
1733 * If true, variable renaming and property renaming map
1734 * files will be produced as {binary name}_vars_map.out and
1735 * {binary name}_props_map.out. Note that this flag cannot be used
1736 * in conjunction with either variable_map_output_file or
1737 * property_map_output_file
1738 */
1739 CommandLineConfig setCreateNameMapFiles(boolean createNameMapFiles) {
1740 this.createNameMapFiles = createNameMapFiles;
1741 return this;
1742 }
1743
1744 private String propertyMapOutputFile = "";
1745
1746 /**
1747 * File where the serialized version of the property renaming map
1748 * produced should be saved
1749 */
1750 CommandLineConfig setPropertyMapOutputFile(String propertyMapOutputFile) {
1751 this.propertyMapOutputFile = propertyMapOutputFile;
1752 return this;
1753 }
1754
1755 private CodingConvention codingConvention = CodingConventions.getDefault();
1756
1757 /**
1758 * Sets rules and conventions to enforce.
1759 */
1760 CommandLineConfig setCodingConvention(CodingConvention codingConvention) {
1761 this.codingConvention = codingConvention;
1762 return this;
1763 }
1764
1765 private int summaryDetailLevel = 1;
1766
1767 /**
1768 * Controls how detailed the compilation summary is. Values:
1769 * 0 (never print summary), 1 (print summary only if there are
1770 * errors or warnings), 2 (print summary if type checking is on,
1771 * see --check_types), 3 (always print summary). The default level
1772 * is 1
1773 */
1774 CommandLineConfig setSummaryDetailLevel(int summaryDetailLevel) {
1775 this.summaryDetailLevel = summaryDetailLevel;
1776 return this;
1777 }
1778
1779 private String outputWrapper = "";
1780
1781 /**
1782 * Interpolate output into this string at the place denoted
1783 * by the marker token %output%, or %output|jsstring%
1784 */
1785 CommandLineConfig setOutputWrapper(String outputWrapper) {
1786 this.outputWrapper = outputWrapper;
1787 return this;
1788 }
1789
1790 private final List<String> moduleWrapper = Lists.newArrayList();
1791
1792 /**
1793 * An output wrapper for a JavaScript module (optional). See the flag
1794 * description for formatting requirements.
1795 */
1796 CommandLineConfig setModuleWrapper(List<String> moduleWrapper) {
1797 this.moduleWrapper.clear();
1798 this.moduleWrapper.addAll(moduleWrapper);
1799 return this;
1800 }
1801
1802 private String moduleOutputPathPrefix = "";
1803
1804 /**
1805 * Prefix for filenames of compiled JS modules.
1806 * <module-name>.js will be appended to this prefix. Directories
1807 * will be created as needed. Use with --module
1808 */
1809 CommandLineConfig setModuleOutputPathPrefix(String moduleOutputPathPrefix) {
1810 this.moduleOutputPathPrefix = moduleOutputPathPrefix;
1811 return this;
1812 }
1813
1814 private String createSourceMap = "";
1815
1816 /**
1817 * If specified, a source map file mapping the generated
1818 * source files back to the original source file will be
1819 * output to the specified path. The %outname% placeholder will
1820 * expand to the name of the output file that the source map
1821 * corresponds to.
1822 */
1823 CommandLineConfig setCreateSourceMap(String createSourceMap) {
1824 this.createSourceMap = createSourceMap;
1825 return this;
1826 }
1827
1828 private SourceMap.DetailLevel sourceMapDetailLevel =
1829 SourceMap.DetailLevel.ALL;
1830
1831 /**
1832 * The detail supplied in the source map file, if generated.
1833 */
1834 CommandLineConfig setSourceMapDetailLevel(SourceMap.DetailLevel level) {
1835 this.sourceMapDetailLevel = level;
1836 return this;
1837 }
1838
1839 private SourceMap.Format sourceMapFormat =
1840 SourceMap.Format.DEFAULT;
1841
1842 /**
1843 * The detail supplied in the source map file, if generated.
1844 */
1845 CommandLineConfig setSourceMapFormat(SourceMap.Format format) {
1846 this.sourceMapFormat = format;
1847 return this;
1848 }
1849
1850 private WarningGuardSpec warningGuards = null;
1851
1852 /**
1853 * Add warning guards.
1854 */
1855 CommandLineConfig setWarningGuardSpec(WarningGuardSpec spec) {
1856 this.warningGuards = spec;
1857 return this;
1858 }
1859
1860 private final List<String> define = Lists.newArrayList();
1861
1862 /**
1863 * Override the value of a variable annotated @define.
1864 * The format is <name>[=<val>], where <name> is the name of a @define
1865 * variable and <val> is a boolean, number, or a single-quoted string
1866 * that contains no single quotes. If [=<val>] is omitted,
1867 * the variable is marked true
1868 */
1869 CommandLineConfig setDefine(List<String> define) {
1870 this.define.clear();
1871 this.define.addAll(define);
1872 return this;
1873 }
1874
1875 private final List<String> tweak = Lists.newArrayList();
1876
1877 /**
1878 * Override the default value of a registered tweak. The format is
1879 * <name>[=<val>], where <name> is the ID of a tweak and <val> is a boolean,
1880 * number, or a single-quoted string that contains no single quotes. If
1881 * [=<val>] is omitted, then true is assumed.
1882 */
1883 CommandLineConfig setTweak(List<String> tweak) {
1884 this.tweak.clear();
1885 this.tweak.addAll(tweak);
1886 return this;
1887 }
1888
1889 private TweakProcessing tweakProcessing = TweakProcessing.OFF;
1890
1891 /**
1892 * Sets the kind of processing to do for goog.tweak functions.
1893 */
1894 CommandLineConfig setTweakProcessing(TweakProcessing tweakProcessing) {
1895 this.tweakProcessing = tweakProcessing;
1896 return this;
1897 }
1898
1899 private String charset = "";
1900
1901 /**
1902 * Input charset for all files.
1903 */
1904 CommandLineConfig setCharset(String charset) {
1905 this.charset = charset;
1906 return this;
1907 }
1908
1909 private boolean manageClosureDependencies = false;
1910
1911 /**
1912 * Sets whether to sort files by their goog.provide/require deps,
1913 * and prune inputs that are not required.
1914 */
1915 CommandLineConfig setManageClosureDependencies(boolean newVal) {
1916 this.manageClosureDependencies = newVal;
1917 return this;
1918 }
1919
1920 private boolean onlyClosureDependencies = false;
1921
1922 /**
1923 * Sets whether to sort files by their goog.provide/require deps,
1924 * and prune inputs that are not required, and drop all non-closure
1925 * files.
1926 */
1927 CommandLineConfig setOnlyClosureDependencies(boolean newVal) {
1928 this.onlyClosureDependencies = newVal;
1929 return this;
1930 }
1931
1932 private List<String> closureEntryPoints = ImmutableList.of();
1933
1934 /**
1935 * Set closure entry points, which makes the compiler only include
1936 * those files and sort them in dependency order.
1937 */
1938 CommandLineConfig setClosureEntryPoints(List<String> entryPoints) {
1939 Preconditions.checkNotNull(entryPoints);
1940 this.closureEntryPoints = entryPoints;
1941 return this;
1942 }
1943
1944 private List<String> outputManifests = ImmutableList.of();
1945
1946 /**
1947 * Sets whether to print output manifest files.
1948 * Filter out empty file names.
1949 */
1950 CommandLineConfig setOutputManifest(List<String> outputManifests) {
1951 this.outputManifests = Lists.newArrayList();
1952 for (String manifestName : outputManifests) {
1953 if (!manifestName.isEmpty()) {
1954 this.outputManifests.add(manifestName);
1955 }
1956 }
1957 this.outputManifests = ImmutableList.copyOf(this.outputManifests);
1958 return this;
1959 }
1960
1961 private String outputModuleDependencies = null;
1962
1963 /**
1964 * Sets whether a JSON file representing the dependencies between modules
1965 * should be created.
1966 */
1967 CommandLineConfig setOutputModuleDependencies(String
1968 outputModuleDependencies) {
1969 this.outputModuleDependencies = outputModuleDependencies;
1970 return this;
1971 }
1972
1973 private List<String> outputBundles = ImmutableList.of();
1974
1975 /**
1976 * Sets whether to print output bundle files.
1977 */
1978 CommandLineConfig setOutputBundle(List<String> outputBundles) {
1979 this.outputBundles = outputBundles;
1980 return this;
1981 }
1982
1983 private boolean acceptConstKeyword = false;
1984
1985 /**
1986 * Sets whether to accept usage of 'const' keyword.
1987 */
1988 CommandLineConfig setAcceptConstKeyword(boolean acceptConstKeyword) {
1989 this.acceptConstKeyword = acceptConstKeyword;
1990 return this;
1991 }
1992
1993 private String languageIn = "";
1994
1995 /**
1996 * Sets whether to accept input files as ECMAScript5 compliant.
1997 * Otherwise, input files are treated as ECMAScript3 compliant.
1998 */
1999 CommandLineConfig setLanguageIn(String languageIn) {
2000 this.languageIn = languageIn;
2001 return this;
2002 }
2003
2004 private boolean skipNormalOutputs = false;
2005
2006 /**
2007 * Sets whether the normal outputs of compilation should be skipped.
2008 */
2009 CommandLineConfig setSkipNormalOutputs(boolean skipNormalOutputs) {
2010 this.skipNormalOutputs = skipNormalOutputs;
2011 return this;
2012 }
2013
2014 private List<String> manifestMaps = ImmutableList.of();
2015
2016 /**
2017 * Sets the execPath:rootRelativePath mappings
2018 */
2019 CommandLineConfig setManifestMaps(List<String> manifestMaps) {
2020 this.manifestMaps = manifestMaps;
2021 return this;
2022 }
2023
2024
2025 private boolean transformAMDToCJSModules = false;
2026
2027 /**
2028 * Set whether to transform AMD to CommonJS modules.
2029 */
2030 CommandLineConfig setTransformAMDToCJSModules(
2031 boolean transformAMDToCJSModules) {
2032 this.transformAMDToCJSModules = transformAMDToCJSModules;
2033 return this;
2034 }
2035
2036 private boolean processCommonJSModules = false;
2037
2038 /**
2039 * Sets whether to process CommonJS modules.
2040 */
2041 CommandLineConfig setProcessCommonJSModules(
2042 boolean processCommonJSModules) {
2043 this.processCommonJSModules = processCommonJSModules;
2044 return this;
2045 }
2046
2047
2048 private String commonJSModulePathPrefix =
2049 ProcessCommonJSModules.DEFAULT_FILENAME_PREFIX;
2050
2051 /**
2052 * Sets the CommonJS module path prefix.
2053 */
2054 CommandLineConfig setCommonJSModulePathPrefix(
2055 String commonJSModulePathPrefix) {
2056 this.commonJSModulePathPrefix = commonJSModulePathPrefix;
2057 return this;
2058 }
2059
2060 private String warningsWhitelistFile = "";
2061
2062 /**
2063 * Sets a whitelist file that suppresses warnings.
2064 */
2065 CommandLineConfig setWarningsWhitelistFile(String fileName) {
2066 this.warningsWhitelistFile = fileName;
2067 return this;
2068 }
2069
2070 private boolean angularPass = false;
2071
2072 /**
2073 * Sets whether to process AngularJS-specific annotations.
2074 */
2075 CommandLineConfig setAngularPass(boolean angularPass) {
2076 this.angularPass = angularPass;
2077 return this;
2078 }
2079 }
2080
2081 /**
2082 * A little helper class to make it easier to collect warning types
2083 * from --jscomp_error, --jscomp_warning, and --jscomp_off.
2084 */
2085 protected static class WarningGuardSpec {
2086 private static class Entry {
2087 private final CheckLevel level;
2088 private final String groupName;
2089
2090 private Entry(CheckLevel level, String groupName) {
2091 this.level = level;
2092 this.groupName = groupName;
2093 }
2094 }
2095
2096 // The entries, in the order that they were added.
2097 private final List<Entry> entries = Lists.newArrayList();
2098
2099 protected void add(CheckLevel level, String groupName) {
2100 entries.add(new Entry(level, groupName));
2101 }
2102
2103 protected void clear() {
2104 entries.clear();
2105 }
2106 }
2107 }