/**
  * Appends the text representation of the given modifier flags, followed by a single space. Used
  * for 3.0 modifiers and annotations.
  *
  * @param ext the list of modifier and annotation nodes (element type: <code>IExtendedModifiers
  *     </code>)
  */
 private void printModifiers(List ext) {
   for (Iterator it = ext.iterator(); it.hasNext(); ) {
     ASTNode p = (ASTNode) it.next();
     p.accept(this);
     this.fBuffer.append(" "); // $NON-NLS-1$
   }
 }
  public void collectOccurrenceMatches(
      IJavaScriptElement element, IDocument document, Collection resultingMatches) {
    HashMap lineToLineElement = new HashMap();

    for (Iterator iter = fResult.iterator(); iter.hasNext(); ) {
      ASTNode node = (ASTNode) iter.next();
      int startPosition = node.getStartPosition();
      int length = node.getLength();
      try {
        boolean isException = node == fSelectedName;
        int line = document.getLineOfOffset(startPosition);
        Integer lineInteger = new Integer(line);
        ExceptionOccurrencesGroupKey groupKey =
            (ExceptionOccurrencesGroupKey) lineToLineElement.get(lineInteger);
        if (groupKey == null) {
          IRegion region = document.getLineInformation(line);
          String lineContents = document.get(region.getOffset(), region.getLength()).trim();
          groupKey = new ExceptionOccurrencesGroupKey(element, line, lineContents, isException);
          lineToLineElement.put(lineInteger, groupKey);
        } else if (isException) {
          // the line with the target exception always has the exception icon:
          groupKey.setException(true);
        }
        Match match = new Match(groupKey, startPosition, length);
        resultingMatches.add(match);
      } catch (BadLocationException e) {
        // nothing
      }
    }
  }
 public String initialize(JavaScriptUnit root, ASTNode node) {
   fAST = root.getAST();
   if (!(node instanceof Name)) {
     return SearchMessages.ExceptionOccurrencesFinder_no_exception;
   }
   fSelectedName = ASTNodes.getTopMostName((Name) node);
   ASTNode parent = fSelectedName.getParent();
   FunctionDeclaration decl = resolveMethodDeclaration(parent);
   if (decl != null && methodThrowsException(decl, fSelectedName)) {
     fException = fSelectedName.resolveTypeBinding();
     fStart = decl.getBody();
   } else if (parent instanceof Type) {
     parent = parent.getParent();
     if (parent instanceof SingleVariableDeclaration
         && parent.getParent() instanceof CatchClause) {
       CatchClause catchClause = (CatchClause) parent.getParent();
       TryStatement tryStatement = (TryStatement) catchClause.getParent();
       if (tryStatement != null) {
         IVariableBinding var = catchClause.getException().resolveBinding();
         if (var != null && var.getType() != null) {
           fException = var.getType();
           fStart = tryStatement.getBody();
         }
       }
     }
   }
   if (fException == null || fStart == null)
     return SearchMessages.ExceptionOccurrencesFinder_no_exception;
   return null;
 }
  /*
  * @see ASTVisitor#visit(TagElement)

  */
  public boolean visit(TagElement node) {
    if (node.isNested()) {
      // nested tags are always enclosed in braces
      this.fBuffer.append("{"); // $NON-NLS-1$
    } else {
      // top-level tags always begin on a new line
      this.fBuffer.append("\n * "); // $NON-NLS-1$
    }
    boolean previousRequiresWhiteSpace = false;
    if (node.getTagName() != null) {
      this.fBuffer.append(node.getTagName());
      previousRequiresWhiteSpace = true;
    }
    boolean previousRequiresNewLine = false;
    for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
      ASTNode e = (ASTNode) it.next();
      // assume text elements include necessary leading and trailing whitespace
      // but Name, MemberRef, FunctionRef, and nested TagElement do not include white space
      boolean currentIncludesWhiteSpace = (e instanceof TextElement);
      if (previousRequiresNewLine && currentIncludesWhiteSpace) {
        this.fBuffer.append("\n * "); // $NON-NLS-1$
      }
      previousRequiresNewLine = currentIncludesWhiteSpace;
      // add space if required to separate
      if (previousRequiresWhiteSpace && !currentIncludesWhiteSpace) {
        this.fBuffer.append(" "); // $NON-NLS-1$
      }
      e.accept(this);
      previousRequiresWhiteSpace = !currentIncludesWhiteSpace && !(e instanceof TagElement);
    }
    if (node.isNested()) {
      this.fBuffer.append("}"); // $NON-NLS-1$
    }
    return false;
  }
    public void postVisit(ASTNode node) {
      // check that parent is && or ||
      if (!(node.getParent() instanceof InfixExpression)) return;

      // we want to add parenthesis around arithmetic operators and instanceof
      boolean needParenthesis = false;
      if (node instanceof InfixExpression) {
        InfixExpression expression = (InfixExpression) node;
        InfixExpression.Operator operator = expression.getOperator();

        InfixExpression parentExpression = (InfixExpression) node.getParent();
        InfixExpression.Operator parentOperator = parentExpression.getOperator();

        if (parentOperator == operator) return;

        needParenthesis =
            (operator == InfixExpression.Operator.LESS)
                || (operator == InfixExpression.Operator.GREATER)
                || (operator == InfixExpression.Operator.LESS_EQUALS)
                || (operator == InfixExpression.Operator.GREATER_EQUALS)
                || (operator == InfixExpression.Operator.EQUALS)
                || (operator == InfixExpression.Operator.NOT_EQUALS)
                || (operator == InfixExpression.Operator.CONDITIONAL_AND)
                || (operator == InfixExpression.Operator.CONDITIONAL_OR);
      }
      if (node instanceof InstanceofExpression) {
        needParenthesis = true;
      }
      if (!needParenthesis) {
        return;
      }
      fNodes.add(node);
    }
 /*
  * @see ASTVisitor#visit(Javadoc)
  */
 public boolean visit(JSdoc node) {
   this.fBuffer.append("/** "); // $NON-NLS-1$
   for (Iterator it = node.tags().iterator(); it.hasNext(); ) {
     ASTNode e = (ASTNode) it.next();
     e.accept(this);
   }
   this.fBuffer.append("\n */"); // $NON-NLS-1$
   return false;
 }
 // !! - like one in ExtractTempRefactoring
 private static boolean canReplace(IASTFragment fragment) {
   ASTNode node = fragment.getAssociatedNode();
   ASTNode parent = node.getParent();
   if (parent instanceof VariableDeclarationFragment) {
     VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
     if (node.equals(vdf.getName())) return false;
   }
   if (parent instanceof ExpressionStatement) return false;
   if (parent instanceof SwitchCase) return false;
   return true;
 }
 public List perform() {
   fStart.accept(this);
   if (fSelectedName != null) {
     fResult.add(fSelectedName);
   }
   return fResult;
 }
  /**
   * Adds the necessary imports for an AST node to the specified compilation unit.
   *
   * @param rewrite the compilation unit rewrite whose compilation unit's imports should be updated
   * @param node the AST node specifying the element for which imports should be added
   * @param typeImports the map of name nodes to strings (element type: Map <Name, String>).
   * @param staticImports the map of name nodes to strings (element type: Map <Name, String>).
   * @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
   * @param declarations <code>true</code> if method declarations are treated as abstract, <code>
   *     false</code> otherwise
   */
  public static void addImports(
      final CompilationUnitRewrite rewrite,
      final ASTNode node,
      final Map typeImports,
      final Map staticImports,
      final Collection excludeBindings,
      final boolean declarations) {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(node);
    Assert.isNotNull(typeImports);
    Assert.isNotNull(staticImports);
    final Set types = new HashSet();
    final Set members = new HashSet();
    final ImportReferencesCollector collector =
        new ImportReferencesCollector(
            rewrite.getCu().getJavaScriptProject(), null, types, members) {

          public final boolean visit(final Block block) {
            Assert.isNotNull(block);
            if (declarations && block.getParent() instanceof FunctionDeclaration) return false;
            return super.visit(block);
          }
        };
    node.accept(collector);
    final ImportRewrite rewriter = rewrite.getImportRewrite();
    final ImportRemover remover = rewrite.getImportRemover();
    Name name = null;
    IBinding binding = null;
    for (final Iterator iterator = types.iterator(); iterator.hasNext(); ) {
      name = (Name) iterator.next();
      binding = name.resolveBinding();
      if (binding instanceof ITypeBinding) {
        final ITypeBinding type = (ITypeBinding) binding;
        if (excludeBindings == null || !excludeBindings.contains(type)) {
          typeImports.put(name, rewriter.addImport(type));
          remover.registerAddedImport(type.getQualifiedName());
        }
      }
    }
    for (final Iterator iterator = members.iterator(); iterator.hasNext(); ) {
      name = (Name) iterator.next();
      binding = name.resolveBinding();
      if (binding instanceof IVariableBinding) {
        final IVariableBinding variable = (IVariableBinding) binding;
        final ITypeBinding declaring = variable.getDeclaringClass();
        if (declaring != null && (excludeBindings == null || !excludeBindings.contains(variable))) {
          staticImports.put(name, rewriter.addStaticImport(variable));
          remover.registerAddedStaticImport(declaring.getQualifiedName(), variable.getName(), true);
        }
      } else if (binding instanceof IFunctionBinding) {
        final IFunctionBinding method = (IFunctionBinding) binding;
        final ITypeBinding declaring = method.getDeclaringClass();
        if (declaring != null && (excludeBindings == null || !excludeBindings.contains(method))) {
          staticImports.put(name, rewriter.addStaticImport(method));
          remover.registerAddedStaticImport(declaring.getQualifiedName(), method.getName(), false);
        }
      }
    }
  }
示例#10
0
 /**
  * Find all nodes connected to the given binding. e.g. Declaration of a field and all references.
  * For types this includes also the constructor declaration, for methods also overridden methods
  * or methods overriding (if existing in the same AST)
  *
  * @param root The root of the AST tree to search
  * @param binding The binding of the searched nodes
  * @return Return
  */
 public static SimpleName[] findByBinding(ASTNode root, IBinding binding) {
   ArrayList<SimpleName> res = new ArrayList<SimpleName>();
   if (root != null) {
     BindingFinder nodeFinder = new BindingFinder(binding, res);
     root.accept(nodeFinder);
   }
   return res.toArray(new SimpleName[res.size()]);
 }
  public static IFix createRemoveUnnecessaryParenthesisFix(
      JavaScriptUnit compilationUnit, ASTNode[] nodes) {
    // check sub-expressions in fully covered nodes
    final ArrayList changedNodes = new ArrayList();
    for (int i = 0; i < nodes.length; i++) {
      ASTNode covered = nodes[i];
      if (covered instanceof ParenthesizedExpression || covered instanceof InfixExpression)
        covered.accept(new UnnecessaryParenthesisVisitor(changedNodes));
    }
    if (changedNodes.isEmpty()) return null;

    HashSet expressions = new HashSet(changedNodes);
    RemoveParenthesisOperation op = new RemoveParenthesisOperation(expressions);
    return new ExpressionsFix(
        FixMessages.ExpressionsFix_removeUnnecessaryParenthesis_description,
        compilationUnit,
        new IFixRewriteOperation[] {op});
  }
  public static IFix createAddParanoidalParenthesisFix(
      JavaScriptUnit compilationUnit, ASTNode[] coveredNodes) throws CoreException {
    if (coveredNodes == null) return null;

    if (coveredNodes.length == 0) return null;
    // check sub-expressions in fully covered nodes
    final ArrayList changedNodes = new ArrayList();
    for (int i = 0; i < coveredNodes.length; i++) {
      ASTNode covered = coveredNodes[i];
      if (covered instanceof InfixExpression)
        covered.accept(new MissingParenthesisVisitor(changedNodes));
    }
    if (changedNodes.isEmpty()) return null;

    IFixRewriteOperation op =
        new AddParenthesisOperation(
            (Expression[]) changedNodes.toArray(new Expression[changedNodes.size()]));
    return new ExpressionsFix(
        FixMessages.ExpressionsFix_addParanoiacParenthesis_description,
        compilationUnit,
        new IFixRewriteOperation[] {op});
  }
示例#13
0
  public static SimpleName[] findByProblems(ASTNode parent, SimpleName nameNode) {
    ArrayList res = new ArrayList();

    ASTNode astRoot = parent.getRoot();
    if (!(astRoot instanceof JavaScriptUnit)) {
      return null;
    }

    IProblem[] problems = ((JavaScriptUnit) astRoot).getProblems();
    int nameNodeKind = getNameNodeProblemKind(problems, nameNode);
    if (nameNodeKind == 0) { // no problem on node
      return null;
    }

    int bodyStart = parent.getStartPosition();
    int bodyEnd = bodyStart + parent.getLength();

    String name = nameNode.getIdentifier();

    for (int i = 0; i < problems.length; i++) {
      IProblem curr = problems[i];
      int probStart = curr.getSourceStart();
      int probEnd = curr.getSourceEnd() + 1;

      if (probStart > bodyStart && probEnd < bodyEnd) {
        int currKind = getProblemKind(curr);
        if ((nameNodeKind & currKind) != 0) {
          ASTNode node = NodeFinder.perform(parent, probStart, probEnd - probStart);
          if (node instanceof SimpleName && name.equals(((SimpleName) node).getIdentifier())) {
            res.add(node);
          }
        }
      }
    }
    return (SimpleName[]) res.toArray(new SimpleName[res.size()]);
  }
示例#14
0
 /**
  * Find all nodes connected to the given name node. If the node has a binding then all nodes
  * connected to this binding are returned. If the node has no binding, then all nodes that also
  * miss a binding and have the same name are returned.
  *
  * @param root The root of the AST tree to search
  * @param name The node to find linked nodes for
  * @return Return
  */
 public static SimpleName[] findByNode(ASTNode root, SimpleName name) {
   IBinding binding = name.resolveBinding();
   if (binding != null) {
     return findByBinding(root, binding);
   }
   SimpleName[] names = findByProblems(root, name);
   if (names != null) {
     return names;
   }
   int parentKind = name.getParent().getNodeType();
   if (parentKind == ASTNode.LABELED_STATEMENT
       || parentKind == ASTNode.BREAK_STATEMENT
       || parentKind == ASTNode.CONTINUE_STATEMENT) {
     ArrayList res = new ArrayList();
     LabelFinder nodeFinder = new LabelFinder(name, res);
     root.accept(nodeFinder);
     return (SimpleName[]) res.toArray(new SimpleName[res.size()]);
   }
   return new SimpleName[] {name};
 }
  /**
   * Collects the necessary imports for an element represented by the specified AST node.
   *
   * @param project the java project containing the element
   * @param node the AST node specifying the element for which imports should be collected
   * @param typeBindings the set of type bindings (element type: Set <ITypeBinding>).
   * @param staticBindings the set of bindings (element type: Set <IBinding>).
   * @param excludeBindings the set of bindings to exclude (element type: Set <IBinding>).
   * @param declarations <code>true</code> if method declarations are treated as abstract, <code>
   *     false</code> otherwise
   */
  public static void collectImports(
      final IJavaScriptProject project,
      final ASTNode node,
      final Collection typeBindings,
      final Collection staticBindings,
      final Collection excludeBindings,
      final boolean declarations) {
    Assert.isNotNull(project);
    Assert.isNotNull(node);
    Assert.isNotNull(typeBindings);
    Assert.isNotNull(staticBindings);
    final Set types = new HashSet();
    final Set members = new HashSet();
    final ImportReferencesCollector collector =
        new ImportReferencesCollector(project, null, types, members) {

          public final boolean visit(final Block block) {
            Assert.isNotNull(block);
            if (declarations && block.getParent() instanceof FunctionDeclaration) return false;
            return super.visit(block);
          }
        };
    node.accept(collector);
    Name name = null;
    IBinding binding = null;
    for (final Iterator iterator = types.iterator(); iterator.hasNext(); ) {
      name = (Name) iterator.next();
      binding = name.resolveBinding();
      if (binding instanceof ITypeBinding) {
        final ITypeBinding type = (ITypeBinding) binding;
        if (excludeBindings == null || !excludeBindings.contains(type)) typeBindings.add(type);
      }
    }
    for (final Iterator iterator = members.iterator(); iterator.hasNext(); ) {
      name = (Name) iterator.next();
      binding = name.resolveBinding();
      if (binding != null && (excludeBindings == null || !excludeBindings.contains(binding)))
        staticBindings.add(binding);
    }
  }
 private CodeScopeBuilder(ASTNode node, IBinding ignore) {
   fScope = new Scope(null, node.getStartPosition(), node.getLength());
   fScopes = new ArrayList();
   fIgnoreBinding = ignore;
 }
 private boolean snippetMatchesAstTokens(final String snippetCode, final ASTNode node) {
   final JavascriptTokenizer tokenizer = new JavascriptTokenizer();
   final List<String> snippetTokens = tokenizer.tokenListFromCode(snippetCode.toCharArray());
   final List<String> astTokens = tokenizer.tokenListFromCode(node.toString().toCharArray());
   return astTokens.equals(snippetTokens);
 }
 public static String asString(ASTNode node) {
   ASTFlattener flattener = new ASTFlattener();
   node.accept(flattener);
   return flattener.getResult();
 }
 protected boolean visitNode(ASTNode node) {
   Assert.isTrue(false, "No implementation to flatten node: " + node.toString()); // $NON-NLS-1$
   return false;
 }
 private CodeScopeBuilder(ASTNode node, Selection ignore) {
   fScope = new Scope(null, node.getStartPosition(), node.getLength());
   fScopes = new ArrayList();
   fIgnoreRange = ignore;
 }