Debian Codegraph @

src/com/google/javascript/jscomp/CompilerOptions.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.base.Preconditions;
20 import com.google.common.collect.ImmutableSet;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Multimap;
24 import com.google.common.collect.Sets;
25 import com.google.javascript.rhino.IR;
26 import com.google.javascript.rhino.Node;
27 import com.google.javascript.rhino.SourcePosition;
28
29 import java.io.Serializable;
30 import java.nio.charset.Charset;
31 import java.text.ParseException;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36
37 /**
38 * Compiler options
39 * @author [email protected] (Nick Santos)
40 */
41 public class CompilerOptions implements Serializable, Cloneable {
42
43 // Unused. For people using reflection to circumvent access control.
44 @SuppressWarnings("unused")
45 private boolean manageClosureDependencies = false;
46
47 // A common enum for compiler passes that can run either globally or locally.
48 public enum Reach {
49 ALL,
50 LOCAL_ONLY,
51 NONE
52 }
53
54 // TODO(nicksantos): All public properties of this class should be made
55 // package-private, and have a public setter.
56
57 private static final long serialVersionUID = 7L;
58
59 /**
60 * The JavaScript language version accepted.
61 */
62 private LanguageMode languageIn;
63
64 /**
65 * The JavaScript language version that should be produced.
66 * Currently, this is always the same as {@link #languageIn}.
67 */
68 private LanguageMode languageOut;
69
70 /**
71 * Whether the compiler accepts the `const' keyword.
72 */
73 boolean acceptConstKeyword;
74
75 /**
76 * Whether the compiler should assume that a function's "this" value
77 * never needs coercion (for example in non-strict "null" or "undefined" will
78 * be coerced to the global "this" and primitives to objects).
79 */
80 private boolean assumeStrictThis;
81
82 /**
83 * Configures the compiler for use as an IDE backend. In this mode:
84 * <ul>
85 * <li>No optimization passes will run.</li>
86 * <li>The last time custom passes are invoked is
87 * {@link CustomPassExecutionTime#BEFORE_OPTIMIZATIONS}</li>
88 * <li>The compiler will always try to process all inputs fully, even
89 * if it encounters errors.</li>
90 * <li>The compiler may record more information than is strictly
91 * needed for codegen.</li>
92 * </ul>
93 */
94 public boolean ideMode;
95
96 boolean saveDataStructures = false;
97
98 /**
99 * Even if checkTypes is disabled, clients might want to still infer types.
100 * This is mostly used when ideMode is enabled.
101 */
102 boolean inferTypes;
103
104 /**
105 * Configures the compiler to skip as many passes as possible.
106 */
107 boolean skipAllPasses;
108
109 /**
110 * If true, name anonymous functions only. All others passes will be skipped.
111 */
112 boolean nameAnonymousFunctionsOnly;
113
114 /**
115 * Configures the compiler to run expensive sanity checks after
116 * every pass. Only intended for internal development.
117 */
118 DevMode devMode;
119
120 /**
121 * Configures the compiler to log a hash code of the AST after
122 * every pass. Only intended for internal development.
123 */
124 private boolean checkDeterminism;
125
126 //--------------------------------
127 // Input Options
128 //--------------------------------
129
130 DependencyOptions dependencyOptions = new DependencyOptions();
131
132 /** Returns localized replacement for MSG_* variables */
133 // Transient so that clients don't have to implement Serializable.
134 public transient MessageBundle messageBundle = null;
135
136 //--------------------------------
137 // Checks
138 //--------------------------------
139
140 /** Checks that all symbols are defined */
141 public boolean checkSymbols;
142
143 public CheckLevel aggressiveVarCheck;
144
145 /** Checks for suspicious variable definitions and undefined variables */
146 public void setAggressiveVarCheck(CheckLevel level) {
147 this.aggressiveVarCheck = level;
148 }
149
150 /** Checks for suspicious statements that have no effect */
151 public boolean checkSuspiciousCode;
152
153 /** Checks for invalid control structures */
154 public boolean checkControlStructures;
155
156 /** Checks types on expressions */
157 public boolean checkTypes;
158
159 boolean tightenTypes;
160
161 /** Tightens types based on a global analysis. Experimental. */
162 public void setTightenTypes(boolean tighten) {
163 tightenTypes = tighten;
164 }
165
166 public CheckLevel reportMissingOverride;
167
168 /**
169 * Flags a warning if a property is missing the @override annotation, but it
170 * overrides a base class property.
171 */
172 public void setReportMissingOverride(CheckLevel level) {
173 reportMissingOverride = level;
174 }
175
176 CheckLevel reportUnknownTypes;
177
178 /** Flags a warning for every node whose type could not be determined. */
179 public void setReportUnknownTypes(CheckLevel level) {
180 reportUnknownTypes = level;
181 }
182
183 /** Checks for missing goog.require() calls **/
184 public CheckLevel checkRequires;
185
186 public void setCheckRequires(CheckLevel level) {
187 checkRequires = level;
188 }
189
190 public CheckLevel checkProvides;
191
192 /** Checks for missing goog.provides() calls **/
193 public void setCheckProvides(CheckLevel level) {
194 checkProvides = level;
195 }
196
197 public CheckLevel checkGlobalNamesLevel;
198
199 /**
200 * Checks the integrity of references to qualified global names.
201 * (e.g. "a.b")
202 */
203 public void setCheckGlobalNamesLevel(CheckLevel level) {
204 checkGlobalNamesLevel = level;
205 }
206
207 public CheckLevel brokenClosureRequiresLevel;
208
209 /** Sets the check level for bad Closure require calls. */
210 public void setBrokenClosureRequiresLevel(CheckLevel level) {
211 brokenClosureRequiresLevel = level;
212 }
213
214 public CheckLevel checkGlobalThisLevel;
215
216 /**
217 * Checks for certain uses of the {@code this} keyword that are considered
218 * unsafe because they are likely to reference the global {@code this}
219 * object unintentionally.
220 *
221 * If this is off, but collapseProperties is on, then the compiler will
222 * usually ignore you and run this check anyways.
223 */
224 public void setCheckGlobalThisLevel(CheckLevel level) {
225 this.checkGlobalThisLevel = level;
226 }
227
228 public CheckLevel checkMissingGetCssNameLevel;
229
230 /**
231 * Checks that certain string literals only appear in strings used as
232 * goog.getCssName arguments.
233 */
234 public void setCheckMissingGetCssNameLevel(CheckLevel level) {
235 this.checkMissingGetCssNameLevel = level;
236 }
237
238 /**
239 * Regex of string literals that may only appear in goog.getCssName arguments.
240 */
241 public String checkMissingGetCssNameBlacklist;
242
243 /** Checks that the syntactic restrictions of Caja are met. */
244 boolean checkCaja;
245
246 public void setCheckCaja(boolean check) {
247 checkCaja = check;
248 }
249
250 /**
251 * A set of extra annotation names which are accepted and silently ignored
252 * when encountered in a source file. Defaults to null which has the same
253 * effect as specifying an empty set.
254 */
255 Set<String> extraAnnotationNames;
256
257 //--------------------------------
258 // Optimizations
259 //--------------------------------
260
261 /** Folds constants (e.g. (2 + 3) to 5) */
262 public boolean foldConstants;
263
264 /** Remove assignments to values that can not be referenced */
265 public boolean deadAssignmentElimination;
266
267 /** Inlines constants (symbols that are all CAPS) */
268 public boolean inlineConstantVars;
269
270 /** Inlines global functions */
271 public boolean inlineFunctions;
272
273 /** Inlines functions defined in local scopes */
274 public boolean inlineLocalFunctions;
275
276 /** More aggressive function inlining */
277 boolean assumeClosuresOnlyCaptureReferences;
278
279 /** Inlines properties */
280 boolean inlineProperties;
281
282 /** Move code to a deeper module */
283 public boolean crossModuleCodeMotion;
284
285 /** Merge two variables together as one. */
286 public boolean coalesceVariableNames;
287
288 /** Move methods to a deeper module */
289 public boolean crossModuleMethodMotion;
290
291 /** Inlines trivial getters */
292 public boolean inlineGetters;
293
294 /** Inlines variables */
295 public boolean inlineVariables;
296
297 /** Inlines variables */
298 boolean inlineLocalVariables;
299
300 // TODO(user): This is temporary. Once flow sensitive inlining is stable
301 // Remove this.
302 public boolean flowSensitiveInlineVariables;
303
304 /** Removes code associated with unused global names */
305 public boolean smartNameRemoval;
306
307 /** Removes code that will never execute */
308 public boolean removeDeadCode;
309
310 public CheckLevel checkUnreachableCode;
311
312 /** Checks for unreachable code */
313 public void setCheckUnreachableCode(CheckLevel level) {
314 this.checkUnreachableCode = level;
315 }
316
317 public CheckLevel checkMissingReturn;
318
319 /** Checks for missing return statements */
320 public void setCheckMissingReturn(CheckLevel level) {
321 this.checkMissingReturn = level;
322 }
323
324 /** Extracts common prototype member declarations */
325 public boolean extractPrototypeMemberDeclarations;
326
327 /** Removes unused member prototypes */
328 public boolean removeUnusedPrototypeProperties;
329
330 /** Tells AnalyzePrototypeProperties it can remove externed props. */
331 public boolean removeUnusedPrototypePropertiesInExterns;
332
333 /** Removes unused member properties */
334 public boolean removeUnusedClassProperties;
335
336 /** Removes unused variables */
337 public boolean removeUnusedVars;
338
339 /** Removes unused variables in local scope. */
340 public boolean removeUnusedLocalVars;
341
342 /** Adds variable aliases for externals to reduce code size */
343 public boolean aliasExternals;
344
345 String aliasableGlobals;
346
347 /**
348 * A comma separated white-list of global names. When {@link #aliasExternals}
349 * is enable, if set to a non-empty string, only externals with these names
350 * will be considered for aliasing.
351 */
352 public void setAliasableGlobals(String names) {
353 aliasableGlobals = names;
354 }
355
356 String unaliasableGlobals;
357
358 /**
359 * A comma separated white-list of global names. When {@link #aliasExternals}
360 * is enable, these global names will not be aliased.
361 */
362 public void setUnaliasableGlobals(String names) {
363 unaliasableGlobals = names;
364 }
365
366 /** Collapses multiple variable declarations into one */
367 public boolean collapseVariableDeclarations;
368
369 /** Group multiple variable declarations into one */
370 boolean groupVariableDeclarations;
371
372 /**
373 * Collapses anonymous function declarations into named function
374 * declarations
375 */
376 public boolean collapseAnonymousFunctions;
377
378 /**
379 * If set to a non-empty set, those strings literals will be aliased to a
380 * single global instance per string, to avoid creating more objects than
381 * necessary.
382 */
383 public Set<String> aliasableStrings;
384
385 /**
386 * A blacklist in the form of a regular expression to block strings that
387 * contains certain words from being aliased.
388 * If the value is the empty string, no words are blacklisted.
389 */
390 public String aliasStringsBlacklist;
391
392 /**
393 * Aliases all string literals to global instances, to avoid creating more
394 * objects than necessary (if true, overrides any set of strings passed in
395 * to aliasableStrings)
396 */
397 public boolean aliasAllStrings;
398
399 /** Print string usage as part of the compilation log. */
400 boolean outputJsStringUsage;
401
402 /** Converts quoted property accesses to dot syntax (a['b'] -> a.b) */
403 public boolean convertToDottedProperties;
404
405 /** Reduces the size of common function expressions. */
406 public boolean rewriteFunctionExpressions;
407
408 /**
409 * Remove unused and constant parameters.
410 */
411 public boolean optimizeParameters;
412
413 /**
414 * Remove unused return values.
415 */
416 public boolean optimizeReturns;
417
418 /**
419 * Remove unused parameters from call sites.
420 */
421 public boolean optimizeCalls;
422
423 /**
424 * Provide formal names for elements of arguments array.
425 */
426 public boolean optimizeArgumentsArray;
427
428 /** Chains calls to functions that return this. */
429 boolean chainCalls;
430
431 //--------------------------------
432 // Renaming
433 //--------------------------------
434
435 /** Controls which variables get renamed. */
436 public VariableRenamingPolicy variableRenaming;
437
438 /** Controls which properties get renamed. */
439 public PropertyRenamingPolicy propertyRenaming;
440
441 /** Should we use affinity information when generating property names. */
442 boolean propertyAffinity;
443
444 /** Controls label renaming. */
445 public boolean labelRenaming;
446
447 /** Reserve property names on the global this object. */
448 public boolean reserveRawExports;
449
450 /** Should shadow variable names in outer scope. */
451 boolean shadowVariables;
452
453 /**
454 * Generate pseudo names for variables and properties for debugging purposes.
455 */
456 public boolean generatePseudoNames;
457
458 /** Specifies a prefix for all globals */
459 public String renamePrefix;
460
461 /**
462 * Specifies the name of an object that will be used to store all non-extern
463 * globals.
464 */
465 public String renamePrefixNamespace;
466
467 /** Aliases true, false, and null to variables with shorter names. */
468 public boolean aliasKeywords;
469
470 /** Flattens multi-level property names (e.g. a$b = x) */
471 public boolean collapseProperties;
472
473 /** Split object literals into individual variables when possible. */
474 boolean collapseObjectLiterals;
475
476 public void setCollapseObjectLiterals(boolean enabled) {
477 collapseObjectLiterals = enabled;
478 }
479
480 /** Flattens multi-level property names on extern types (e.g. String$f = x) */
481 boolean collapsePropertiesOnExternTypes;
482
483 /**
484 * Devirtualize prototype method by rewriting them to be static calls that
485 * take the this pointer as their first argument
486 */
487 public boolean devirtualizePrototypeMethods;
488
489 /**
490 * Use @nosideeffects annotations, function bodies and name graph
491 * to determine if calls have side effects. Requires --check_types.
492 */
493 public boolean computeFunctionSideEffects;
494
495 /**
496 * Where to save debug report for compute function side effects.
497 */
498 String debugFunctionSideEffectsPath;
499
500 /**
501 * Rename properties to disambiguate between unrelated fields based on
502 * type information.
503 */
504 public boolean disambiguateProperties;
505
506 /** Rename unrelated properties to the same name to reduce code size. */
507 public boolean ambiguateProperties;
508
509 /** Give anonymous functions names for easier debugging */
510 public AnonymousFunctionNamingPolicy anonymousFunctionNaming;
511
512 /** Input anonymous function renaming map. */
513 VariableMap inputAnonymousFunctionNamingMap;
514
515 /** Input variable renaming map. */
516 VariableMap inputVariableMap;
517
518 /** Input property renaming map. */
519 VariableMap inputPropertyMap;
520
521 /** Whether to export test functions. */
522 public boolean exportTestFunctions;
523
524 boolean specializeInitialModule;
525
526 /** Specialize the initial module at the cost of later modules */
527 public void setSpecializeInitialModule(boolean enabled) {
528 specializeInitialModule = enabled;
529 }
530
531 //--------------------------------
532 // Special-purpose alterations
533 //--------------------------------
534
535 /**
536 * Replace UI strings with chrome.i18n.getMessage calls.
537 * Used by Chrome extensions/apps.
538 */
539 boolean replaceMessagesWithChromeI18n;
540 String tcProjectId;
541
542 public void setReplaceMessagesWithChromeI18n(
543 boolean replaceMessagesWithChromeI18n,
544 String tcProjectId) {
545 if (replaceMessagesWithChromeI18n &&
546 messageBundle != null &&
547 !(messageBundle instanceof EmptyMessageBundle)) {
548 throw new RuntimeException("When replacing messages with " +
549 "chrome.i18n.getMessage, a message bundle should not be specified.");
550 }
551
552 this.replaceMessagesWithChromeI18n = replaceMessagesWithChromeI18n;
553 this.tcProjectId = tcProjectId;
554 }
555
556 /** Inserts run-time type assertions for debugging. */
557 boolean runtimeTypeCheck;
558
559 /**
560 * A JS function to be used for logging run-time type assertion
561 * failures. It will be passed the warning as a string and the
562 * faulty expression as arguments.
563 */
564 String runtimeTypeCheckLogFunction;
565
566 /** A CodingConvention to use during the compile. */
567 private CodingConvention codingConvention;
568
569 boolean ignoreCajaProperties;
570
571 /** Add code to skip properties that Caja adds to Object.prototype */
572 public void setIgnoreCajaProperties(boolean enabled) {
573 ignoreCajaProperties = enabled;
574 }
575
576 public String syntheticBlockStartMarker;
577
578 public String syntheticBlockEndMarker;
579
580 /** Compiling locale */
581 public String locale;
582
583 /** Sets the special "COMPILED" value to true */
584 public boolean markAsCompiled;
585
586 /** Removes try...catch...finally blocks for easier debugging */
587 public boolean removeTryCatchFinally;
588
589 /** Processes goog.provide() and goog.require() calls */
590 public boolean closurePass;
591
592 /** Processes jQuery aliases */
593 public boolean jqueryPass;
594
595 /** Processes AngularJS-specific annotations */
596 boolean angularPass;
597
598 /** Remove goog.abstractMethod assignments. */
599 boolean removeAbstractMethods;
600
601 /** Remove goog.asserts calls. */
602 boolean removeClosureAsserts;
603
604 /** Gather CSS names (requires closurePass) */
605 public boolean gatherCssNames;
606
607 /** Names of types to strip */
608 public Set<String> stripTypes;
609
610 /** Name suffixes that determine which variables and properties to strip */
611 public Set<String> stripNameSuffixes;
612
613 /** Name prefixes that determine which variables and properties to strip */
614 public Set<String> stripNamePrefixes;
615
616 /** Qualified type name prefixes that determine which types to strip */
617 public Set<String> stripTypePrefixes;
618
619 /** Custom passes */
620 public transient
621 Multimap<CustomPassExecutionTime, CompilerPass> customPasses;
622
623 /** Mark no side effect calls */
624 public boolean markNoSideEffectCalls;
625
626 /** Replacements for @defines. Will be Boolean, Numbers, or Strings */
627 private Map<String, Object> defineReplacements;
628
629 /** What kind of processing to do for goog.tweak functions. */
630 private TweakProcessing tweakProcessing;
631
632 /** Replacements for tweaks. Will be Boolean, Numbers, or Strings */
633 private Map<String, Object> tweakReplacements;
634
635 /** Move top-level function declarations to the top */
636 public boolean moveFunctionDeclarations;
637
638 /** Instrumentation template to use with #recordFunctionInformation */
639 public String instrumentationTemplate;
640
641 String appNameStr;
642
643 /**
644 * App identifier string for use by the instrumentation template's
645 * app_name_setter. @see #instrumentationTemplate
646 */
647 public void setAppNameStr(String appNameStr) {
648 this.appNameStr = appNameStr;
649 }
650
651 /** Record function information */
652 public boolean recordFunctionInformation;
653
654 public boolean generateExports;
655
656 /** Map used in the renaming of CSS class names. */
657 public CssRenamingMap cssRenamingMap;
658
659 /** Whitelist used in the renaming of CSS class names. */
660 Set<String> cssRenamingWhitelist;
661
662 /** Process instances of goog.testing.ObjectPropertyString. */
663 boolean processObjectPropertyString;
664
665 /** Replace id generators */
666 boolean replaceIdGenerators = true; // true by default for legacy reasons.
667
668 /** Id generators to replace. */
669 Set<String> idGenerators;
670
671 /**
672 * A previous map of ids (serialized to a string by a previous compile).
673 * This will be used as a hint during the ReplaceIdGenerators pass, which
674 * will attempt to reuse the same ids.
675 */
676 String idGeneratorsMapSerialized;
677
678 /** Configuration strings */
679 List<String> replaceStringsFunctionDescriptions;
680
681 String replaceStringsPlaceholderToken;
682 // A list of strings that should not be used as replacements
683 Set<String> replaceStringsReservedStrings;
684 // A previous map of replacements to strings.
685 VariableMap replaceStringsInputMap;
686
687 /** List of properties that we report invalidation errors for. */
688 Map<String, CheckLevel> propertyInvalidationErrors;
689
690 /** Transform AMD to CommonJS modules. */
691 boolean transformAMDToCJSModules = false;
692
693 /** Rewrite CommonJS modules so that they can be concatenated together. */
694 boolean processCommonJSModules = false;
695
696 /** CommonJS module prefix. */
697 String commonJSModulePathPrefix =
698 ProcessCommonJSModules.DEFAULT_FILENAME_PREFIX;
699
700
701 //--------------------------------
702 // Output options
703 //--------------------------------
704
705 /** Output in pretty indented format */
706 public boolean prettyPrint;
707
708 /** Line break the output a bit more aggressively */
709 public boolean lineBreak;
710
711 /** Prefer line breaks at end of file */
712 public boolean preferLineBreakAtEndOfFile;
713
714 /** Prints a separator comment before each JS script */
715 public boolean printInputDelimiter;
716
717 /** The string to use as the separator for printInputDelimiter */
718 public String inputDelimiter = "// Input %num%";
719
720 boolean preferSingleQuotes;
721
722 /**
723 * Normally, when there are an equal number of single and double quotes
724 * in a string, the compiler will use double quotes. Set this to true
725 * to prefer single quotes.
726 */
727 public void setPreferSingleQuotes(boolean enabled) {
728 this.preferSingleQuotes = enabled;
729 }
730
731 boolean trustedStrings;
732
733 /**
734 * Some people want to put arbitrary user input into strings, which are then
735 * run through the compiler. These scripts are then put into HTML.
736 * By default, we assume strings are untrusted. If the compiler is run
737 * from the command-line, we assume that strings are trusted.
738 */
739 public void setTrustedStrings(boolean yes) {
740 trustedStrings = yes;
741 }
742
743 String reportPath;
744
745 /** Where to save a report of global name usage */
746 public void setReportPath(String reportPath) {
747 this.reportPath = reportPath;
748 }
749
750 TracerMode tracer;
751
752 public TracerMode getTracerMode() {
753 return tracer;
754 }
755
756 public void setTracerMode(TracerMode mode) {
757 tracer = mode;
758 }
759
760 private boolean colorizeErrorOutput;
761
762 public ErrorFormat errorFormat;
763
764 private ComposeWarningsGuard warningsGuard = new ComposeWarningsGuard();
765
766 int summaryDetailLevel = 1;
767
768 int lineLengthThreshold = CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD;
769
770 //--------------------------------
771 // Special Output Options
772 //--------------------------------
773
774 /**
775 * Whether the exports should be made available via {@link Result} after
776 * compilation. This is implicitly true if {@link #externExportsPath} is set.
777 */
778 private boolean externExports;
779
780 /** The output path for the created externs file. */
781 String externExportsPath;
782
783 String nameReferenceReportPath;
784
785 /** Where to save a cross-reference report from the name reference graph */
786 public void setNameReferenceReportPath(String filePath) {
787 nameReferenceReportPath = filePath;
788 }
789
790 String nameReferenceGraphPath;
791
792 /** Where to save the name reference graph */
793 public void setNameReferenceGraphPath(String filePath) {
794 nameReferenceGraphPath = filePath;
795 }
796
797 //--------------------------------
798 // Debugging Options
799 //--------------------------------
800
801 /** The output path for the source map. */
802 public String sourceMapOutputPath;
803
804 /** The detail level for the generated source map. */
805 public SourceMap.DetailLevel sourceMapDetailLevel =
806 SourceMap.DetailLevel.SYMBOLS;
807
808 /** The source map file format */
809 public SourceMap.Format sourceMapFormat =
810 SourceMap.Format.DEFAULT;
811
812 public List<SourceMap.LocationMapping> sourceMapLocationMappings =
813 Collections.emptyList();
814
815 /**
816 * Charset to use when generating code. If null, then output ASCII.
817 * This needs to be a string because CompilerOptions is serializable.
818 */
819 String outputCharset;
820
821 /**
822 * Whether the named objects types included 'undefined' by default.
823 */
824 boolean looseTypes;
825
826 /**
827 * When set, assume that apparently side-effect free code is meaningful.
828 */
829 boolean protectHiddenSideEffects;
830
831 /**
832 * When enabled, assume that apparently side-effect free code is meaningful.
833 */
834 public void setProtectHiddenSideEffects(boolean enable) {
835 this.protectHiddenSideEffects = enable;
836 }
837
838 /**
839 * Data holder Alias Transformation information accumulated during a compile.
840 */
841 private transient AliasTransformationHandler aliasHandler;
842
843 /**
844 * Handler for compiler warnings and errors.
845 */
846 transient ErrorHandler errorHandler;
847
848 /**
849 * Initializes compiler options. All options are disabled by default.
850 *
851 * Command-line frontends to the compiler should set these properties
852 * like a builder.
853 */
854 public CompilerOptions() {
855 // Accepted language
856 languageIn = LanguageMode.ECMASCRIPT3;
857
858 // Language variation
859 acceptConstKeyword = false;
860
861 // Checks
862 skipAllPasses = false;
863 nameAnonymousFunctionsOnly = false;
864 devMode = DevMode.OFF;
865 checkDeterminism = false;
866 checkSymbols = false;
867 aggressiveVarCheck = CheckLevel.OFF;
868 checkSuspiciousCode = false;
869 checkControlStructures = false;
870 checkTypes = false;
871 tightenTypes = false;
872 reportMissingOverride = CheckLevel.OFF;
873 reportUnknownTypes = CheckLevel.OFF;
874 checkRequires = CheckLevel.OFF;
875 checkProvides = CheckLevel.OFF;
876 checkGlobalNamesLevel = CheckLevel.OFF;
877 brokenClosureRequiresLevel = CheckLevel.ERROR;
878 checkGlobalThisLevel = CheckLevel.OFF;
879 checkUnreachableCode = CheckLevel.OFF;
880 checkMissingReturn = CheckLevel.OFF;
881 checkMissingGetCssNameLevel = CheckLevel.OFF;
882 checkMissingGetCssNameBlacklist = null;
883 checkCaja = false;
884 computeFunctionSideEffects = false;
885 chainCalls = false;
886 extraAnnotationNames = null;
887
888 // Optimizations
889 foldConstants = false;
890 coalesceVariableNames = false;
891 deadAssignmentElimination = false;
892 inlineConstantVars = false;
893 inlineFunctions = false;
894 inlineLocalFunctions = false;
895 assumeStrictThis = false;
896 assumeClosuresOnlyCaptureReferences = false;
897 inlineProperties = false;
898 crossModuleCodeMotion = false;
899 crossModuleMethodMotion = false;
900 inlineGetters = false;
901 inlineVariables = false;
902 inlineLocalVariables = false;
903 smartNameRemoval = false;
904 removeDeadCode = false;
905 extractPrototypeMemberDeclarations = false;
906 removeUnusedPrototypeProperties = false;
907 removeUnusedPrototypePropertiesInExterns = false;
908 removeUnusedClassProperties = false;
909 removeUnusedVars = false;
910 removeUnusedLocalVars = false;
911 aliasExternals = false;
912 collapseVariableDeclarations = false;
913 groupVariableDeclarations = false;
914 collapseAnonymousFunctions = false;
915 aliasableStrings = Collections.emptySet();
916 aliasStringsBlacklist = "";
917 aliasAllStrings = false;
918 outputJsStringUsage = false;
919 convertToDottedProperties = false;
920 rewriteFunctionExpressions = false;
921 optimizeParameters = false;
922 optimizeReturns = false;
923
924 // Renaming
925 variableRenaming = VariableRenamingPolicy.OFF;
926 propertyRenaming = PropertyRenamingPolicy.OFF;
927 propertyAffinity = false;
928 labelRenaming = false;
929 generatePseudoNames = false;
930 shadowVariables = false;
931 renamePrefix = null;
932 aliasKeywords = false;
933 collapseProperties = false;
934 collapsePropertiesOnExternTypes = false;
935 collapseObjectLiterals = false;
936 devirtualizePrototypeMethods = false;
937 disambiguateProperties = false;
938 ambiguateProperties = false;
939 anonymousFunctionNaming = AnonymousFunctionNamingPolicy.OFF;
940 exportTestFunctions = false;
941
942 // Alterations
943 runtimeTypeCheck = false;
944 runtimeTypeCheckLogFunction = null;
945 ignoreCajaProperties = false;
946 syntheticBlockStartMarker = null;
947 syntheticBlockEndMarker = null;
948 locale = null;
949 markAsCompiled = false;
950 removeTryCatchFinally = false;
951 closurePass = false;
952 jqueryPass = false;
953 angularPass = false;
954 removeAbstractMethods = true;
955 removeClosureAsserts = false;
956 stripTypes = Collections.emptySet();
957 stripNameSuffixes = Collections.emptySet();
958 stripNamePrefixes = Collections.emptySet();
959 stripTypePrefixes = Collections.emptySet();
960 customPasses = null;
961 markNoSideEffectCalls = false;
962 defineReplacements = Maps.newHashMap();
963 tweakProcessing = TweakProcessing.OFF;
964 tweakReplacements = Maps.newHashMap();
965 moveFunctionDeclarations = false;
966 instrumentationTemplate = null;
967 appNameStr = "";
968 recordFunctionInformation = false;
969 generateExports = false;
970 cssRenamingMap = null;
971 cssRenamingWhitelist = null;
972 processObjectPropertyString = false;
973 idGenerators = Collections.emptySet();
974 replaceStringsFunctionDescriptions = Collections.emptyList();
975 replaceStringsPlaceholderToken = "";
976 replaceStringsReservedStrings = Collections.emptySet();
977 propertyInvalidationErrors = Maps.newHashMap();
978
979 // Output
980 printInputDelimiter = false;
981 prettyPrint = false;
982 lineBreak = false;
983 preferLineBreakAtEndOfFile = false;
984 reportPath = null;
985 tracer = TracerMode.OFF;
986 colorizeErrorOutput = false;
987 errorFormat = ErrorFormat.SINGLELINE;
988 debugFunctionSideEffectsPath = null;
989 externExports = false;
990 nameReferenceReportPath = null;
991 nameReferenceGraphPath = null;
992
993 // Debugging
994 aliasHandler = NULL_ALIAS_TRANSFORMATION_HANDLER;
995 errorHandler = null;
996 }
997
998 /**
999 * @return Whether to attempt to remove unused class properties
1000 */
1001 public boolean isRemoveUnusedClassProperties() {
1002 return removeUnusedClassProperties;
1003 }
1004
1005 /**
1006 * @param removeUnusedClassProperties Whether to attempt to remove
1007 * unused class properties
1008 */
1009 public void setRemoveUnusedClassProperties(boolean removeUnusedClassProperties) {
1010 this.removeUnusedClassProperties = removeUnusedClassProperties;
1011 }
1012
1013 /**
1014 * Returns the map of define replacements.
1015 */
1016 public Map<String, Node> getDefineReplacements() {
1017 return getReplacementsHelper(defineReplacements);
1018 }
1019
1020 /**
1021 * Returns the map of tweak replacements.
1022 */
1023 public Map<String, Node> getTweakReplacements() {
1024 return getReplacementsHelper(tweakReplacements);
1025 }
1026
1027 /**
1028 * Creates a map of String->Node from a map of String->Number/String/Boolean.
1029 */
1030 private static Map<String, Node> getReplacementsHelper(
1031 Map<String, Object> source) {
1032 Map<String, Node> map = Maps.newHashMap();
1033 for (Map.Entry<String, Object> entry : source.entrySet()) {
1034 String name = entry.getKey();
1035 Object value = entry.getValue();
1036 if (value instanceof Boolean) {
1037 map.put(name, NodeUtil.booleanNode(((Boolean) value).booleanValue()));
1038 } else if (value instanceof Integer) {
1039 map.put(name, IR.number(((Integer) value).intValue()));
1040 } else if (value instanceof Double) {
1041 map.put(name, IR.number(((Double) value).doubleValue()));
1042 } else {
1043 Preconditions.checkState(value instanceof String);
1044 map.put(name, IR.string((String) value));
1045 }
1046 }
1047 return map;
1048 }
1049
1050 /**
1051 * Sets the value of the {@code @define} variable in JS
1052 * to a boolean literal.
1053 */
1054 public void setDefineToBooleanLiteral(String defineName, boolean value) {
1055 defineReplacements.put(defineName, new Boolean(value));
1056 }
1057
1058 /**
1059 * Sets the value of the {@code @define} variable in JS to a
1060 * String literal.
1061 */
1062 public void setDefineToStringLiteral(String defineName, String value) {
1063 defineReplacements.put(defineName, value);
1064 }
1065
1066 /**
1067 * Sets the value of the {@code @define} variable in JS to a
1068 * number literal.
1069 */
1070 public void setDefineToNumberLiteral(String defineName, int value) {
1071 defineReplacements.put(defineName, new Integer(value));
1072 }
1073
1074 /**
1075 * Sets the value of the {@code @define} variable in JS to a
1076 * number literal.
1077 */
1078 public void setDefineToDoubleLiteral(String defineName, double value) {
1079 defineReplacements.put(defineName, new Double(value));
1080 }
1081
1082 /**
1083 * Sets the value of the tweak in JS
1084 * to a boolean literal.
1085 */
1086 public void setTweakToBooleanLiteral(String tweakId, boolean value) {
1087 tweakReplacements.put(tweakId, new Boolean(value));
1088 }
1089
1090 /**
1091 * Sets the value of the tweak in JS to a
1092 * String literal.
1093 */
1094 public void setTweakToStringLiteral(String tweakId, String value) {
1095 tweakReplacements.put(tweakId, value);
1096 }
1097
1098 /**
1099 * Sets the value of the tweak in JS to a
1100 * number literal.
1101 */
1102 public void setTweakToNumberLiteral(String tweakId, int value) {
1103 tweakReplacements.put(tweakId, new Integer(value));
1104 }
1105
1106 /**
1107 * Sets the value of the tweak in JS to a
1108 * number literal.
1109 */
1110 public void setTweakToDoubleLiteral(String tweakId, double value) {
1111 tweakReplacements.put(tweakId, new Double(value));
1112 }
1113
1114 /**
1115 * Skip all possible passes, to make the compiler as fast as possible.
1116 */
1117 public void skipAllCompilerPasses() {
1118 skipAllPasses = true;
1119 }
1120
1121 /**
1122 * Whether the warnings guard in this Options object enables the given
1123 * group of warnings.
1124 */
1125 boolean enables(DiagnosticGroup type) {
1126 return warningsGuard.enables(type);
1127 }
1128
1129 /**
1130 * Whether the warnings guard in this Options object disables the given
1131 * group of warnings.
1132 */
1133 boolean disables(DiagnosticGroup type) {
1134 return warningsGuard.disables(type);
1135 }
1136
1137 /**
1138 * Configure the given type of warning to the given level.
1139 */
1140 public void setWarningLevel(DiagnosticGroup type, CheckLevel level) {
1141 addWarningsGuard(new DiagnosticGroupWarningsGuard(type, level));
1142 }
1143
1144 WarningsGuard getWarningsGuard() {
1145 return warningsGuard;
1146 }
1147
1148 /**
1149 * Reset the warnings guard.
1150 */
1151 public void resetWarningsGuard() {
1152 warningsGuard = new ComposeWarningsGuard();
1153 }
1154
1155 /**
1156 * The emergency fail safe removes all strict and ERROR-escalating
1157 * warnings guards.
1158 */
1159 void useEmergencyFailSafe() {
1160 warningsGuard = warningsGuard.makeEmergencyFailSafeGuard();
1161 }
1162
1163 /**
1164 * Add a guard to the set of warnings guards.
1165 */
1166 public void addWarningsGuard(WarningsGuard guard) {
1167 warningsGuard.addGuard(guard);
1168 }
1169
1170 /**
1171 * Sets the variable and property renaming policies for the compiler,
1172 * in a way that clears warnings about the renaming policy being
1173 * uninitialized from flags.
1174 */
1175 public void setRenamingPolicy(VariableRenamingPolicy newVariablePolicy,
1176 PropertyRenamingPolicy newPropertyPolicy) {
1177 this.variableRenaming = newVariablePolicy;
1178 this.propertyRenaming = newPropertyPolicy;
1179 }
1180
1181 public void setPropertyAffinity(boolean useAffinity) {
1182 this.propertyAffinity = useAffinity;
1183 }
1184
1185 /** Should shadow outer scope variable name during renaming. */
1186 public void setShadowVariables(boolean shadow) {
1187 this.shadowVariables = shadow;
1188 }
1189
1190 /**
1191 * If true, flattens multi-level property names on extern types
1192 * (e.g. String$f = x). This should only be used with the typed version of
1193 * the externs files.
1194 */
1195 public void setCollapsePropertiesOnExternTypes(boolean collapse) {
1196 collapsePropertiesOnExternTypes = collapse;
1197 }
1198
1199 /**
1200 * If true, process goog.testing.ObjectPropertyString instances.
1201 */
1202 public void setProcessObjectPropertyString(boolean process) {
1203 processObjectPropertyString = process;
1204 }
1205
1206 /**
1207 * @param replaceIdGenerators the replaceIdGenerators to set
1208 */
1209 public void setReplaceIdGenerators(boolean replaceIdGenerators) {
1210 this.replaceIdGenerators = replaceIdGenerators;
1211 }
1212
1213 /**
1214 * Sets the id generators to replace.
1215 */
1216 public void setIdGenerators(Set<String> idGenerators) {
1217 this.idGenerators = Sets.newHashSet(idGenerators);
1218 }
1219
1220 /**
1221 * A previous map of ids (serialized to a string by a previous compile).
1222 * This will be used as a hint during the ReplaceIdGenerators pass, which
1223 * will attempt to reuse the same ids.
1224 */
1225 public void setIdGeneratorsMap(String previousMappings) {
1226 this.idGeneratorsMapSerialized = previousMappings;
1227 }
1228
1229 /**
1230 * Set the function inlining policy for the compiler.
1231 */
1232 public void setInlineFunctions(Reach reach) {
1233 switch (reach) {
1234 case ALL:
1235 this.inlineFunctions = true;
1236 this.inlineLocalFunctions = true;
1237 break;
1238 case LOCAL_ONLY:
1239 this.inlineFunctions = false;
1240 this.inlineLocalFunctions = true;
1241 break;
1242 case NONE:
1243 this.inlineFunctions = false;
1244 this.inlineLocalFunctions = false;
1245 break;
1246 default:
1247 throw new IllegalStateException("unexpected");
1248 }
1249 }
1250
1251 /**
1252 * Set the variable inlining policy for the compiler.
1253 */
1254 public void setInlineVariables(Reach reach) {
1255 switch (reach) {
1256 case ALL:
1257 this.inlineVariables = true;
1258 this.inlineLocalVariables = true;
1259 break;
1260 case LOCAL_ONLY:
1261 this.inlineVariables = false;
1262 this.inlineLocalVariables = true;
1263 break;
1264 case NONE:
1265 this.inlineVariables = false;
1266 this.inlineLocalVariables = false;
1267 break;
1268 default:
1269 throw new IllegalStateException("unexpected");
1270 }
1271 }
1272
1273 /**
1274 * Set the function inlining policy for the compiler.
1275 */
1276 public void setInlineProperties(boolean enable) {
1277 inlineProperties = enable;
1278 }
1279
1280 /**
1281 * Set the variable removal policy for the compiler.
1282 */
1283 @Deprecated
1284 public void setRemoveUnusedVariable(Reach reach) {
1285 setRemoveUnusedVariables(reach);
1286 }
1287
1288 /**
1289 * Set the variable removal policy for the compiler.
1290 */
1291 public void setRemoveUnusedVariables(Reach reach) {
1292 switch (reach) {
1293 case ALL:
1294 this.removeUnusedVars = true;
1295 this.removeUnusedLocalVars = true;
1296 break;
1297 case LOCAL_ONLY:
1298 this.removeUnusedVars = false;
1299 this.removeUnusedLocalVars = true;
1300 break;
1301 case NONE:
1302 this.removeUnusedVars = false;
1303 this.removeUnusedLocalVars = false;
1304 break;
1305 default:
1306 throw new IllegalStateException("unexpected");
1307 }
1308 }
1309
1310 /**
1311 * Sets the functions whose debug strings to replace.
1312 */
1313 public void setReplaceStringsConfiguration(
1314 String placeholderToken, List<String> functionDescriptors) {
1315 this.replaceStringsPlaceholderToken = placeholderToken;
1316 this.replaceStringsFunctionDescriptions =
1317 Lists.newArrayList(functionDescriptors);
1318 }
1319
1320 @Deprecated
1321 public void setRewriteNewDateGoogNow(boolean rewrite) {
1322 }
1323
1324 public void setRemoveAbstractMethods(boolean remove) {
1325 this.removeAbstractMethods = remove;
1326 }
1327
1328 public void setRemoveClosureAsserts(boolean remove) {
1329 this.removeClosureAsserts = remove;
1330 }
1331
1332 /**
1333 * If true, name anonymous functions only. All other passes will be skipped.
1334 */
1335 public void setNameAnonymousFunctionsOnly(boolean value) {
1336 this.nameAnonymousFunctionsOnly = value;
1337 }
1338
1339 public void setColorizeErrorOutput(boolean colorizeErrorOutput) {
1340 this.colorizeErrorOutput = colorizeErrorOutput;
1341 }
1342
1343 public boolean shouldColorizeErrorOutput() {
1344 return colorizeErrorOutput;
1345 }
1346
1347 /**
1348 * If true, chain calls to functions that return this.
1349 */
1350 public void setChainCalls(boolean value) {
1351 this.chainCalls = value;
1352 }
1353
1354 /**
1355 * If true, accept `const' keyword.
1356 */
1357 public void setAcceptConstKeyword(boolean value) {
1358 this.acceptConstKeyword = value;
1359 }
1360
1361 /**
1362 * Enable run-time type checking, which adds JS type assertions for debugging.
1363 *
1364 * @param logFunction A JS function to be used for logging run-time type
1365 * assertion failures.
1366 */
1367 public void enableRuntimeTypeCheck(String logFunction) {
1368 this.runtimeTypeCheck = true;
1369 this.runtimeTypeCheckLogFunction = logFunction;
1370 }
1371
1372 public void disableRuntimeTypeCheck() {
1373 this.runtimeTypeCheck = false;
1374 }
1375
1376 public void setGenerateExports(boolean generateExports) {
1377 this.generateExports = generateExports;
1378 }
1379
1380 public void setAngularPass(boolean angularPass) {
1381 this.angularPass = angularPass;
1382 }
1383
1384 public void setCodingConvention(CodingConvention codingConvention) {
1385 this.codingConvention = codingConvention;
1386 }
1387
1388 public CodingConvention getCodingConvention() {
1389 return codingConvention;
1390 }
1391
1392 /**
1393 * Sets dependency options. See the DependencyOptions class for more info.
1394 * This supersedes manageClosureDependencies.
1395 */
1396 public void setDependencyOptions(DependencyOptions options) {
1397 Preconditions.checkNotNull(options);
1398 this.dependencyOptions = options;
1399 }
1400
1401 /**
1402 * Sort inputs by their goog.provide/goog.require calls, and prune inputs
1403 * whose symbols are not required.
1404 */
1405 public void setManageClosureDependencies(boolean newVal) {
1406 dependencyOptions.setDependencySorting(
1407 newVal || dependencyOptions.shouldSortDependencies());
1408 dependencyOptions.setDependencyPruning(
1409 newVal || dependencyOptions.shouldPruneDependencies());
1410 dependencyOptions.setMoocherDropping(false);
1411 manageClosureDependencies = newVal;
1412 }
1413
1414 /**
1415 * Sort inputs by their goog.provide/goog.require calls.
1416 *
1417 * @param entryPoints Entry points to the program. Must be goog.provide'd
1418 * symbols. Any goog.provide'd symbols that are not a transitive
1419 * dependency of the entry points will be deleted.
1420 * Files without goog.provides, and their dependencies,
1421 * will always be left in.
1422 */
1423 public void setManageClosureDependencies(List<String> entryPoints) {
1424 Preconditions.checkNotNull(entryPoints);
1425 setManageClosureDependencies(true);
1426 dependencyOptions.setEntryPoints(entryPoints);
1427 }
1428
1429 /**
1430 * Controls how detailed the compilation summary is. Values:
1431 * 0 (never print summary), 1 (print summary only if there are
1432 * errors or warnings), 2 (print summary if type checking is on,
1433 * see --check_types), 3 (always print summary). The default level
1434 * is 1
1435 */
1436 public void setSummaryDetailLevel(int summaryDetailLevel) {
1437 this.summaryDetailLevel = summaryDetailLevel;
1438 }
1439
1440 /**
1441 * @deprecated replaced by {@link #setExternExports}
1442 */
1443 @Deprecated
1444 public void enableExternExports(boolean enabled) {
1445 this.externExports = enabled;
1446 }
1447
1448 public void setExtraAnnotationNames(Iterable<String> extraAnnotationNames) {
1449 this.extraAnnotationNames = ImmutableSet.copyOf(extraAnnotationNames);
1450 }
1451
1452 public boolean isExternExportsEnabled() {
1453 return externExports;
1454 }
1455
1456 /**
1457 * Sets the output charset by name.
1458 */
1459 public void setOutputCharset(String charsetName) {
1460 this.outputCharset = charsetName;
1461 }
1462
1463 /**
1464 * Gets the output charset as a rich object.
1465 */
1466 Charset getOutputCharset() {
1467 return outputCharset == null ? null : Charset.forName(outputCharset);
1468 }
1469
1470 /**
1471 * Sets how goog.tweak calls are processed.
1472 */
1473 public void setTweakProcessing(TweakProcessing tweakProcessing) {
1474 this.tweakProcessing = tweakProcessing;
1475 }
1476
1477 public TweakProcessing getTweakProcessing() {
1478 return tweakProcessing;
1479 }
1480
1481 /**
1482 * Sets how goog.tweak calls are processed.
1483 */
1484 public void setLanguageIn(LanguageMode languageIn) {
1485 this.languageIn = languageIn;
1486 this.languageOut = languageIn;
1487 }
1488
1489 public LanguageMode getLanguageIn() {
1490 return languageIn;
1491 }
1492
1493 public LanguageMode getLanguageOut() {
1494 return languageOut;
1495 }
1496
1497 /**
1498 * Whether to include "undefined" in the default types.
1499 * For example:
1500 * "{Object}" is normally "Object|null" becomes "Object|null|undefined"
1501 * "{?string}" is normally "string|null" becomes "string|null|undefined"
1502 * In either case "!" annotated types excluded both null and undefined.
1503 */
1504 public void setLooseTypes(boolean looseTypes) {
1505 this.looseTypes = looseTypes;
1506 }
1507
1508 @Override
1509 public Object clone() throws CloneNotSupportedException {
1510 CompilerOptions clone = (CompilerOptions) super.clone();
1511 // TODO(bolinfest): Add relevant custom cloning.
1512 return clone;
1513 }
1514
1515 public void setAliasTransformationHandler(
1516 AliasTransformationHandler changes) {
1517 this.aliasHandler = changes;
1518 }
1519
1520 public AliasTransformationHandler getAliasTransformationHandler() {
1521 return this.aliasHandler;
1522 }
1523
1524 /**
1525 * Set a custom handler for warnings and errors.
1526 *
1527 * This is mostly used for piping the warnings and errors to
1528 * a file behind the scenes.
1529 *
1530 * If you want to filter warnings and errors, you should use a WarningsGuard.
1531 *
1532 * If you want to change how warnings and errors are reported to the user,
1533 * you should set a ErrorManager on the Compiler. An ErrorManager is
1534 * intended to summarize the errors for a single compile job.
1535 */
1536 public void setErrorHandler(ErrorHandler handler) {
1537 this.errorHandler = handler;
1538 }
1539
1540 /**
1541 * If true, enables type inference. If checkTypes is enabled, this flag has
1542 * no effect.
1543 */
1544 public void setInferTypes(boolean enable) {
1545 inferTypes = enable;
1546 }
1547
1548 /**
1549 * Gets the inferTypes flag. Note that if checkTypes is enabled, this flag
1550 * is ignored when configuring the compiler.
1551 */
1552 public boolean getInferTypes() {
1553 return inferTypes;
1554 }
1555
1556 /**
1557 * @return Whether assumeStrictThis is set.
1558 */
1559 public boolean assumeStrictThis() {
1560 return assumeStrictThis;
1561 }
1562
1563 /**
1564 * If true, enables enables additional optimizations.
1565 */
1566 public void setAssumeStrictThis(boolean enable) {
1567 this.assumeStrictThis = enable;
1568 }
1569
1570 /**
1571 * @return Whether assumeClosuresOnlyCaptureReferences is set.
1572 */
1573 public boolean assumeClosuresOnlyCaptureReferences() {
1574 return assumeClosuresOnlyCaptureReferences;
1575 }
1576
1577 /**
1578 * Whether to assume closures capture only what they reference. This allows
1579 * more aggressive function inlining.
1580 */
1581 public void setAssumeClosuresOnlyCaptureReferences(boolean enable) {
1582 this.assumeClosuresOnlyCaptureReferences = enable;
1583 }
1584
1585 /**
1586 * Sets the list of properties that we report property invalidation errors
1587 * for.
1588 */
1589 public void setPropertyInvalidationErrors(
1590 Map<String, CheckLevel> propertyInvalidationErrors) {
1591 this.propertyInvalidationErrors =
1592 Maps.newHashMap(propertyInvalidationErrors);
1593 }
1594
1595 public void setLanguageOut(LanguageMode languageOut) {
1596 this.languageOut = languageOut;
1597 }
1598
1599 public void setIdeMode(boolean ideMode) {
1600 this.ideMode = ideMode;
1601 }
1602
1603 /**
1604 * Whether to keep internal data structures around after we're
1605 * finished compiling. We do this by default when IDE mode is on.
1606 */
1607 public void setSaveDataStructures(boolean save) {
1608 this.saveDataStructures = save;
1609 }
1610
1611 public void setSkipAllPasses(boolean skipAllPasses) {
1612 this.skipAllPasses = skipAllPasses;
1613 }
1614
1615 public void setDevMode(DevMode devMode) {
1616 this.devMode = devMode;
1617 }
1618
1619 public void setCheckDeterminism(boolean checkDeterminism) {
1620 this.checkDeterminism = checkDeterminism;
1621 }
1622
1623 public boolean getCheckDeterminism() {
1624 return checkDeterminism;
1625 }
1626
1627 public void setMessageBundle(MessageBundle messageBundle) {
1628 this.messageBundle = messageBundle;
1629 }
1630
1631 public void setCheckSymbols(boolean checkSymbols) {
1632 this.checkSymbols = checkSymbols;
1633 }
1634
1635 public void setCheckSuspiciousCode(boolean checkSuspiciousCode) {
1636 this.checkSuspiciousCode = checkSuspiciousCode;
1637 }
1638
1639 public void setCheckControlStructures(boolean checkControlStructures) {
1640 this.checkControlStructures = checkControlStructures;
1641 }
1642
1643 public void setCheckTypes(boolean checkTypes) {
1644 this.checkTypes = checkTypes;
1645 }
1646
1647 public void setCheckMissingGetCssNameBlacklist(String blackList) {
1648 this.checkMissingGetCssNameBlacklist = blackList;
1649 }
1650
1651 public void setFoldConstants(boolean foldConstants) {
1652 this.foldConstants = foldConstants;
1653 }
1654
1655 public void setDeadAssignmentElimination(boolean deadAssignmentElimination) {
1656 this.deadAssignmentElimination = deadAssignmentElimination;
1657 }
1658
1659 public void setInlineConstantVars(boolean inlineConstantVars) {
1660 this.inlineConstantVars = inlineConstantVars;
1661 }
1662
1663 public void setInlineFunctions(boolean inlineFunctions) {
1664 this.inlineFunctions = inlineFunctions;
1665 }
1666
1667 public void setInlineLocalFunctions(boolean inlineLocalFunctions) {
1668 this.inlineLocalFunctions = inlineLocalFunctions;
1669 }
1670
1671 public void setCrossModuleCodeMotion(boolean crossModuleCodeMotion) {
1672 this.crossModuleCodeMotion = crossModuleCodeMotion;
1673 }
1674
1675 public void setCoalesceVariableNames(boolean coalesceVariableNames) {
1676 this.coalesceVariableNames = coalesceVariableNames;
1677 }
1678
1679 public void setCrossModuleMethodMotion(boolean crossModuleMethodMotion) {
1680 this.crossModuleMethodMotion = crossModuleMethodMotion;
1681 }
1682
1683 public void setInlineGetters(boolean inlineGetters) {
1684 this.inlineGetters = inlineGetters;
1685 }
1686
1687 public void setInlineVariables(boolean inlineVariables) {
1688 this.inlineVariables = inlineVariables;
1689 }
1690
1691 public void setInlineLocalVariables(boolean inlineLocalVariables) {
1692 this.inlineLocalVariables = inlineLocalVariables;
1693 }
1694
1695 public void setFlowSensitiveInlineVariables(boolean enabled) {
1696 this.flowSensitiveInlineVariables = enabled;
1697 }
1698
1699 public void setSmartNameRemoval(boolean smartNameRemoval) {
1700 this.smartNameRemoval = smartNameRemoval;
1701 }
1702
1703 public void setRemoveDeadCode(boolean removeDeadCode) {
1704 this.removeDeadCode = removeDeadCode;
1705 }
1706
1707 public void setExtractPrototypeMemberDeclarations(boolean enabled) {
1708 this.extractPrototypeMemberDeclarations = enabled;
1709 }
1710
1711 public void setRemoveUnusedPrototypeProperties(boolean enabled) {
1712 this.removeUnusedPrototypeProperties = enabled;
1713 }
1714
1715 public void setRemoveUnusedPrototypePropertiesInExterns(
1716 boolean enabled) {
1717 this.removeUnusedPrototypePropertiesInExterns = enabled;
1718 }
1719
1720 public void setRemoveUnusedVars(boolean removeUnusedVars) {
1721 this.removeUnusedVars = removeUnusedVars;
1722 }
1723
1724 public void setRemoveUnusedLocalVars(boolean removeUnusedLocalVars) {
1725 this.removeUnusedLocalVars = removeUnusedLocalVars;
1726 }
1727
1728 public void setAliasExternals(boolean aliasExternals) {
1729 this.aliasExternals = aliasExternals;
1730 }
1731
1732 public void setCollapseVariableDeclarations(boolean enabled) {
1733 this.collapseVariableDeclarations = enabled;
1734 }
1735
1736 public void setGroupVariableDeclarations(boolean enabled) {
1737 this.groupVariableDeclarations = enabled;
1738 }
1739
1740 public void setCollapseAnonymousFunctions(boolean enabled) {
1741 this.collapseAnonymousFunctions = enabled;
1742 }
1743
1744 public void setAliasableStrings(Set<String> aliasableStrings) {
1745 this.aliasableStrings = aliasableStrings;
1746 }
1747
1748 public void setAliasStringsBlacklist(String aliasStringsBlacklist) {
1749 this.aliasStringsBlacklist = aliasStringsBlacklist;
1750 }
1751
1752 public void setAliasAllStrings(boolean aliasAllStrings) {
1753 this.aliasAllStrings = aliasAllStrings;
1754 }
1755
1756 public void setOutputJsStringUsage(boolean outputJsStringUsage) {
1757 this.outputJsStringUsage = outputJsStringUsage;
1758 }
1759
1760 public void setConvertToDottedProperties(boolean convertToDottedProperties) {
1761 this.convertToDottedProperties = convertToDottedProperties;
1762 }
1763
1764 public void setRewriteFunctionExpressions(boolean rewriteFunctionExpressions) {
1765 this.rewriteFunctionExpressions = rewriteFunctionExpressions;
1766 }
1767
1768 public void setOptimizeParameters(boolean optimizeParameters) {
1769 this.optimizeParameters = optimizeParameters;
1770 }
1771
1772 public void setOptimizeReturns(boolean optimizeReturns) {
1773 this.optimizeReturns = optimizeReturns;
1774 }
1775
1776 public void setOptimizeCalls(boolean optimizeCalls) {
1777 this.optimizeCalls = optimizeCalls;
1778 }
1779
1780 public void setOptimizeArgumentsArray(boolean optimizeArgumentsArray) {
1781 this.optimizeArgumentsArray = optimizeArgumentsArray;
1782 }
1783
1784 public void setVariableRenaming(VariableRenamingPolicy variableRenaming) {
1785 this.variableRenaming = variableRenaming;
1786 }
1787
1788 public void setPropertyRenaming(PropertyRenamingPolicy propertyRenaming) {
1789 this.propertyRenaming = propertyRenaming;
1790 }
1791
1792 public void setLabelRenaming(boolean labelRenaming) {
1793 this.labelRenaming = labelRenaming;
1794 }
1795
1796 public void setReserveRawExports(boolean reserveRawExports) {
1797 this.reserveRawExports = reserveRawExports;
1798 }
1799
1800 public void setGeneratePseudoNames(boolean generatePseudoNames) {
1801 this.generatePseudoNames = generatePseudoNames;
1802 }
1803
1804 public void setRenamePrefix(String renamePrefix) {
1805 this.renamePrefix = renamePrefix;
1806 }
1807
1808 public void setRenamePrefixNamespace(String renamePrefixNamespace) {
1809 this.renamePrefixNamespace = renamePrefixNamespace;
1810 }
1811
1812 public void setAliasKeywords(boolean aliasKeywords) {
1813 this.aliasKeywords = aliasKeywords;
1814 }
1815
1816 public void setCollapseProperties(boolean collapseProperties) {
1817 this.collapseProperties = collapseProperties;
1818 }
1819
1820 public void setDevirtualizePrototypeMethods(boolean devirtualizePrototypeMethods) {
1821 this.devirtualizePrototypeMethods = devirtualizePrototypeMethods;
1822 }
1823
1824 public void setComputeFunctionSideEffects(boolean computeFunctionSideEffects) {
1825 this.computeFunctionSideEffects = computeFunctionSideEffects;
1826 }
1827
1828 public void setDebugFunctionSideEffectsPath(String debugFunctionSideEffectsPath) {
1829 this.debugFunctionSideEffectsPath = debugFunctionSideEffectsPath;
1830 }
1831
1832 public void setDisambiguateProperties(boolean disambiguateProperties) {
1833 this.disambiguateProperties = disambiguateProperties;
1834 }
1835
1836 public void setAmbiguateProperties(boolean ambiguateProperties) {
1837 this.ambiguateProperties = ambiguateProperties;
1838 }
1839
1840 public void setAnonymousFunctionNaming(
1841 AnonymousFunctionNamingPolicy anonymousFunctionNaming) {
1842 this.anonymousFunctionNaming = anonymousFunctionNaming;
1843 }
1844
1845 public void setInputAnonymousFunctionNamingMap(VariableMap inputMap) {
1846 this.inputAnonymousFunctionNamingMap = inputMap;
1847 }
1848
1849 @Deprecated
1850 public void setInputVariableMapSerialized(byte[] inputVariableMapSerialized)
1851 throws ParseException {
1852 this.inputVariableMap = VariableMap.fromBytes(inputVariableMapSerialized);
1853 }
1854
1855 public void setInputVariableMap(VariableMap inputVariableMap) {
1856 this.inputVariableMap = inputVariableMap;
1857 }
1858
1859 @Deprecated
1860 public void setInputPropertyMapSerialized(byte[] inputPropertyMapSerialized)
1861 throws ParseException {
1862 this.inputPropertyMap = VariableMap.fromBytes(inputPropertyMapSerialized);
1863 }
1864
1865 public void setInputPropertyMap(VariableMap inputPropertyMap) {
1866 this.inputPropertyMap = inputPropertyMap;
1867 }
1868
1869 public void setExportTestFunctions(boolean exportTestFunctions) {
1870 this.exportTestFunctions = exportTestFunctions;
1871 }
1872
1873 public void setRuntimeTypeCheck(boolean runtimeTypeCheck) {
1874 this.runtimeTypeCheck = runtimeTypeCheck;
1875 }
1876
1877 public void setRuntimeTypeCheckLogFunction(String runtimeTypeCheckLogFunction) {
1878 this.runtimeTypeCheckLogFunction = runtimeTypeCheckLogFunction;
1879 }
1880
1881 public void setSyntheticBlockStartMarker(String syntheticBlockStartMarker) {
1882 this.syntheticBlockStartMarker = syntheticBlockStartMarker;
1883 }
1884
1885 public void setSyntheticBlockEndMarker(String syntheticBlockEndMarker) {
1886 this.syntheticBlockEndMarker = syntheticBlockEndMarker;
1887 }
1888
1889 public void setLocale(String locale) {
1890 this.locale = locale;
1891 }
1892
1893 public void setMarkAsCompiled(boolean markAsCompiled) {
1894 this.markAsCompiled = markAsCompiled;
1895 }
1896
1897 public void setRemoveTryCatchFinally(boolean removeTryCatchFinally) {
1898 this.removeTryCatchFinally = removeTryCatchFinally;
1899 }
1900
1901 public void setClosurePass(boolean closurePass) {
1902 this.closurePass = closurePass;
1903 }
1904
1905 public void setGatherCssNames(boolean gatherCssNames) {
1906 this.gatherCssNames = gatherCssNames;
1907 }
1908
1909 public void setStripTypes(Set<String> stripTypes) {
1910 this.stripTypes = stripTypes;
1911 }
1912
1913 public void setStripNameSuffixes(Set<String> stripNameSuffixes) {
1914 this.stripNameSuffixes = stripNameSuffixes;
1915 }
1916
1917 public void setStripNamePrefixes(Set<String> stripNamePrefixes) {
1918 this.stripNamePrefixes = stripNamePrefixes;
1919 }
1920
1921 public void setStripTypePrefixes(Set<String> stripTypePrefixes) {
1922 this.stripTypePrefixes = stripTypePrefixes;
1923 }
1924
1925 public void setCustomPasses(Multimap<CustomPassExecutionTime, CompilerPass> customPasses) {
1926 this.customPasses = customPasses;
1927 }
1928
1929 public void setMarkNoSideEffectCalls(boolean markNoSideEffectCalls) {
1930 this.markNoSideEffectCalls = markNoSideEffectCalls;
1931 }
1932
1933 public void setDefineReplacements(Map<String, Object> defineReplacements) {
1934 this.defineReplacements = defineReplacements;
1935 }
1936
1937 public void setTweakReplacements(Map<String, Object> tweakReplacements) {
1938 this.tweakReplacements = tweakReplacements;
1939 }
1940
1941 public void setMoveFunctionDeclarations(boolean moveFunctionDeclarations) {
1942 this.moveFunctionDeclarations = moveFunctionDeclarations;
1943 }
1944
1945 public void setInstrumentationTemplate(String instrumentationTemplate) {
1946 this.instrumentationTemplate = instrumentationTemplate;
1947 }
1948
1949 public void setRecordFunctionInformation(boolean recordFunctionInformation) {
1950 this.recordFunctionInformation = recordFunctionInformation;
1951 }
1952
1953 public void setCssRenamingMap(CssRenamingMap cssRenamingMap) {
1954 this.cssRenamingMap = cssRenamingMap;
1955 }
1956
1957 public void setCssRenamingWhitelist(Set<String> whitelist) {
1958 this.cssRenamingWhitelist = whitelist;
1959 }
1960
1961 public void setReplaceStringsFunctionDescriptions(List<String> replaceStringsFunctionDescriptions) {
1962 this.replaceStringsFunctionDescriptions = replaceStringsFunctionDescriptions;
1963 }
1964
1965 public void setReplaceStringsPlaceholderToken(String replaceStringsPlaceholderToken) {
1966 this.replaceStringsPlaceholderToken = replaceStringsPlaceholderToken;
1967 }
1968
1969 public void setReplaceStringsReservedStrings(Set<String> replaceStringsReservedStrings) {
1970 this.replaceStringsReservedStrings = replaceStringsReservedStrings;
1971 }
1972
1973 public void setReplaceStringsInputMap(VariableMap serializedMap) {
1974 this.replaceStringsInputMap = serializedMap;
1975 }
1976
1977 public void setPrettyPrint(boolean prettyPrint) {
1978 this.prettyPrint = prettyPrint;
1979 }
1980
1981 public void setLineBreak(boolean lineBreak) {
1982 this.lineBreak = lineBreak;
1983 }
1984
1985 public void setPreferLineBreakAtEndOfFile(boolean lineBreakAtEnd) {
1986 this.preferLineBreakAtEndOfFile = lineBreakAtEnd;
1987 }
1988
1989 public void setPrintInputDelimiter(boolean printInputDelimiter) {
1990 this.printInputDelimiter = printInputDelimiter;
1991 }
1992
1993 public void setInputDelimiter(String inputDelimiter) {
1994 this.inputDelimiter = inputDelimiter;
1995 }
1996
1997 public void setTracer(TracerMode tracer) {
1998 this.tracer = tracer;
1999 }
2000
2001 public void setErrorFormat(ErrorFormat errorFormat) {
2002 this.errorFormat = errorFormat;
2003 }
2004
2005 public void setWarningsGuard(ComposeWarningsGuard warningsGuard) {
2006 this.warningsGuard = warningsGuard;
2007 }
2008
2009 public void setLineLengthThreshold(int lineLengthThreshold) {
2010 this.lineLengthThreshold = lineLengthThreshold;
2011 }
2012
2013 public void setExternExports(boolean externExports) {
2014 this.externExports = externExports;
2015 }
2016
2017 public void setExternExportsPath(String externExportsPath) {
2018 this.externExportsPath = externExportsPath;
2019 }
2020
2021 public void setSourceMapOutputPath(String sourceMapOutputPath) {
2022 this.sourceMapOutputPath = sourceMapOutputPath;
2023 }
2024
2025 public void setSourceMapDetailLevel(SourceMap.DetailLevel sourceMapDetailLevel) {
2026 this.sourceMapDetailLevel = sourceMapDetailLevel;
2027 }
2028
2029 public void setSourceMapFormat(SourceMap.Format sourceMapFormat) {
2030 this.sourceMapFormat = sourceMapFormat;
2031 }
2032
2033 public void setSourceMapLocationMappings(List<SourceMap.LocationMapping> sourceMapLocationMappings) {
2034 this.sourceMapLocationMappings = sourceMapLocationMappings;
2035 }
2036
2037 /**
2038 * Activates transformation of AMD to CommonJS modules.
2039 */
2040 public void setTransformAMDToCJSModules(boolean transformAMDToCJSModules) {
2041 this.transformAMDToCJSModules = transformAMDToCJSModules;
2042 }
2043
2044 /**
2045 * Rewrites CommonJS modules so that modules can be concatenated together,
2046 * by renaming all globals to avoid conflicting with other modules.
2047 */
2048 public void setProcessCommonJSModules(boolean processCommonJSModules) {
2049 this.processCommonJSModules = processCommonJSModules;
2050 }
2051
2052 /**
2053 * Sets a path prefix for CommonJS modules.
2054 */
2055 public void setCommonJSModulePathPrefix(String commonJSModulePathPrefix) {
2056 this.commonJSModulePathPrefix = commonJSModulePathPrefix;
2057 }
2058
2059
2060 //////////////////////////////////////////////////////////////////////////////
2061 // Enums
2062
2063 /** When to do the extra sanity checks */
2064 public static enum LanguageMode {
2065 /**
2066 * Traditional JavaScript
2067 */
2068 ECMASCRIPT3,
2069
2070 /**
2071 * Shiny new JavaScript
2072 */
2073 ECMASCRIPT5,
2074
2075 /**
2076 * Nitpicky, shiny new JavaScript
2077 */
2078 ECMASCRIPT5_STRICT;
2079
2080 public static LanguageMode fromString(String value) {
2081 if (value.equals("ECMASCRIPT5_STRICT") ||
2082 value.equals("ES5_STRICT")) {
2083 return CompilerOptions.LanguageMode.ECMASCRIPT5_STRICT;
2084 } else if (value.equals("ECMASCRIPT5") ||
2085 value.equals("ES5")) {
2086 return CompilerOptions.LanguageMode.ECMASCRIPT5;
2087 } else if (value.equals("ECMASCRIPT3") ||
2088 value.equals("ES3")) {
2089 return CompilerOptions.LanguageMode.ECMASCRIPT3;
2090 }
2091 return null;
2092 }
2093 }
2094
2095 /** When to do the extra sanity checks */
2096 static enum DevMode {
2097 /**
2098 * Don't do any extra sanity checks.
2099 */
2100 OFF,
2101
2102 /**
2103 * After the initial parse
2104 */
2105 START,
2106
2107 /**
2108 * At the start and at the end of all optimizations.
2109 */
2110 START_AND_END,
2111
2112 /**
2113 * After every pass
2114 */
2115 EVERY_PASS
2116 }
2117
2118 public static enum TracerMode {
2119 ALL, // Collect all timing and size metrics.
2120 RAW_SIZE, // Collect all timing and size metrics, except gzipped size.
2121 TIMING_ONLY, // Collect timing metrics only.
2122 OFF; // Collect no timing and size metrics.
2123
2124 boolean isOn() {
2125 return this != OFF;
2126 }
2127 }
2128
2129 public static enum TweakProcessing {
2130 OFF, // Do not run the ProcessTweaks pass.
2131 CHECK, // Run the pass, but do not strip out the calls.
2132 STRIP; // Strip out all calls to goog.tweak.*.
2133
2134 public boolean isOn() {
2135 return this != OFF;
2136 }
2137
2138 public boolean shouldStrip() {
2139 return this == STRIP;
2140 }
2141 }
2142
2143 /**
2144 * A Role Specific Interface for JS Compiler that represents a data holder
2145 * object which is used to store goog.scope alias code changes to code made
2146 * during a compile. There is no guarantee that individual alias changes are
2147 * invoked in the order they occur during compilation, so implementations
2148 * should not assume any relevance to the order changes arrive.
2149 * <p>
2150 * Calls to the mutators are expected to resolve very quickly, so
2151 * implementations should not perform expensive operations in the mutator
2152 * methods.
2153 *
2154 * @author [email protected] (Tyler Goodwin)
2155 */
2156 public interface AliasTransformationHandler {
2157
2158 /**
2159 * Builds an AliasTransformation implementation and returns it to the
2160 * caller.
2161 * <p>
2162 * Callers are allowed to request multiple AliasTransformation instances for
2163 * the same file, though it is expected that the first and last char values
2164 * for multiple instances will not overlap.
2165 * <p>
2166 * This method is expected to have a side-effect of storing off the created
2167 * AliasTransformation, which guarantees that invokers of this interface
2168 * cannot leak AliasTransformation to this implementation that the
2169 * implementor did not create
2170 *
2171 * @param sourceFile the source file the aliases re contained in.
2172 * @param position the region of the source file associated with the
2173 * goog.scope call. The item of the SourcePosition is the returned
2174 * AliasTransformation
2175 */
2176 public AliasTransformation logAliasTransformation(
2177 String sourceFile, SourcePosition<AliasTransformation> position);
2178 }
2179
2180 /**
2181 * A Role Specific Interface for the JS Compiler to report aliases used to
2182 * change the code during a compile.
2183 * <p>
2184 * While aliases defined by goog.scope are expected to by only 1 per file, and
2185 * the only top-level structure in the file, this is not enforced.
2186 */
2187 public interface AliasTransformation {
2188
2189 /**
2190 * Adds an alias definition to the AliasTransformation instance.
2191 * <p>
2192 * Last definition for a given alias is kept if an alias is inserted
2193 * multiple times (since this is generally the behavior in JavaScript code).
2194 *
2195 * @param alias the name of the alias.
2196 * @param definition the definition of the alias.
2197 */
2198 void addAlias(String alias, String definition);
2199 }
2200
2201 /**
2202 * A Null implementation of the CodeChanges interface which performs all
2203 * operations as a No-Op
2204 */
2205 static final AliasTransformationHandler NULL_ALIAS_TRANSFORMATION_HANDLER =
2206 new NullAliasTransformationHandler();
2207
2208 private static class NullAliasTransformationHandler
2209 implements AliasTransformationHandler, Serializable {
2210 private static final long serialVersionUID = 0L;
2211
2212 private static final AliasTransformation NULL_ALIAS_TRANSFORMATION =
2213 new NullAliasTransformation();
2214
2215 @Override
2216 public AliasTransformation logAliasTransformation(
2217 String sourceFile, SourcePosition<AliasTransformation> position) {
2218 position.setItem(NULL_ALIAS_TRANSFORMATION);
2219 return NULL_ALIAS_TRANSFORMATION;
2220 }
2221
2222 private static class NullAliasTransformation
2223 implements AliasTransformation, Serializable {
2224 private static final long serialVersionUID = 0L;
2225
2226 @Override
2227 public void addAlias(String alias, String definition) {
2228 }
2229 }
2230 }
2231 }