com.google.javascript.jscomp.JSError Java Examples

The following examples show how to use com.google.javascript.jscomp.JSError. 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: CollectModuleMetadata.java    From clutz with MIT License 6 votes vote down vote up
/** Registers a goog.provide namespace for future lookup. */
void registerProvidesModule(Node n, String file, String namespace) {
  FileModule module;
  if (fileToModule.containsKey(file)) {
    if (fileToModule.get(file).isGoogModule) {
      compiler.report(
          JSError.make(
              n,
              GentsErrorManager.GENTS_MODULE_PASS_ERROR,
              String.format("goog.provide cannot be used in the same file as goog.module.")));
      return;
    }
    module = fileToModule.get(file);
  } else {
    module = new FileModule(file, false);
  }
  module.jsNamespaces.add(namespace);
  module.registerNamespaceToGlobalScope(namespace);
}
 
Example #2
Source File: ModuleConversionPass.java    From clutz with MIT License 6 votes vote down vote up
/** Validate the module import assumptions */
private boolean validateImport() {
  if (!isDestructuringImport && fullLocalNames.size() != 1) {
    compiler.report(
        JSError.make(
            originalImportNode,
            GentsErrorManager.GENTS_MODULE_PASS_ERROR,
            String.format(
                "Non destructuring imports should have exactly one local name, got [%s]",
                String.join(", ", fullLocalNames))));
    return false;
  }

  if (this.module == null && !isAlreadyConverted()) {
    compiler.report(
        JSError.make(
            originalImportNode,
            GentsErrorManager.GENTS_MODULE_PASS_ERROR,
            String.format("Module %s does not exist.", requiredNamespace)));
    return false;
  }
  return true;
}
 
Example #3
Source File: SecureCompiler.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
Report generateReport(Result result) {
  // a report may be generated only after actual compilation is complete
  if (result == null) {
    return null;
  }

  ArrayList<JsonMLError> errors = Lists.newArrayList();
  for (JSError error : result.errors) {
    errors.add(JsonMLError.make(error, sourceAst));
  }

  ArrayList<JsonMLError> warnings = Lists.newArrayList();
  for (JSError warning : result.warnings) {
    warnings.add(JsonMLError.make(warning, sourceAst));
  }

  return new Report(
      errors.toArray(new JsonMLError[0]),
      warnings.toArray(new JsonMLError[0]));
}
 
Example #4
Source File: ClutzErrorManager.java    From clutz with MIT License 6 votes vote down vote up
@Override
public void report(CheckLevel level, JSError error) {
  // Ignore warnings in non-debug mode.
  if (!debug && level == CheckLevel.WARNING) return;

  if (reportClutzMissingTypes
      && error.getDescription().contains("Bad type annotation. Unknown type")) {
    // Prepend an error that hints at missing externs/dependencies.
    reportClutzMissingTypes = false;
    // Leave out the location on purpose, the specific places of missing types are reported from
    // the original message; without a location this error sorts first, so that it is seen first.
    this.report(CheckLevel.ERROR, JSError.make(DeclarationGenerator.CLUTZ_MISSING_TYPES));
    // Fall through, still report the actual error below.
  }
  super.report(level, error);
}
 
Example #5
Source File: TypeConversionPass.java    From clutz with MIT License 5 votes vote down vote up
/**
 * Attempts to move a method declaration into a class definition. This generates a new
 * MEMBER_FUNCTION_DEF Node while removing the old function node from the AST.
 */
private void moveMethodsIntoClasses(ClassMemberDeclaration declaration) {
  Node classMembers = declaration.classNode.getLastChild();
  String fieldName = declaration.memberName;

  // Detach nodes in order to move them around in the AST.
  declaration.exprRoot.detach();
  declaration.rhs.detach();

  Node memberFunc = IR.memberFunctionDef(fieldName, declaration.rhs);
  memberFunc.setStaticMember(declaration.isStatic);
  memberFunc.setJSDocInfo(declaration.jsDoc);
  if (declaration.classNode.getToken() == Token.INTERFACE) {
    Node body = declaration.rhs.getLastChild();
    Preconditions.checkState(body.isNormalBlock());
    if (body.hasChildren()) {
      compiler.report(
          JSError.make(
              declaration.rhs,
              GentsErrorManager.GENTS_CLASS_PASS_ERROR,
              String.format("Interface method %s should be empty.", declaration.memberName)));
    }
    declaration.rhs.replaceChild(body, new Node(Token.EMPTY));
  }

  // Append the new method to the class
  classMembers.addChildToBack(memberFunc);
  nodeComments.moveComment(declaration.exprRoot, memberFunc);
  compiler.reportChangeToEnclosingScope(memberFunc);
}
 
Example #6
Source File: MinerrPass.java    From ng-closure-runner with MIT License 5 votes vote down vote up
private String getExprString(Node ast) {
  try {
    return getExprStringR(ast);
  } catch (IllegalArgumentException e) {
    compiler.report(JSError.make(ast, UNSUPPORTED_STRING_EXPRESSION_ERROR));
  }
  return null;
}
 
Example #7
Source File: DepsGenerator.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void reportDuplicateProvide(String namespace, DependencyInfo firstDep,
    DependencyInfo secondDep) {
  if (firstDep == secondDep) {
    errorManager.report(CheckLevel.WARNING,
        JSError.make(firstDep.getName(), -1, -1,
            DUPE_PROVIDES_WARNING, namespace));
  } else {
    errorManager.report(CheckLevel.ERROR,
        JSError.make(secondDep.getName(), -1, -1,
            MULTIPLE_PROVIDES_ERROR, namespace, firstDep.getName()));
  }
}
 
Example #8
Source File: JsonMLError.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public static JsonMLError make(JSError error, JsonMLAst ast) {
  // try to find the corresponding JsonML element
  // it is stored as line number of the JSError
  int n = error.lineNumber;
  JsonML element = ast.getElementPreOrder(n);

  ErrorLevel level = error.getDefaultLevel() == CheckLevel.ERROR
      ? ErrorLevel.COMPILATION_ERROR
      : ErrorLevel.COMPILATION_WARNING;

  return new JsonMLError(error.getType(), error.sourceName, element, 0,
      level, error.description);
}
 
Example #9
Source File: Reader.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reports a new parser error to the compiler and terminates the job
 * if the error is fatal.
 * @param error JSError instance to be passed to the compiler
 * @param terminal if true, parsing is terminated by throwing exception
 */
private void report(JSError error, boolean terminal)
    throws JsonMLException {
  compiler.report(error);
  if (terminal) {
    throw new JsonMLException();
  }
}
 
Example #10
Source File: Reader.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void report(DiagnosticType type, JsonML element,
    String... arguments) throws JsonMLException {
  // nodeIndex is the number of the node in which the error occurred
  // we will store it in line number
  int lineno = nodeIndex;
  int charno = -1;

  report(JSError.make(sourceName, lineno, charno, type, arguments));
}
 
Example #11
Source File: AntErrorManager.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void println(CheckLevel level, JSError error) {
  switch (level) {
    case ERROR:
      this.task.log(error.format(level, this.formatter), Project.MSG_ERR);
      break;
    case WARNING:
      this.task.log(error.format(level, this.formatter), Project.MSG_WARN);
      break;
    case OFF:
      break;
  }
}
 
Example #12
Source File: GentsErrorManager.java    From clutz with MIT License 5 votes vote down vote up
@Override
public void report(CheckLevel level, JSError error) {
  // Ignore warnings in non-debug mode.
  if (!debug && level == CheckLevel.WARNING) {
    return;
  }
  super.report(level, error);
}
 
Example #13
Source File: CollectModuleMetadata.java    From clutz with MIT License 5 votes vote down vote up
/** Registers a goog.module namespace for future lookup. */
private void registerGoogModule(Node n, String file, String namespace) {
  if (fileToModule.containsKey(file)) {
    compiler.report(
        JSError.make(
            n,
            GentsErrorManager.GENTS_MODULE_PASS_ERROR,
            String.format(
                "goog.module files cannot contain other goog.module or goog.provides.")));
    return;
  }
  FileModule module = new FileModule(file, true);
  module.jsNamespaces.add(namespace);
  module.registerNamespaceToGlobalScope(namespace);
}
 
Example #14
Source File: TypeConversionPass.java    From clutz with MIT License 5 votes vote down vote up
private void addTypeToScope(Node n, String typeName) {
  if (types.containsKey(typeName)) {
    compiler.report(
        JSError.make(
            n,
            GentsErrorManager.GENTS_CLASS_PASS_ERROR,
            String.format("Type %s has been defined multiple times.", typeName)));
    return;
  }
  types.put(typeName, n);
}
 
Example #15
Source File: ClosureJsInteropGenerator.java    From jsinterop-generator with Apache License 2.0 5 votes vote down vote up
private void checkJavascriptCompilationResults(Result compilationResult) {
  for (JSError error : compilationResult.errors) {
    problems.error("Javascript compilation error: %s", error.getDescription());
  }

  problems.report();
}
 
Example #16
Source File: TypeConversionPass.java    From clutz with MIT License 4 votes vote down vote up
/**
 * Attempts to convert a ES5 superclass call into a ES6 super() call.
 *
 * <p>Examples:
 *
 * <pre>
 * B.call(this, args) -> super(args);
 * B.prototype.foo.call(this, args) ->super.foo(args);
 * A.base(this, 'constructor', args) -> super(args);
 * A.base(this, 'foo', args) -> super.foo(args);
 * </pre>
 *
 * <p>This returns without any modification if the node is not an superclass call statement.
 */
private void maybeReplaceSuperCall(Node callNode) {
  Preconditions.checkState(callNode.isCall());
  String callName = callNode.getFirstChild().getQualifiedName();

  // First validate that we are inside a constructor call that extends another class
  Node classNode = NodeUtil.getEnclosingClass(callNode);
  if (callName == null || classNode == null) {
    return;
  }

  String className = NodeUtil.getName(classNode);

  // Translate super constructor or super method calls as follows:
  // A.base(this, 'constructor', args) -> super(args);
  // A.base(this, 'foo', args) -> super.foo(args);
  if (callName.equals(className + ".base") && callNode.getSecondChild().isThis()) {
    // Super calls for root classes are not converted
    if (classNode.getSecondChild().isEmpty()) {
      compiler.report(
          JSError.make(
              callNode,
              GentsErrorManager.GENTS_CLASS_PASS_ERROR,
              String.format("Cannot call superclass in root class %s", className)));
      return;
    }
    String methodName = callNode.getChildAtIndex(2).getString();

    if ("constructor".equals(methodName)) {
      nodeComments.replaceWithComment(callNode.getFirstChild(), IR.superNode());
    } else {
      nodeComments.replaceWithComment(
          callNode.getFirstChild(), NodeUtil.newQName(compiler, "super." + methodName));
    }

    // Remove twice to get rid of "this" and the method name
    callNode.removeChild(callNode.getSecondChild());
    callNode.removeChild(callNode.getSecondChild());
    compiler.reportChangeToEnclosingScope(callNode);
    return;
  }

  String superClassName = classNode.getSecondChild().getQualifiedName();
  // B.call(this, args) -> super(args);
  if (callName.equals(superClassName + ".call") && callNode.getSecondChild().isThis()) {
    nodeComments.replaceWithComment(callNode.getFirstChild(), IR.superNode());

    callNode.removeChild(callNode.getSecondChild());
    compiler.reportChangeToEnclosingScope(callNode);
    return;
  }

  // B.prototype.foo.call(this, args) -> super.foo(args);
  if (callName.startsWith(superClassName + ".prototype.") && callName.endsWith(".call")) {
    if (callNode.getSecondChild().isThis()) {
      // Determine name of method being called
      Node nameNode = callNode.getFirstFirstChild();
      Node n = nameNode;
      while (!n.getLastChild().getString().equals("prototype")) {
        n = n.getFirstChild();
      }
      nameNode.detach();

      nodeComments.replaceWithComment(n, IR.superNode());
      nodeComments.replaceWithComment(callNode.getFirstChild(), nameNode);
      callNode.removeChild(callNode.getSecondChild());
      compiler.reportChangeToEnclosingScope(callNode);
      return;
    }
  }
}
 
Example #17
Source File: DepsGenerator.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void reportSameFile(String namespace, DependencyInfo depInfo) {
  errorManager.report(CheckLevel.WARNING,
      JSError.make(depInfo.getName(), -1, -1,
          SAME_FILE_WARNING, namespace));
}
 
Example #18
Source File: DepsGenerator.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void reportUndefinedNamespace(
    String namespace, DependencyInfo depInfo) {
  errorManager.report(CheckLevel.ERROR,
      JSError.make(depInfo.getName(), -1, -1,
          NEVER_PROVIDED_ERROR, namespace));
}
 
Example #19
Source File: TypeConversionPass.java    From clutz with MIT License 4 votes vote down vote up
/**
 * Attempts to remove an inheritance statement. ex. goog.inherits(base, super)
 *
 * <p>This returns without any modification if the node is not an inheritance statement. This
 * fails by reporting an error when the node is an invalid inheritance statement.
 */
private void maybeRemoveInherits(Node exprNode) {
  Preconditions.checkState(exprNode.isExprResult());
  if (exprNode.getFirstChild().isCall()) {
    Node callNode = exprNode.getFirstChild();
    // Remove goog.inherits calls
    if (!callNode.getFirstChild().matchesQualifiedName("goog.inherits")) {
      return;
    }
    String className = callNode.getSecondChild().getQualifiedName();
    String superClassName = callNode.getLastChild().getQualifiedName();

    // Check that class exists
    if (!types.containsKey(className)) {
      compiler.report(
          JSError.make(
              exprNode,
              GentsErrorManager.GENTS_CLASS_PASS_ERROR,
              String.format("Class %s could not be found.", className)));
      return;
    }

    // Check that superclass is consistent
    Node classNode = types.get(className);
    String storedSuperClassName = classNode.getSecondChild().getQualifiedName();
    if (classNode.getSecondChild().isEmpty() || !storedSuperClassName.equals(superClassName)) {
      compiler.report(
          JSError.make(
              exprNode,
              GentsErrorManager.GENTS_CLASS_PASS_ERROR,
              String.format("Invalid superclass for %s", className)));
      return;
    }

    compiler.reportChangeToEnclosingScope(exprNode);
    exprNode.detach();
  } else if (exprNode.getFirstChild().isAssign()) {
    Node assignNode = exprNode.getFirstChild();
    // Report error if trying to assign to prototype directly
    Node lhs = assignNode.getFirstChild();
    if (lhs.isGetProp() && "prototype".equals(lhs.getLastChild().getString())) {
      compiler.report(
          JSError.make(
              exprNode,
              GentsErrorManager.GENTS_CLASS_PASS_ERROR,
              String.format(
                  "Cannot directly assign to prototype for %s",
                  lhs.getFirstChild().getQualifiedName())));
    }
  }
}
 
Example #20
Source File: DepsGenerator.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void reportDuplicateRequire(
    String namespace, DependencyInfo depInfo) {
  errorManager.report(CheckLevel.WARNING,
      JSError.make(depInfo.getName(), -1, -1,
          DUPE_REQUIRE_WARNING, namespace));
}
 
Example #21
Source File: DepsGenerator.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void reportNoDepsInDepsFile(String filePath) {
  errorManager.report(CheckLevel.WARNING,
      JSError.make(filePath, -1, -1, NO_DEPS_WARNING));
}
 
Example #22
Source File: CompilerUtil.java    From js-dossier with Apache License 2.0 4 votes vote down vote up
private static void appendErrors(List<String> list, List<JSError> errors) {
  for (JSError error : errors) {
    list.add(String.format("%s %s:%d", error.description, error.sourceName, error.lineNumber));
  }
}
 
Example #23
Source File: Reader.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Reports a new parser error to the compiler and terminates the job.
 * @param error JSError instance to be passed to the compiler
 */
private void report(JSError error) throws JsonMLException {
  report(error, true);
}