Esempio n. 1
0
 private Compiler createCompiler(
     List<SourceFile> inputs, List<SourceFile> externs, CompilerOptions compilerOptions) {
   Compiler compiler = new Compiler();
   compiler.disableThreads();
   compiler.compile(externs, inputs, compilerOptions);
   return compiler;
 }
Esempio n. 2
0
  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;

    JSSourceFile[] inputs = {JSSourceFile.fromCode(fileName1, js1)};

    if (js2 != null && fileName2 != null) {
      JSSourceFile[] multiple = {
        JSSourceFile.fromCode(fileName1, js1), JSSourceFile.fromCode(fileName2, js2)
      };
      inputs = multiple;
    }

    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;
  }
Esempio n. 3
0
  /** core method */
  private void writeJsTo(Writer writer) throws IOException {
    Compiler compiler;
    CompilerOptions options;
    List<SourceFile> externals;
    List<SourceFile> sources;
    Result result;
    boolean first;
    int i;
    Node node;

    compiler = new Compiler(new LoggerErrorManager());
    options = new CompilerOptions();
    options.setOutputCharset(Engine.ENCODING);
    sources = new ArrayList<>();
    externals = new ArrayList<>();
    for (i = 0; i < nodes.size(); i++) {
      node = nodes.get(i);
      sources.add(
          SourceFile.fromCode(
              location(node) + /* to get unique names, which is checked by the compiler: */ "_" + i,
              readString(node)));
    }
    result = compiler.compile(externals, sources, options);
    if (!result.success) {
      if (result.errors.length < 1) {
        throw new IllegalStateException();
      }
      throw new IOException(
          result.errors[0].sourceName
              + ":"
              + result.errors[0].lineNumber
              + ":"
              + result.errors[0].description);
    }
    if (overallMinimize) {
      writer.write(compiler.toSource());
    } else {
      first = true;
      for (SourceFile source : sources) {
        if (first) {
          first = false;
        } else {
          writer.write(LF);
        }
        if (!overallMinimize) {
          writer.write(type.comment(source.getName()));
        }
        writer.write(source.getCode());
      }
    }
  }
Esempio n. 4
0
  /**
   * For now, this method is private so that the client does not get access to the Compiler that was
   * used.
   */
  private void compile(Config config, Compiler compiler, PlovrCompilerOptions options) {
    Preconditions.checkState(!hasResult(), "Compilation already occurred");
    this.compiler = compiler;
    for (SourceFile input : inputs) {
      String path = input.getOriginalPath();
      try {
        File file = new File(config.getConfigFile().getParentFile(), path);
        if (file.exists()) {
          fam.watch(file);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    if (modules == null) {
      this.result = compiler.compile(externs, inputs, options);
    } else {
      this.result = compiler.compileModules(externs, modules, options);
    }

    if (config.getTreatWarningsAsErrors() && result.warnings.length > 0) {
      // Combine the errors and warnings into a single array.
      Result originalResult = this.result;
      JSError[] errors = new JSError[originalResult.errors.length + originalResult.warnings.length];
      System.arraycopy(originalResult.errors, 0, errors, 0, originalResult.errors.length);
      System.arraycopy(
          originalResult.warnings,
          0,
          errors,
          originalResult.errors.length,
          originalResult.warnings.length);

      this.result =
          new Result(
              errors,
              new JSError[0], /* warnings */
              originalResult.debugLog,
              originalResult.variableMap,
              originalResult.propertyMap,
              originalResult.namedAnonFunctionMap,
              originalResult.stringMap,
              originalResult.functionInformationMap,
              originalResult.sourceMap,
              originalResult.externExport,
              originalResult.cssNames,
              originalResult.idGeneratorMap);
    }
  }
 private String compile(HtmlLibrary library, ClosureOptimizationLevel opt, InputStream js)
     throws IOException {
   CompilationLevel compilationLevel = opt.toCompilationLevel();
   if (null == compilationLevel) {
     // return original input
     return IOUtils.toString(js);
   }
   SourceFile input = SourceFile.fromInputStream(getLibraryName(library), js);
   // TODO externs not supported, should avoid ADVANCED compilation
   SourceFile extern = SourceFile.fromCode("TODO", StringUtils.EMPTY);
   CompilerOptions options = new CompilerOptions();
   compilationLevel.setOptionsForCompilationLevel(options);
   // ES5 assumption to allow getters/setters
   options.setLanguageIn(CompilerOptions.LanguageMode.ECMASCRIPT5);
   Compiler compiler = new Compiler();
   compiler.compile(extern, input, options);
   return compiler.toSource();
 }
  /** @throws ExecutionException */
  public void run() throws ExecutionException {
    final Compiler compiler = new Compiler();
    final CompilerOptions options = new CompilerOptions();
    closureOptimization.setOptionsForCompilationLevel(options);

    final List<JSSourceFile> externs = Collections.emptyList();
    final List<JSSourceFile> sources = new ArrayList<JSSourceFile>();
    if (closurePreScript != null) {
      getLogger().info("Include PreScript:");
      sources.add(JSSourceFile.fromCode("closurePreScript.js", closurePreScript));
    }
    getFiles(sources);
    if (closurePostScript != null) {
      getLogger().info("Include PostScript:");
      sources.add(JSSourceFile.fromCode("closurePostScript.js", closurePostScript));
    }

    getLogger().info("Got " + sources.size() + " source files");
    final Result result = compiler.compile(externs, sources, options);
    if (!result.success) {
      throw new ExecutionException("Failed to compile scripts");
    }

    getLogger().info("Writing compiled js to " + closureTargetFile);
    try {
      FileUtils.forceMkdir(closureTargetFile.getParentFile());
      final FileWriter writer = new FileWriter(closureTargetFile);
      try {
        String preSource =
            closurePreScriptFile != null ? FileUtils.readFileToString(closurePreScriptFile) : "";
        String postSource =
            closurePostScriptFile != null ? FileUtils.readFileToString(closurePostScriptFile) : "";

        StringBuilder sb = new StringBuilder();
        sb.append(preSource).append(compiler.toSource()).append(postSource);
        writer.write(sb.toString());
      } finally {
        writer.close();
      }
    } catch (IOException e) {
      throw new ExecutionException("Failed to write target file: " + closureTargetFile, e);
    }
  }
Esempio n. 7
0
  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);

    JSSourceFile[] externs = findExternFiles();
    JSSourceFile[] sources = findSourceFiles();

    log("Compiling " + sources.length + " file(s) with " + externs.length + " extern(s)");

    Result result = compiler.compile(externs, sources, options);
    if (result.success) {
      writeResult(compiler.toSource());
    } else {
      throw new BuildException("Compilation failed.");
    }
  }
  /**
   * Minimize the output using google closure compiler.
   *
   * @param output The input file to minimize.
   * @throws IOException If something goes wrong.
   * @throws MojoFailureException If something goes wrong.
   */
  private void minimize(final File output) throws IOException, MojoFailureException {
    final CompilerOptions options = new CompilerOptions();
    options.setCodingConvention(new ClosureCodingConvention());
    options.setOutputCharset("UTF-8");
    options.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES, CheckLevel.WARNING);
    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

    Compiler.setLoggingLevel(Level.SEVERE);
    Compiler compiler = new Compiler();
    compiler.disableThreads();
    compiler.initOptions(options);

    Result result =
        compiler.compile(
            Collections.<SourceFile>emptyList(),
            Arrays.asList(SourceFile.fromFile(output)),
            options);
    if (result.success) {
      FileUtils.fileWrite(output, compiler.toSource());
    } else {
      JSError[] errors = result.errors;
      throw new MojoFailureException(errors[0].toString());
    }
  }
  @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) {
        StringBuilder source = new StringBuilder(compiler.toSource());

        if (this.outputWrapperFile != null) {
          try {
            this.outputWrapper = Files.toString(this.outputWrapperFile, UTF_8);
          } catch (Exception e) {
            throw new BuildException("Invalid output_wrapper_file specified.");
          }
        }

        if (this.outputWrapper != null) {
          int pos = -1;
          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);
          source.append(System.getProperty("line.separator"));
          source.append("//@ sourceMappingURL=" + sourceMapOutputFile.getName());
        }
        writeResult(source.toString());
      } else {
        throw new BuildException("Compilation failed.");
      }
    } else {
      log("None of the files changed. Compilation skipped.");
    }
  }