com.google.javascript.jscomp.CompilerOptions Java Examples
The following examples show how to use
com.google.javascript.jscomp.CompilerOptions.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 8 votes |
public CompileTask() { this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT3; this.warningLevel = WarningLevel.DEFAULT; this.debugOptions = false; this.compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS; this.customExternsOnly = false; this.manageDependencies = false; this.prettyPrint = false; this.printInputDelimiter = false; this.generateExports = false; this.replaceProperties = false; this.forceRecompile = false; this.replacePropertiesPrefix = "closure.define."; this.defineParams = Lists.newLinkedList(); this.externFileLists = Lists.newLinkedList(); this.sourceFileLists = Lists.newLinkedList(); this.sourcePaths = Lists.newLinkedList(); this.warnings = Lists.newLinkedList(); }
Example #2
Source File: DossierCompiler.java From js-dossier with Apache License 2.0 | 6 votes |
@Override public <T extends SourceFile> void initModules( List<T> externs, List<JSModule> modules, CompilerOptions options) { checkArgument(modules.size() == 1, "only expecting 1 module, but got %s", modules.size()); List<? extends SourceFile> externList = externs; if (!modulePaths.isEmpty()) { try { externList = concat(externs, nodeLibrary.getExternFiles()); JSModule module = modules.iterator().next(); nodeLibrary.getExternModules().forEach(module::add); } catch (IOException e) { throw new RuntimeException(e); } } super.initModules(externList, modules, options); }
Example #3
Source File: NgClosureRunner.java From ng-closure-runner with MIT License | 6 votes |
@Override protected CompilerOptions createOptions() { CompilerOptions options = super.createOptions(); if (minerrPass) { if (options.customPasses == null) { options.customPasses = ArrayListMultimap.create(); } try { options.customPasses.put(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, createMinerrPass()); } catch (IOException e) { System.err.println(e); System.exit(1); } } return options; }
Example #4
Source File: SecureCompiler.java From astor with GNU General Public License v2.0 | 6 votes |
/** * Returns compiler options which are safe for compilation of a cajoled * module. The set of options is similar to the one which is used by * CompilationLevel in simple mode. The main difference is that variable * renaming and closurePass options are turned off. */ private CompilerOptions getSecureCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.variableRenaming = VariableRenamingPolicy.OFF; options.setInlineVariables(Reach.LOCAL_ONLY); options.inlineLocalFunctions = true; options.checkGlobalThisLevel = CheckLevel.OFF; options.coalesceVariableNames = true; options.deadAssignmentElimination = true; options.collapseVariableDeclarations = true; options.convertToDottedProperties = true; options.labelRenaming = true; options.removeDeadCode = true; options.optimizeArgumentsArray = true; options.removeUnusedVars = false; options.removeUnusedLocalVars = true; return options; }
Example #5
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 6 votes |
/** * Converts project properties beginning with the replacement prefix * into Compiler {@code @define} replacements. * * @param options */ private void convertPropertiesMap(CompilerOptions options) { @SuppressWarnings("unchecked") Map<String, Object> props = getProject().getProperties(); for (Map.Entry<String, Object> entry : props.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.startsWith(replacePropertiesPrefix)) { key = key.substring(replacePropertiesPrefix.length()); if (!setDefine(options, key, value)) { log("Unexpected property value for key=" + key + "; value=" + value); } } } }
Example #6
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 5 votes |
@Override public void execute() { if (this.outputFile == null) { throw new BuildException("outputFile attribute must be set"); } Compiler.setLoggingLevel(Level.OFF); CompilerOptions options = createCompilerOptions(); Compiler compiler = createCompiler(options); List<SourceFile> externs = findExternFiles(); List<SourceFile> sources = findSourceFiles(); if (isStale() || forceRecompile) { log("Compiling " + sources.size() + " file(s) with " + externs.size() + " extern(s)"); Result result = compiler.compile(externs, sources, options); if (result.success) { writeResult(compiler.toSource()); } else { throw new BuildException("Compilation failed."); } } else { log("None of the files changed. Compilation skipped."); } }
Example #7
Source File: DossierCommandLineRunner.java From js-dossier with Apache License 2.0 | 5 votes |
@Inject DossierCommandLineRunner( @StrictMode boolean strictMode, @Stdout PrintStream stdout, @Stderr PrintStream stderr, @Input FileSystem inputFileSystem, @Input ImmutableSet<Path> sources, @Externs ImmutableSet<Path> externs, Provider<DossierCompiler> compilerProvider, Provider<CompilerOptions> optionsProvider) { super(new String[0], stdout, stderr); this.inputFileSystem = inputFileSystem; this.compilerProvider = compilerProvider; this.optionsProvider = optionsProvider; getCommandLineConfig() .setWarningGuards( CHECKS .stream() .map( c -> new HiddenFlagEntry<>( strictMode ? CheckLevel.ERROR : CheckLevel.WARNING, c)) .collect(toList())) .setCodingConvention(new ClosureCodingConvention()) .setMixedJsSources( sources .stream() .map(s -> new HiddenFlagEntry<>(JsSourceType.JS, s.toString())) .collect(toList())) .setExterns(externs.stream().map(Path::toString).collect(toList())); }
Example #8
Source File: JsOptimizerUtil.java From netty-cookbook with Apache License 2.0 | 5 votes |
/** * @param code * JavaScript source code to compile. * @return The compiled version of the code. */ public static String compile(String code) { // System.out.println("------------------------"); // System.out.println(code); // System.out.println("------------------------"); Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); // Advanced mode is used here, but additional options could be set, too. CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); // To get the complete set of externs, the logic in // CompilerRunner.getDefaultExterns() should be used here. SourceFile extern = SourceFile.fromCode("externs.js", ""); // The dummy input name "input.js" is used here so that any warnings or // errors will cite line numbers in terms of input.js. SourceFile input = SourceFile.fromCode("input.js", code); // compile() returns a Result, but it is not needed here. compiler.compile(extern, input, options); // The compiler is responsible for generating the compiled code; it is // not // accessible via the Result. return compiler.toSource(); }
Example #9
Source File: SourceMapTestCase.java From astor with GNU General Public License v2.0 | 5 votes |
protected RunResult compile( String js1, String fileName1, String js2, String fileName2) { Compiler compiler = new Compiler(); CompilerOptions options = getCompilerOptions(); // Turn on IDE mode to get rid of optimizations. options.ideMode = true; List<SourceFile> inputs = ImmutableList.of(SourceFile.fromCode(fileName1, js1)); if (js2 != null && fileName2 != null) { inputs = ImmutableList.of( SourceFile.fromCode(fileName1, js1), SourceFile.fromCode(fileName2, js2)); } Result result = compiler.compile(EXTERNS, inputs, options); assertTrue("compilation failed", result.success); String source = compiler.toSource(); StringBuilder sb = new StringBuilder(); try { result.sourceMap.validate(true); result.sourceMap.appendTo(sb, "testcode"); } catch (IOException e) { throw new RuntimeException("unexpected exception", e); } RunResult rr = new RunResult(); rr.generatedSource = source; rr.sourceMap = result.sourceMap; rr.sourceMapFileContent = sb.toString(); return rr; }
Example #10
Source File: SourceMapTestCase.java From astor with GNU General Public License v2.0 | 5 votes |
protected CompilerOptions getCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.sourceMapOutputPath = "testcode_source_map.out"; options.sourceMapFormat = getSourceMapFormat(); options.sourceMapDetailLevel = detailLevel; return options; }
Example #11
Source File: CheckDebuggerStatementTest.java From astor with GNU General Public License v2.0 | 5 votes |
@Override protected CompilerOptions getOptions() { CompilerOptions options = super.getOptions(); if (checkLevel != null) { options.setWarningLevel( DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT, checkLevel); } return options; }
Example #12
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 5 votes |
private Compiler createCompiler(CompilerOptions options) { Compiler compiler = new Compiler(); MessageFormatter formatter = options.errorFormat.toFormatter(compiler, false); AntErrorManager errorManager = new AntErrorManager(formatter, this); compiler.setErrorManager(errorManager); return compiler; }
Example #13
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Maps Ant-style values (e.g., from Properties) into expected * Closure {@code @define} literals * * @return True if the {@code @define} replacement succeeded, false if * the variable's value could not be mapped properly. */ private boolean setDefine(CompilerOptions options, String key, Object value) { boolean success = false; if (value instanceof String) { final boolean isTrue = "true".equals(value); final boolean isFalse = "false".equals(value); if (isTrue || isFalse) { options.setDefineToBooleanLiteral(key, isTrue); } else { try { double dblTemp = Double.parseDouble((String) value); options.setDefineToDoubleLiteral(key, dblTemp); } catch (NumberFormatException nfe) { // Not a number, assume string options.setDefineToStringLiteral(key, (String) value); } } success = true; } else if (value instanceof Boolean) { options.setDefineToBooleanLiteral(key, (Boolean) value); success = true; } else if (value instanceof Integer) { options.setDefineToNumberLiteral(key, (Integer) value); success = true; } else if (value instanceof Double) { options.setDefineToDoubleLiteral(key, (Double) value); success = true; } return success; }
Example #14
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Converts {@code <define/>} nested elements into Compiler {@code @define} * replacements. Note: unlike project properties, {@code <define/>} elements * do not need to be named starting with the replacement prefix. */ private void convertDefineParameters(CompilerOptions options) { for (Parameter p : defineParams) { String key = p.getName(); Object value = p.getValue(); if (!setDefine(options, key, value)) { log("Unexpected @define value for name=" + key + "; value=" + value); } } }
Example #15
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 5 votes |
private CompilerOptions createCompilerOptions() { CompilerOptions options = new CompilerOptions(); this.compilationLevel.setOptionsForCompilationLevel(options); if (this.debugOptions) { this.compilationLevel.setDebugOptionsForCompilationLevel(options); } options.prettyPrint = this.prettyPrint; options.printInputDelimiter = this.printInputDelimiter; options.generateExports = this.generateExports; options.setLanguageIn(this.languageIn); this.warningLevel.setOptionsForWarningLevel(options); options.setManageClosureDependencies(manageDependencies); if (replaceProperties) { convertPropertiesMap(options); } convertDefineParameters(options); for (Warning warning : warnings) { CheckLevel level = warning.getLevel(); String groupName = warning.getGroup(); DiagnosticGroup group = new DiagnosticGroups().forName(groupName); if (group == null) { throw new BuildException( "Unrecognized 'warning' option value (" + groupName + ")"); } options.setWarningLevel(group, level); } return options; }
Example #16
Source File: CompileTask.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Set the language to which input sources conform. * @param value The name of the language. * (ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT). */ public void setLanguageIn(String value) { if (value.equals("ECMASCRIPT5_STRICT") || value.equals("ES5_STRICT")) { this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT5_STRICT; } else if (value.equals("ECMASCRIPT5") || value.equals("ES5")) { this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT5; } else if (value.equals("ECMASCRIPT3") || value.equals("ES3")) { this.languageIn = CompilerOptions.LanguageMode.ECMASCRIPT3; } else { throw new BuildException( "Unrecognized 'languageIn' option value (" + value + ")"); } }
Example #17
Source File: ClosureCompiler.java From caja with Apache License 2.0 | 5 votes |
public static String build(Task task, List<File> inputs) { List<SourceFile> externs; try { externs = CommandLineRunner.getDefaultExterns(); } catch (IOException e) { throw new BuildException(e); } List<SourceFile> jsInputs = new ArrayList<SourceFile>(); for (File f : inputs) { jsInputs.add(SourceFile.fromFile(f)); } CompilerOptions options = new CompilerOptions(); CompilationLevel.ADVANCED_OPTIMIZATIONS .setOptionsForCompilationLevel(options); WarningLevel.VERBOSE.setOptionsForWarningLevel(options); for (DiagnosticGroup dg : diagnosticGroups) { options.setWarningLevel(dg, CheckLevel.ERROR); } options.setCodingConvention(new GoogleCodingConvention()); Compiler compiler = new Compiler(); MessageFormatter formatter = options.errorFormat.toFormatter(compiler, false); AntErrorManager errorManager = new AntErrorManager(formatter, task); compiler.setErrorManager(errorManager); Result r = compiler.compile(externs, jsInputs, options); if (!r.success) { return null; } String wrapped = "(function(){" + compiler.toSource() + "})();\n"; return wrapped; }
Example #18
Source File: OptionsTest.java From clutz with MIT License | 5 votes |
@Test public void testClosureEnvCustom() throws Exception { Options opts = new Options( new String[] { "my/thing/static/js/0-bootstrap.js", "--closure_env", "CUSTOM", }); assertThat(opts.closureEnv).isEqualTo(CompilerOptions.Environment.CUSTOM); assertThat(opts.getCompilerOptions().getEnvironment()) .isEqualTo(CompilerOptions.Environment.CUSTOM); }
Example #19
Source File: InitialParseRetainingCompiler.java From clutz with MIT License | 5 votes |
/** * Copied verbatim from com.google.javascript.jscomp.Compiler, except using getter methods instead * of private fields and running cloneParsedInputs() at the appropriate time. */ @Override public <T1 extends SourceFile, T2 extends SourceFile> Result compile( List<T1> externs, List<T2> inputs, CompilerOptions options) { // The compile method should only be called once. checkState(getRoot() == null); try { init(externs, inputs, options); if (!hasErrors()) { parseForCompilation(); cloneParsedInputs(); } if (!hasErrors()) { if (options.getInstrumentForCoverageOnly()) { // TODO(bradfordcsmith): The option to instrument for coverage only should belong to the // runner, not the compiler. instrumentForCoverage(); } else { stage1Passes(); if (!hasErrors()) { stage2Passes(); } } performPostCompilationTasks(); } } finally { generateReport(); } return getResult(); }
Example #20
Source File: GentsCodeGenerator.java From clutz with MIT License | 5 votes |
public GentsCodeGenerator( CodeConsumer consumer, CompilerOptions options, NodeComments astComments, NodeComments nodeComments, Map<String, String> externsMap, SourceExtractor extractor, Compiler compiler, Node root) { super(consumer, options); this.astComments = astComments; this.nodeComments = nodeComments; this.externsMap = externsMap; this.extractor = extractor; /* * Preference should be given to using a comment identified by the AstCommentLinkingPass * if that pass has associated the comment with any node in the AST. * * This is needed to support trailing comments because the CommentLinkingPass can * incorrectly assign a trailing comment to a node X that occurs earlier in the AST * from the node Y it should be associated with (and which the AstCommentLinkingPass has * associated it with). * * If precedence of comments is done on a per-node basis, then the comment will be * generated by node X before it could be correctly printed by Y. * * The set below records all of the comments identified by the AstCommentLinking * pass that are in the AST given by 'root'. * * Using this set, the comment will not be associated with node X because the * GentsCodeGenerator knows it was associated with another node (Y) by the * AstCommentLinkingPass. As such, the comment will be associated with node Y which * can process it as a trailing comment after X has been processed. */ this.astCommentsPresent = getAllCommentsWithin(astComments, compiler, root); }
Example #21
Source File: Options.java From clutz with MIT License | 5 votes |
CompilerOptions getCompilerOptions() { final CompilerOptions options = new CompilerOptions(); options.setClosurePass(true); // Turns off common warning messages, when PhaseOptimizer decides to skip some passes due to // unsupported code constructs. They are not very actionable to users and do not matter to // gents. Logger phaseLogger = Logger.getLogger("com.google.javascript.jscomp.PhaseOptimizer"); phaseLogger.setLevel(Level.OFF); options.setCheckGlobalNamesLevel(CheckLevel.ERROR); // Report duplicate definitions, e.g. for accidentally duplicated externs. options.setWarningLevel(DiagnosticGroups.DUPLICATE_VARS, CheckLevel.ERROR); options.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT_NEXT); // We have to emit _TYPED, as any other mode triggers optimizations // in the Closure code printer. Notably optimizations break typed // syntax for arrow functions, by removing the surrounding parens // emitting `foo(x:string => x)`, which is invalid. options.setLanguageOut(LanguageMode.ECMASCRIPT6_TYPED); // Do not transpile module declarations options.setWrapGoogModulesForWhitespaceOnly(false); // Stop escaping the characters "=&<>" options.setTrustedStrings(true); options.setPreferSingleQuotes(true); // Compiler passes must be disabled to disable down-transpilation to ES5. options.skipAllCompilerPasses(); // turns off optimizations. options.setChecksOnly(true); options.setPreserveDetailedSourceInfo(true); // Changing this to INCLUDE_DESCRIPTIONS_WITH_WHITESPACE, which feels more natural to the goals // of gents, makes no difference in golden test. Likely we ignore this info. options.setParseJsDocDocumentation(Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE); options.clearConformanceConfigs(); return options; }
Example #22
Source File: CompilerUtil.java From js-dossier with Apache License 2.0 | 5 votes |
@Inject public CompilerUtil( DossierCompiler compiler, TypeRegistry typeRegistry, CompilerOptions options) { this.compiler = compiler; this.typeRegistry = typeRegistry; this.options = options; }
Example #23
Source File: ClosureCompiler.java From AngularBeans with GNU Lesser General Public License v3.0 | 5 votes |
public ClosureCompiler() { //We have to ensure a safe concurrency as ModuleGenerator is session-scoped and //multiple sessions can generate the script at the same time. synchronized (lock) { this.options = new CompilerOptions(); CompilationLevel.WHITESPACE_ONLY.setOptionsForCompilationLevel(options); options.setVariableRenaming(VariableRenamingPolicy.OFF); options.setAngularPass(true); options.setTightenTypes(false); options.prettyPrint = false; } }
Example #24
Source File: ClosureJsInteropGenerator.java From jsinterop-generator with Apache License 2.0 | 5 votes |
private CompilerOptions createCompilerOptions() { CompilerOptions options = new CompilerOptions(); options.setLanguageOut(ECMASCRIPT5); options.setChecksOnly(true); options.setStrictModeInput(true); options.setCheckTypes(true); options.setPreserveDetailedSourceInfo(true); options.setWarningLevel(DiagnosticGroups.UNRECOGNIZED_TYPE_ERROR, CheckLevel.ERROR); return options; }
Example #25
Source File: CompilerUtil.java From js-dossier with Apache License 2.0 | 4 votes |
public CompilerOptions getOptions() { return options; }
Example #26
Source File: DossierCommandLineRunner.java From js-dossier with Apache License 2.0 | 4 votes |
@Override @SuppressWarnings("unchecked") protected CompilerOptions createOptions() { return optionsProvider.get(); }
Example #27
Source File: DossierCommandLineRunner.java From js-dossier with Apache License 2.0 | 4 votes |
@Override protected void addWhitelistWarningsGuard(CompilerOptions options, File whitelistFile) { options.addWarningsGuard(WhitelistWarningsGuard.fromFile(whitelistFile)); }
Example #28
Source File: CompilerModule.java From js-dossier with Apache License 2.0 | 4 votes |
@Provides CompilerOptions provideCompilerOptions( ProvidedSymbolPass providedSymbolPass, TypeCollectionPass typeCollectionPass, @Modules ImmutableSet<Path> modulePaths, Environment environment) { CompilerOptions options = new CompilerOptions(); switch (environment) { case BROWSER: options.setEnvironment(CompilerOptions.Environment.BROWSER); options.setModuleResolutionMode(ModuleLoader.ResolutionMode.BROWSER); break; case NODE: options.setEnvironment(CompilerOptions.Environment.CUSTOM); options.setModuleResolutionMode(ModuleLoader.ResolutionMode.NODE); break; default: throw new AssertionError("unexpected environment: " + environment); } options.setModuleRoots(ImmutableList.of()); options.setLanguageIn(LanguageMode.STABLE_IN); options.setLanguageOut(LanguageMode.STABLE_OUT); options.setCodingConvention(new ClosureCodingConvention()); CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options); CompilationLevel.ADVANCED_OPTIMIZATIONS.setTypeBasedOptimizationOptions(options); options.setChecksOnly(true); options.setContinueAfterErrors(true); options.setAllowHotswapReplaceScript(true); options.setPreserveDetailedSourceInfo(true); options.setParseJsDocDocumentation(Config.JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE); // For easier debugging. options.setPrettyPrint(true); options.addCustomPass(CustomPassExecutionTime.BEFORE_CHECKS, providedSymbolPass); options.addCustomPass(CustomPassExecutionTime.BEFORE_OPTIMIZATIONS, typeCollectionPass); return options; }
Example #29
Source File: ClosureCompiler.java From AngularBeans with GNU Lesser General Public License v3.0 | 4 votes |
public ClosureCompiler(CompilerOptions options) { this.options = options; }
Example #30
Source File: MinifyUtil.java From minifierbeans with Apache License 2.0 | 4 votes |
public String compressSelectedJavaScript(String inputFilename, String content, MinifyProperty minifyProperty) throws IOException { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); compiler.initOptions(options); options.setStrictModeInput(false); options.setEmitUseStrict(false); options.setTrustedStrings(true); CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options); List<SourceFile> inputs = new ArrayList<SourceFile>(); inputs.add(SourceFile.fromCode(inputFilename, content)); StringWriter outputWriter = new StringWriter(); compiler.compile(CommandLineRunner.getDefaultExterns(), inputs, options); outputWriter.flush(); return compiler.toSource(); }