Search in sources :

Example 76 with Compiler

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.");
    }
}
Also used : Compiler(com.google.javascript.jscomp.Compiler) CompilerOptions(com.google.javascript.jscomp.CompilerOptions) BuildException(org.apache.tools.ant.BuildException) SourceFile(com.google.javascript.jscomp.SourceFile) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) Result(com.google.javascript.jscomp.Result)

Example 77 with Compiler

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);");
}
Also used : Compiler(com.google.javascript.jscomp.Compiler) CompilerOptions(com.google.javascript.jscomp.CompilerOptions) SourceFile(com.google.javascript.jscomp.SourceFile) Test(org.junit.Test)

Example 78 with Compiler

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);
    }
}
Also used : Compiler(com.google.javascript.jscomp.Compiler) BytecodeMethodSignature(de.mirkosertic.bytecoder.core.BytecodeMethodSignature) WASMCompileResult(de.mirkosertic.bytecoder.backend.wasm.WASMCompileResult) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileWriter(java.io.FileWriter) CompileOptions(de.mirkosertic.bytecoder.backend.CompileOptions) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) BytecodeArrayTypeRef(de.mirkosertic.bytecoder.core.BytecodeArrayTypeRef) FileOutputStream(java.io.FileOutputStream) CompileTarget(de.mirkosertic.bytecoder.backend.CompileTarget) CompilerOptions(com.google.javascript.jscomp.CompilerOptions) URLClassLoader(java.net.URLClassLoader) WASMCompileResult(de.mirkosertic.bytecoder.backend.wasm.WASMCompileResult) CompileResult(de.mirkosertic.bytecoder.backend.CompileResult) SourceFile(com.google.javascript.jscomp.SourceFile) SourceFile(com.google.javascript.jscomp.SourceFile) File(java.io.File) Slf4JLogger(de.mirkosertic.bytecoder.unittest.Slf4JLogger) PrintWriter(java.io.PrintWriter)

Example 79 with Compiler

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;
}
Also used : Compiler(com.google.javascript.jscomp.Compiler) Comment(com.google.javascript.jscomp.parsing.parser.trees.Comment) ParserRunner(com.google.javascript.jscomp.parsing.ParserRunner) Config(com.google.javascript.jscomp.parsing.Config) ErrorReporter(com.google.javascript.rhino.ErrorReporter) CompilerOptions(com.google.javascript.jscomp.CompilerOptions) InputId(com.google.javascript.rhino.InputId) SourceFile(com.google.javascript.jscomp.SourceFile)

Example 80 with Compiler

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;
}
Also used : Compiler(com.google.javascript.jscomp.Compiler) IOException(java.io.IOException) CompilerOptions(com.google.javascript.jscomp.CompilerOptions) SourceFile(com.google.javascript.jscomp.SourceFile) SourceMapInput(com.google.javascript.jscomp.SourceMapInput)

Aggregations

Compiler (com.google.javascript.jscomp.Compiler)172 Test (org.junit.Test)132 Node (com.google.javascript.rhino.Node)116 CompilerOptions (com.google.javascript.jscomp.CompilerOptions)50 SourceFile (com.google.javascript.jscomp.SourceFile)22 NodeSubject.assertNode (com.google.javascript.rhino.testing.NodeSubject.assertNode)16 NoninjectingCompiler (com.google.javascript.jscomp.testing.NoninjectingCompiler)9 TestExternsBuilder (com.google.javascript.jscomp.testing.TestExternsBuilder)8 Result (com.google.javascript.jscomp.Result)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 File (java.io.File)4 BlackHoleErrorManager (com.google.javascript.jscomp.BlackHoleErrorManager)3 JSError (com.google.javascript.jscomp.JSError)3 InputId (com.google.javascript.rhino.InputId)3 GwtIncompatible (com.google.common.annotations.GwtIncompatible)2 AbstractCompiler (com.google.javascript.jscomp.AbstractCompiler)2 CompilerInput (com.google.javascript.jscomp.CompilerInput)2 JSChunk (com.google.javascript.jscomp.JSChunk)2 JSModule (com.google.javascript.jscomp.JSModule)2