use of com.google.javascript.jscomp.Compiler in project closure-compiler by google.
the class CompileTask method execute.
@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(options);
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) {
StringBuilder source = new StringBuilder(compiler.toSource());
if (this.outputWrapperFile != null) {
try {
this.outputWrapper = Files.asCharSource(this.outputWrapperFile, UTF_8).read();
} catch (Exception e) {
throw new BuildException("Invalid output_wrapper_file specified.");
}
}
if (this.outputWrapper != null) {
int pos = this.outputWrapper.indexOf(CommandLineRunner.OUTPUT_MARKER);
if (pos > -1) {
String prefix = this.outputWrapper.substring(0, pos);
source.insert(0, prefix);
// end of outputWrapper
int suffixStart = pos + CommandLineRunner.OUTPUT_MARKER.length();
String suffix = this.outputWrapper.substring(suffixStart);
source.append(suffix);
} else {
throw new BuildException("Invalid output_wrapper specified. " + "Missing '" + CommandLineRunner.OUTPUT_MARKER + "'.");
}
}
if (result.sourceMap != null) {
flushSourceMap(result.sourceMap);
}
writeResult(source.toString());
} else {
throw new BuildException("Compilation failed.");
}
} else {
log("None of the files changed. Compilation skipped.");
}
}
use of com.google.javascript.jscomp.Compiler in project closure-compiler by google.
the class ClosureIntegrationTest method testWeakSymbols_arentInlinedIntoStrongCode.
@Test
public void testWeakSymbols_arentInlinedIntoStrongCode() {
SourceFile extern = SourceFile.fromCode("extern.js", lines(//
"/** @fileoverview @externs */", "", "function alert(x) {}"));
SourceFile aa = SourceFile.fromCode("A.js", lines("goog.module('a.A');", "goog.module.declareLegacyNamespace();", "", "class A { };", "", "exports = A;"), SourceKind.WEAK);
SourceFile ab = SourceFile.fromCode("B.js", lines("goog.module('a.B');", "goog.module.declareLegacyNamespace();", "", "class B { };", "", "exports = B;"), SourceKind.STRONG);
SourceFile entryPoint = SourceFile.fromCode("C.js", lines(//
"goog.module('a.C');", "", "const A = goog.requireType('a.A');", "const B = goog.require('a.B');", "", "alert(new B());", // Note how `a` is declared by any strong legacy module rooted on "a" (`a.B`).
"alert(new a.A());"), SourceKind.STRONG);
CompilerOptions options = new CompilerOptions();
options.setEmitUseStrict(false);
options.setClosurePass(true);
options.setDependencyOptions(DependencyOptions.pruneForEntryPoints(ImmutableList.of(ModuleIdentifier.forClosure("a.C"))));
Compiler compiler = new Compiler();
compiler.compile(ImmutableList.of(extern), ImmutableList.of(entryPoint, aa, ab), options);
assertThat(compiler.toSource()).isEqualTo("var a={};" + "class module$contents$a$B_B{}" + "a.B=module$contents$a$B_B;" + "" + "var module$exports$a$C={};" + "alert(new module$contents$a$B_B);" + "alert(new a.A);");
}
use of com.google.javascript.jscomp.Compiler in project Bytecoder by mirkosertic.
the class BytecoderMavenMojo method execute.
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
File theBaseDirectory = new File(buldDirectory);
File theBytecoderDirectory = new File(theBaseDirectory, "bytecoder");
theBytecoderDirectory.mkdirs();
try {
ClassLoader theLoader = prepareClassLoader();
Class theTargetClass = theLoader.loadClass(mainClass);
CompileTarget theCompileTarget = new CompileTarget(theLoader, CompileTarget.BackendType.valueOf(backend));
File theBytecoderFileName = new File(theBytecoderDirectory, theCompileTarget.generatedFileName());
BytecodeMethodSignature theSignature = new BytecodeMethodSignature(BytecodePrimitiveTypeRef.VOID, new BytecodeTypeRef[] { new BytecodeArrayTypeRef(BytecodeObjectTypeRef.fromRuntimeClass(String.class), 1) });
CompileOptions theOptions = new CompileOptions(new Slf4JLogger(), debugOutput, KnownOptimizer.ALL);
CompileResult theCode = theCompileTarget.compileToJS(theOptions, theTargetClass, "main", theSignature);
try (PrintWriter theWriter = new PrintWriter(new FileWriter(theBytecoderFileName))) {
theWriter.println(theCode.getData());
}
if (optimizeWithGoogleClosure) {
Compiler theCompiler = new Compiler();
CompilerOptions theClosureOptions = new CompilerOptions();
theClosureOptions.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT5_STRICT);
theClosureOptions.setLanguageOut(CompilerOptions.LanguageMode.ECMASCRIPT5_STRICT);
CompilationLevel.valueOf(closureOptimizationLevel).setOptionsForCompilationLevel(theClosureOptions);
List<SourceFile> theSourceFiles = CommandLineRunner.getBuiltinExterns(CompilerOptions.Environment.BROWSER);
theSourceFiles.add(SourceFile.fromCode("bytecoder.js", (String) theCode.getData()));
theCompiler.compile(new ArrayList<>(), theSourceFiles, theClosureOptions);
String theClosureCode = theCompiler.toSource();
File theBytecoderClosureFileName = new File(theBytecoderDirectory, "bytecoder-closure.js");
try (PrintWriter theWriter = new PrintWriter(new FileWriter(theBytecoderClosureFileName))) {
theWriter.println(theClosureCode);
}
}
if (theCode instanceof WASMCompileResult) {
WASMCompileResult theWASMCompileResult = (WASMCompileResult) theCode;
int[] theWASM = wat2wasm(theWASMCompileResult);
File theBytecoderWASMFileName = new File(theBytecoderDirectory, "bytecoder.wasm");
try (FileOutputStream theFos = new FileOutputStream(theBytecoderWASMFileName)) {
for (int aTheWASM : theWASM) {
theFos.write(aTheWASM);
}
}
}
} catch (Exception e) {
throw new MojoExecutionException("Error running bytecoder", e);
}
}
use of com.google.javascript.jscomp.Compiler in project closure-compiler by google.
the class JsfileParser method parse.
/**
* Internal implementation to produce the {@link FileInfo} object.
*/
private static FileInfo parse(String code, String filename, @Nullable Reporter reporter) {
ErrorReporter errorReporter = new DelegatingReporter(reporter);
Compiler compiler = new Compiler();
compiler.init(ImmutableList.<SourceFile>of(), ImmutableList.<SourceFile>of(), new CompilerOptions());
Config config = ParserRunner.createConfig(// TODO(sdh): ES8 STRICT, with a non-strict fallback - then give warnings.
Config.LanguageMode.ECMASCRIPT8, Config.JsDocParsing.INCLUDE_DESCRIPTIONS_NO_WHITESPACE, Config.RunMode.KEEP_GOING, /* extraAnnotationNames */
ImmutableSet.<String>of(), /* parseInlineSourceMaps */
true, Config.StrictMode.SLOPPY);
SourceFile source = SourceFile.fromCode(filename, code);
FileInfo info = new FileInfo(errorReporter);
ParserRunner.ParseResult parsed = ParserRunner.parse(source, code, config, errorReporter);
parsed.ast.setInputId(new InputId(filename));
String version = parsed.features.version();
if (!version.equals("es3")) {
info.loadFlags.add(JsArray.of("lang", version));
}
for (Comment comment : parsed.comments) {
if (comment.type == Comment.Type.JSDOC) {
parseComment(comment, info);
}
}
NodeTraversal.traverseEs6(compiler, parsed.ast, new Traverser(info));
return info;
}
use of com.google.javascript.jscomp.Compiler in project closure-compiler by google.
the class GwtRunner method compile.
/**
* Public compiler call. Exposed in {@link #exportCompile}.
*/
public static ModuleOutput compile(Flags flags) {
String[] unhandled = updateFlags(flags, defaultFlags);
if (unhandled.length > 0) {
throw new RuntimeException("Unhandled flag: " + unhandled[0]);
}
List<SourceFile> jsCode = fromFileArray(flags.jsCode, "Input_");
ImmutableMap<String, SourceMapInput> sourceMaps = buildSourceMaps(flags.jsCode, "Input_");
CompilerOptions options = new CompilerOptions();
applyDefaultOptions(options);
applyOptionsFromFlags(options, flags);
options.setInputSourceMaps(sourceMaps);
disableUnsupportedOptions(options);
List<SourceFile> externs = fromFileArray(flags.externs, "Extern_");
externs.addAll(createExterns(options.getEnvironment()));
NodeErrorManager errorManager = new NodeErrorManager();
Compiler compiler = new Compiler(new NodePrintStream());
compiler.setErrorManager(errorManager);
compiler.compile(externs, jsCode, options);
ModuleOutput output = new ModuleOutput();
output.compiledCode = writeOutput(compiler, flags.outputWrapper);
output.errors = toNativeErrorArray(errorManager.errors);
output.warnings = toNativeErrorArray(errorManager.warnings);
if (flags.createSourceMap) {
StringBuilder b = new StringBuilder();
try {
compiler.getSourceMap().appendTo(b, "");
} catch (IOException e) {
// ignore
}
output.sourceMap = b.toString();
}
return output;
}
Aggregations