com.google.javascript.jscomp.Compiler Java Examples

The following examples show how to use com.google.javascript.jscomp.Compiler. 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: JavaScriptResource.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
public JavaScriptResource(final String resourceName,
                          final ImmutableMap<String, Object> scriptConstants,
                          final boolean debugMode) throws IOException {
    this.resourceName = Objects.requireNonNull(resourceName);
    this.scriptConstants = Objects.requireNonNull(scriptConstants);
    logger.debug("Compiling JavaScript resource: {}", resourceName);
    final Compiler compiler;
    try (final InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName)) {
        compiler = compile(resourceName, is, scriptConstants, debugMode);
    }
    logger.info("Pre-compiled JavaScript source: {}", resourceName);
    final Result result = compiler.getResult();
    if (!result.success || !result.warnings.isEmpty()) {
        throw new IllegalArgumentException("Javascript resource contains warnings and/or errors: " + resourceName);
    }
    final byte[] entityBytes = compiler.toSource().getBytes(StandardCharsets.UTF_8);
    entityBody = new GzippableHttpBody(ByteBuffer.wrap(entityBytes), generateETag(entityBytes));
}
 
Example #2
Source File: CompileTask.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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 #3
Source File: GoogleClosureOutputProcessor.java    From spring-soy-view with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final Reader reader, final Writer writer) throws IOException {
    final String originalJsSourceCode = IOUtils.toString(reader);
    try {
        Compiler.setLoggingLevel(Level.SEVERE);
        final Compiler compiler = new Compiler();
        final CompilerOptions compilerOptions = newCompilerOptions();
        compilationLevel.setOptionsForCompilationLevel(compilerOptions);
        //make it play nice with GAE
        compiler.disableThreads();
        compiler.initOptions(compilerOptions);

        final SourceFile input = SourceFile.fromInputStream("dummy.js", new ByteArrayInputStream(originalJsSourceCode.getBytes(getEncoding())));
        final Result result = compiler.compile(Lists.<SourceFile>newArrayList(), Lists.newArrayList(input), compilerOptions);

        logWarningsAndErrors(result);

        boolean origFallback = false;
        if (result.success) {
            final String minifiedJsSourceCode = compiler.toSource();
            if (StringUtils.isEmpty(minifiedJsSourceCode)) {
                origFallback = true;
            } else {
                writer.write(minifiedJsSourceCode);
            }
        } else {
            origFallback = true;
        }
        if (origFallback) {
            writer.write(originalJsSourceCode);
        }
    } finally {
        reader.close();
        writer.close();
    }
}
 
Example #4
Source File: NgClosureRunner.java    From ng-closure-runner with MIT License 5 votes vote down vote up
@Override
protected Compiler createCompiler() {
  // Always use the same compiler.
  if (cachedCompiler != null) {
    return cachedCompiler;
  }
  cachedCompiler = super.createCompiler();
  return cachedCompiler;
}
 
Example #5
Source File: JavaScriptResource.java    From divolte-collector with Apache License 2.0 5 votes vote down vote up
private static Compiler compile(final String filename,
                                final InputStream javascript,
                                final ImmutableMap<String,Object> scriptConstants,
                                final boolean debugMode) throws IOException {
    final CompilerOptions options = new CompilerOptions();
    COMPILATION_LEVEL.setOptionsForCompilationLevel(options);
    COMPILATION_LEVEL.setTypeBasedOptimizationOptions(options);
    options.setEnvironment(CompilerOptions.Environment.BROWSER);
    options.setLanguageIn(ECMASCRIPT5_STRICT);
    options.setLanguageOut(ECMASCRIPT5_STRICT);
    WarningLevel.VERBOSE.setOptionsForWarningLevel(options);

    // Enable pseudo-compatible mode for debugging where the output is compiled but
    // can be related more easily to the original JavaScript source.
    if (debugMode) {
        options.setPrettyPrint(true);
        COMPILATION_LEVEL.setDebugOptionsForCompilationLevel(options);
    }

    options.setDefineReplacements(scriptConstants);

    final SourceFile source = SourceFile.fromInputStream(filename, javascript, StandardCharsets.UTF_8);
    final Compiler compiler = new Compiler();
    final ErrorManager errorManager = new SortingErrorManager(ImmutableSet.of(new Slf4jErrorReportGenerator(compiler)));
    compiler.setErrorManager(errorManager);
    // TODO: Use an explicit list of externs instead of the default browser set, to control compatibility.
    final List<SourceFile> externs = CommandLineRunner.getBuiltinExterns(options.getEnvironment());
    compiler.compile(externs, ImmutableList.of(source), options);
    return compiler;
}
 
Example #6
Source File: JsOptimizerUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
/**
	 * @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 #7
Source File: SourceMapTestCase.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
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 #8
Source File: JsonMLConversionTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void testJsonMLToAstConversion(Node astRoot, JsonML jsonmlRoot,
    String js) {
  Compiler compiler = new Compiler();
  JsonMLAst ast = new JsonMLAst(jsonmlRoot);
  Node resultAstRoot = ast.getAstRoot(compiler);

  String explanation = resultAstRoot.checkTreeEquals(astRoot);
  assertNull("JsonML -> AST converter returned incorect result for " + js
     + "\n" + explanation, explanation);
}
 
Example #9
Source File: CompileTask.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@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 #10
Source File: ClosureCompiler.java    From caja with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: GentsCodeGenerator.java    From clutz with MIT License 5 votes vote down vote up
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 #12
Source File: LinkCommentsForOneFile.java    From clutz with MIT License 5 votes vote down vote up
public LinkCommentsForOneFile(
    Compiler compiler, ImmutableList<Comment> comments, NodeComments nodeComments) {
  this.compiler = compiler;
  this.nodeComments = nodeComments;
  this.comments = comments;
  if (!comments.isEmpty()) {
    commentBuffer.add(comments.get(0));
  }
}
 
Example #13
Source File: TypeScriptGenerator.java    From clutz with MIT License 5 votes vote down vote up
TypeScriptGenerator(Options opts, ExperimentTracker experimentTracker) {
  this.opts = opts;
  this.experimentTracker = experimentTracker;
  this.compiler = new Compiler();
  compiler.disableThreads();
  setErrorStream(System.err);

  this.pathUtil = new PathUtil(opts.root, opts.absolutePathPrefix);
  this.nameUtil = new NameUtil(compiler);
}
 
Example #14
Source File: ClosureCompiler.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String compile(String code) {
	Compiler compiler = new Compiler();
	compiler.disableThreads();
	
	SourceFile extern = SourceFile.fromCode("externs.js","function alert(x) {}");
	SourceFile input = SourceFile.fromCode("input.js", code);
	
	compiler.compile(extern, input, options);
	return compiler.toSource();
}
 
Example #15
Source File: ClosureJavaScriptCompressor.java    From htmlcompressor with Apache License 2.0 4 votes vote down vote up
@Override
public String compress(String source) {
	
	StringWriter writer = new StringWriter();
	
	//prepare source
	List<JSSourceFile> input = new ArrayList<JSSourceFile>();
	input.add(JSSourceFile.fromCode("source.js", source));
	
	//prepare externs
	List<JSSourceFile> externsList = new ArrayList<JSSourceFile>();
	if(compilationLevel.equals(CompilationLevel.ADVANCED_OPTIMIZATIONS)) {
		//default externs
		if(!customExternsOnly) {
			try {
				externsList = getDefaultExterns();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//add user defined externs
		if(externs != null) {
			for(JSSourceFile extern : externs) {
				externsList.add(extern);
			}
		}
		//add empty externs
		if(externsList.size() == 0) {
			externsList.add(JSSourceFile.fromCode("externs.js", ""));
		}
	} else {
		//empty externs
		externsList.add(JSSourceFile.fromCode("externs.js", ""));
	}
	
	Compiler.setLoggingLevel(loggingLevel);
	
	Compiler compiler = new Compiler();
	compiler.disableThreads();
	
	compilationLevel.setOptionsForCompilationLevel(compilerOptions);
	warningLevel.setOptionsForWarningLevel(compilerOptions);
	
	Result result = compiler.compile(externsList, input, compilerOptions);
	
	if (result.success) {
		writer.write(compiler.toSource());
	} else {
		writer.write(source);
	}

	return writer.toString();

}
 
Example #16
Source File: SecureCompiler.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public SecureCompiler() {
  compiler = new Compiler();
  options = getSecureCompilerOptions();
}
 
Example #17
Source File: CompileEachLineOfProgramOutput.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public static Result compile(String program, int num) {
  SourceFile input = SourceFile.fromCode(""+num, program);
  Compiler compiler = new Compiler();
  Result result = compiler.compile(extern, input, options);
  return result;
}
 
Example #18
Source File: JsonMLConversionTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Override
public CompilerPass getProcessor(Compiler compiler) {
  return null; // unused
}
 
Example #19
Source File: CommentLinkingPass.java    From clutz with MIT License 4 votes vote down vote up
public CommentLinkingPass(Compiler compiler) {
  this.compiler = compiler;
  this.nodeComments = new NodeComments();
}
 
Example #20
Source File: AstCommentLinkingPass.java    From clutz with MIT License 4 votes vote down vote up
public AstCommentLinkingPass(Compiler compiler, SourceExtractor extractor) {
  this.compiler = compiler;
  this.nodeComments = new NodeComments();
  this.extractor = extractor;
}
 
Example #21
Source File: MinifyUtil.java    From minifierbeans with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example #22
Source File: MinerrPassTest.java    From ng-closure-runner with MIT License 4 votes vote down vote up
@Override
public CompilerPass getProcessor(Compiler compiler) {
  return new MinerrPass(compiler, new PrintStream(dummyOutput), subCode);
}
 
Example #23
Source File: ClosureJsInteropGenerator.java    From jsinterop-generator with Apache License 2.0 4 votes vote down vote up
public ClosureJsInteropGenerator(Options options) {
  this.options = options;
  this.compiler = new Compiler();
  this.problems = new Problems(options.isStrict());
}
 
Example #24
Source File: GenerationContext.java    From jsinterop-generator with Apache License 2.0 votes vote down vote up
public abstract Compiler getCompiler();