@Override
  protected CompilerOptions createOptions() {
    CompilerOptions options = new CompilerOptions();
    if (flags.processJqueryPrimitives) {
      options.setCodingConvention(new JqueryCodingConvention());
    } else {
      options.setCodingConvention(new ClosureCodingConvention());
    }

    options.setExtraAnnotationNames(flags.extraAnnotationName);

    CompilationLevel level = flags.compilationLevel;
    level.setOptionsForCompilationLevel(options);

    if (flags.debug) {
      level.setDebugOptionsForCompilationLevel(options);
    }

    if (flags.useTypesForOptimization) {
      level.setTypeBasedOptimizationOptions(options);
    }

    if (flags.generateExports) {
      options.setGenerateExports(flags.generateExports);
    }

    WarningLevel wLevel = flags.warningLevel;
    wLevel.setOptionsForWarningLevel(options);
    for (FormattingOption formattingOption : flags.formatting) {
      formattingOption.applyToOptions(options);
    }

    options.closurePass = flags.processClosurePrimitives;

    options.jqueryPass =
        CompilationLevel.ADVANCED_OPTIMIZATIONS == level && flags.processJqueryPrimitives;

    options.angularPass = flags.angularPass;

    if (!flags.translationsFile.isEmpty()) {
      try {
        options.messageBundle =
            new XtbMessageBundle(
                new FileInputStream(flags.translationsFile), flags.translationsProject);
      } catch (IOException e) {
        throw new RuntimeException("Reading XTB file", e);
      }
    } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) {
      // In SIMPLE or WHITESPACE mode, if the user hasn't specified a
      // translations file, they might reasonably try to write their own
      // implementation of goog.getMsg that makes the substitution at
      // run-time.
      //
      // In ADVANCED mode, goog.getMsg is going to be renamed anyway,
      // so we might as well inline it.
      options.messageBundle = new EmptyMessageBundle();
    }

    return options;
  }
 @Override
 protected CompilerOptions getOptions() {
   CompilerOptions options = super.getOptions();
   options.setWarningLevel(DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.OFF);
   options.setCodingConvention(getCodingConvention());
   return options;
 }
 @Override
 protected CompilerOptions getOptions() {
   CompilerOptions options = super.getOptions();
   options.setWarningLevel(DiagnosticGroups.ACCESS_CONTROLS, CheckLevel.ERROR);
   options.setWarningLevel(DiagnosticGroups.CONSTANT_PROPERTY, CheckLevel.ERROR);
   return options;
 }
Пример #4
0
 private void applyToOptions(CompilerOptions options) {
   switch (this) {
     case PRETTY_PRINT:
       options.prettyPrint = true;
       break;
     case PRINT_INPUT_DELIMITER:
       options.printInputDelimiter = true;
       break;
     default:
       throw new RuntimeException("Unknown formatting option: " + this);
   }
 }
  /**
   * Gets the compiler options to use for this test. Use getProcessor to determine what passes
   * should be run.
   */
  protected CompilerOptions getOptions(CompilerOptions options) {
    options.setLanguageIn(acceptedLanguage);

    // This doesn't affect whether checkSymbols is run--it just affects
    // whether variable warnings are filtered.
    options.checkSymbols = true;

    options.setWarningLevel(DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.WARNING);
    options.setWarningLevel(DiagnosticGroups.INVALID_CASTS, CheckLevel.WARNING);
    options.setCodingConvention(getCodingConvention());
    return options;
  }
 private static LiveVariablesAnalysis computeLiveness(String src) {
   Compiler compiler = new Compiler();
   CompilerOptions options = new CompilerOptions();
   options.setCodingConvention(new GoogleCodingConvention());
   compiler.initOptions(options);
   src = "function _FUNCTION(param1, param2){" + src + "}";
   Node n = compiler.parseTestCode(src).removeFirstChild();
   Node script = new Node(Token.SCRIPT, n);
   assertEquals(0, compiler.getErrorCount());
   Scope scope = new SyntacticScopeCreator(compiler).createScope(n, new Scope(script, compiler));
   ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
   cfa.process(null, n);
   ControlFlowGraph<Node> cfg = cfa.getCfg();
   LiveVariablesAnalysis analysis = new LiveVariablesAnalysis(cfg, scope, compiler);
   analysis.analyze();
   return analysis;
 }
 private Node parse(String[] original) {
   String[] argStrings = args.toArray(new String[] {});
   CommandLineRunner runner = new CommandLineRunner(argStrings);
   Compiler compiler = runner.createCompiler();
   List<SourceFile> inputs = Lists.newArrayList();
   for (int i = 0; i < original.length; i++) {
     inputs.add(SourceFile.fromCode(getFilename(i), original[i]));
   }
   CompilerOptions options = new CompilerOptions();
   // ECMASCRIPT5 is the most forgiving.
   options.setLanguageIn(LanguageMode.ECMASCRIPT5);
   compiler.init(externs, inputs, options);
   Node all = compiler.parseInputs();
   Preconditions.checkState(compiler.getErrorCount() == 0);
   Preconditions.checkNotNull(all);
   Node n = all.getLastChild();
   return n;
 }
Пример #8
0
  private Iterable<String> _createOptions(
      List<? extends File> classPath,
      List<? extends File> sourcePath,
      File destination,
      List<? extends File> bootClassPath,
      String sourceVersion,
      boolean showWarnings) {
    if (bootClassPath == null) {
      bootClassPath = _defaultBootClassPath;
    }

    LinkedList<String> options = new LinkedList<String>();
    for (Map.Entry<String, String> e : CompilerOptions.getOptions(showWarnings).entrySet()) {
      options.add(e.getKey());
      if (e.getValue().length() > 0) options.add(e.getValue());
    }
    options.add("-g");

    if (classPath != null) {
      options.add("-classpath");
      options.add(IOUtil.pathToString(classPath));
    }
    if (sourcePath != null) {
      options.add("-sourcepath");
      options.add(IOUtil.pathToString(sourcePath));
    }
    if (destination != null) {
      options.add("-d");
      options.add(destination.getPath());
    }
    if (bootClassPath != null) {
      options.add("-bootclasspath");
      options.add(IOUtil.pathToString(bootClassPath));
    }
    if (sourceVersion != null) {
      options.add("-source");
      options.add(sourceVersion);
    }
    if (!showWarnings) {
      options.add("-nowarn");
    }

    // Bug fix: if "-target" is not present, Iterables in for-each loops cause compiler errors
    if (sourceVersion != null) {
      options.add("-target");
      options.add(sourceVersion);
    }
    /* The following line is commented out because it does not work for Java 8. */
    //    else { options.add("-target"); options.add("1.7"); }

    return options;
  }
  /**
   * Verifies that the compiler pass's JS output matches the expected output and (optionally) that
   * an expected warning is issued. Or, if an error is expected, this method just verifies that the
   * error is encountered.
   *
   * @param externs Externs inputs
   * @param js Inputs
   * @param expected Expected output, or null if an error is expected
   * @param error Expected error, or null if no error is expected
   * @param warning Expected warning, or null if no warning is expected
   * @param description The description of the expected warning, or null if no warning is expected
   *     or if the warning's description should not be examined
   */
  private void test(
      List<SourceFile> externs,
      List<SourceFile> js,
      String expected,
      DiagnosticType error,
      DiagnosticType warning,
      String description) {
    Compiler compiler = createCompiler();
    lastCompiler = compiler;

    CompilerOptions options = getOptions();

    options.setLanguageIn(acceptedLanguage);
    // Note that in this context, turning on the checkTypes option won't
    // actually cause the type check to run.
    options.checkTypes = parseTypeInfo;
    compiler.init(externs, js, options);

    BaseJSTypeTestCase.addNativeProperties(compiler.getTypeRegistry());

    test(compiler, maybeCreateArray(expected), error, warning, description);
  }
Пример #10
0
  @Override
  protected CompilerOptions createOptions() {
    CompilerOptions options = new CompilerOptions();
    options.setCodingConvention(new ClosureCodingConvention());
    CompilationLevel level = flags.compilation_level;
    level.setOptionsForCompilationLevel(options);
    if (flags.debug) {
      level.setDebugOptionsForCompilationLevel(options);
    }

    if (flags.generate_exports) {
      options.setGenerateExports(flags.generate_exports);
    }

    WarningLevel wLevel = flags.warning_level;
    wLevel.setOptionsForWarningLevel(options);
    for (FormattingOption formattingOption : flags.formatting) {
      formattingOption.applyToOptions(options);
    }

    options.closurePass = flags.process_closure_primitives;
    return options;
  }
Пример #11
0
 public void copyFrom(CompilerOptions other) {
   super.copyFrom(other);
   linkOptions.copyFrom(other);
   localWorkers = other.getLocalWorkers();
 }
  private final void parseAndTypeCheck(String externs, String js) {
    setUp();
    final CompilerOptions options = compiler.getOptions();
    options.setClosurePass(true);
    options.setNewTypeInference(true);
    options.setWarningLevel(DiagnosticGroups.NEW_CHECK_TYPES_ALL_CHECKS, CheckLevel.WARNING);
    compiler.init(
        ImmutableList.of(SourceFile.fromCode("[externs]", externs)),
        ImmutableList.of(SourceFile.fromCode("[testcode]", js)),
        options);

    Node externsRoot = IR.block();
    externsRoot.setIsSyntheticBlock(true);
    externsRoot.addChildToFront(compiler.getInput(new InputId("[externs]")).getAstRoot(compiler));
    Node astRoot = IR.block();
    astRoot.setIsSyntheticBlock(true);
    astRoot.addChildToFront(compiler.getInput(new InputId("[testcode]")).getAstRoot(compiler));

    assertEquals(
        "parsing error: " + Joiner.on(", ").join(compiler.getErrors()),
        0,
        compiler.getErrorCount());
    assertEquals(
        "parsing warning: " + Joiner.on(", ").join(compiler.getWarnings()),
        0,
        compiler.getWarningCount());

    // Create common parent of externs and ast; needed by Es6RewriteBlockScopedDeclaration.
    Node block = IR.block(externsRoot, astRoot);
    block.setIsSyntheticBlock(true);

    // Run ASTValidator
    (new AstValidator(compiler)).validateRoot(block);

    DeclaredGlobalExternsOnWindow rewriteExterns = new DeclaredGlobalExternsOnWindow(compiler);
    passes.add(makePassFactory("globalExternsOnWindow", rewriteExterns));
    ProcessClosurePrimitives closurePass =
        new ProcessClosurePrimitives(compiler, null, CheckLevel.ERROR, false);
    passes.add(makePassFactory("ProcessClosurePrimitives", closurePass));
    if (options.getLanguageIn() == CompilerOptions.LanguageMode.ECMASCRIPT6_TYPED) {
      passes.add(makePassFactory("convertEs6TypedToEs6", new Es6TypedToEs6Converter(compiler)));
    }
    if (options.getLanguageIn().isEs6OrHigher()) {
      passes.add(
          makePassFactory(
              "Es6RenameVariablesInParamLists", new Es6RenameVariablesInParamLists(compiler)));
      passes.add(
          makePassFactory(
              "Es6SplitVariableDeclarations", new Es6SplitVariableDeclarations(compiler)));
      passes.add(makePassFactory("es6ConvertSuper", new Es6ConvertSuper(compiler)));
      passes.add(makePassFactory("convertEs6", new Es6ToEs3Converter(compiler)));
      passes.add(
          makePassFactory(
              "Es6RewriteBlockScopedDeclaration", new Es6RewriteBlockScopedDeclaration(compiler)));
      passes.add(makePassFactory("rewriteGenerators", new Es6RewriteGenerators(compiler)));
      passes.add(makePassFactory("Es6RuntimeLibrary", new InjectEs6RuntimeLibrary(compiler)));
      passes.add(
          makePassFactory("Es6StaticInheritance", new Es6ToEs3ClassSideInheritance(compiler)));
    }
    passes.add(makePassFactory("GlobalTypeInfo", compiler.getSymbolTable()));
    passes.add(makePassFactory("NewTypeInference", new NewTypeInference(compiler)));

    PhaseOptimizer phaseopt = new PhaseOptimizer(compiler, null, null);
    phaseopt.consume(passes);
    phaseopt.process(externsRoot, astRoot);
  }
Пример #13
0
 /** Adds warning levels by name. */
 void setWarningLevel(CompilerOptions options, String name, CheckLevel level) {
   DiagnosticGroup group = forName(name);
   Preconditions.checkNotNull(group, "No warning class for name: %s", name);
   options.setWarningLevel(group, level);
 }