/*
  * @see edu.berkeley.eduride.isa.corext.dom.GenericVisitor#visitNode(org.eclipse.jdt.core.dom.ASTNode)
  */
 protected boolean visitNode(ASTNode node) {
   if ((node.getFlags() & ASTNode.MALFORMED) == ASTNode.MALFORMED) {
     retainPositions(node.getStartPosition(), node.getLength());
     return false;
   }
   return true;
 }
Ejemplo n.º 2
0
 protected boolean found(ASTNode node, ASTNode name) {
   if (name.getStartPosition() == this.rangeStart && name.getLength() == this.rangeLength) {
     this.foundNode = node;
     return true;
   }
   return false;
 }
 private void divideTypeRefs(
     List /* <SimpleName> */ importNames,
     List /* <SimpleName> */ staticNames,
     List /* <SimpleName> */ removedRefs,
     List /* <SimpleName> */ unremovedRefs) {
   int[] removedStartsEnds = new int[2 * fRemovedNodes.size()];
   for (int index = 0; index < fRemovedNodes.size(); index++) {
     ASTNode node = (ASTNode) fRemovedNodes.get(index);
     int start = node.getStartPosition();
     removedStartsEnds[2 * index] = start;
     removedStartsEnds[2 * index + 1] = start + node.getLength();
   }
   for (Iterator iterator = importNames.iterator(); iterator.hasNext(); ) {
     SimpleName name = (SimpleName) iterator.next();
     if (isInRemoved(name, removedStartsEnds)) removedRefs.add(name);
     else unremovedRefs.add(name);
   }
   for (Iterator iterator = staticNames.iterator(); iterator.hasNext(); ) {
     SimpleName name = (SimpleName) iterator.next();
     if (isInRemoved(name, removedStartsEnds)) removedRefs.add(name);
     else unremovedRefs.add(name);
   }
   for (Iterator iterator = fInlinedStaticImports.iterator(); iterator.hasNext(); ) {
     ImportDeclaration importDecl = (ImportDeclaration) iterator.next();
     Name name = importDecl.getName();
     if (name instanceof QualifiedName) name = ((QualifiedName) name).getName();
     removedRefs.add(name);
   }
 }
  @SuppressWarnings("rawtypes") // DOM AST API returns raw collections
  public SourcePosition getPosition() {
    final MirrorKind kind = _parent.kind();
    ASTNode astNode = null;
    switch (kind) {
      case ANNOTATION_MIRROR:
        final AnnotationMirrorImpl anno = (AnnotationMirrorImpl) _parent;
        astNode = anno.getASTNodeForElement(_name);
        break;
      case ANNOTATION_ELEMENT:
        final AnnotationElementDeclarationImpl element = (AnnotationElementDeclarationImpl) _parent;
        astNode = element.getAstNodeForDefault();
        break;
      default:
        throw new IllegalStateException(); // should never reach this point.
    }
    // did not come from source.
    if (astNode == null) return null;
    if (_index >= 0 && astNode.getNodeType() == ASTNode.ARRAY_INITIALIZER) {
      final ArrayInitializer arrayInit = (ArrayInitializer) astNode;
      final List exprs = arrayInit.expressions();
      if (exprs != null && _index < exprs.size()) astNode = (ASTNode) exprs.get(_index);
    }
    if (astNode == null) return null;

    final CompilationUnit unit = getCompilationUnit();
    if (unit == null) return null;
    final int offset = astNode.getStartPosition();
    return new SourcePositionImpl(
        astNode.getStartPosition(),
        astNode.getLength(),
        unit.getLineNumber(offset),
        unit.getColumnNumber(offset),
        this);
  }
 private boolean isAffected(ASTNode node) {
   if (fSubRange == null) {
     return true;
   }
   int nodeStart = node.getStartPosition();
   int offset = fSubRange.getOffset();
   return nodeStart + node.getLength() > offset && offset + fSubRange.getLength() > nodeStart;
 }
 public int[] getSelectionStartAndEnd(ICompilationUnit iunit) {
   int[] offsets = new int[2];
   CompilationUnit parsedUnit = ASTreeManipulationMethods.parseICompilationUnit(iunit);
   ASTNode nodeOne = ASTreeManipulationMethods.getASTNodeByIndex(parsedUnit, firstCutNodeIndex);
   ASTNode nodeTwo = ASTreeManipulationMethods.getASTNodeByIndex(parsedUnit, lastCutNodeIndex);
   offsets[0] = nodeOne.getStartPosition();
   offsets[1] = nodeTwo.getStartPosition() + nodeTwo.getLength() - 1;
   return offsets;
 }
  private boolean isNodeEnclosingMethod(ASTNode node) {
    int nodeStartPosition = node.getStartPosition();
    int nodeEndPosition = nodeStartPosition + node.getLength();

    if (nodeStartPosition < fMethodStartPosition && nodeEndPosition > fMethodEndPosition) {
      // Is the method completely enclosed by the node?
      return true;
    }
    return false;
  }
  private boolean isNodeWithinMethod(ASTNode node) {
    int nodeStartPosition = node.getStartPosition();
    int nodeEndPosition = nodeStartPosition + node.getLength();

    if (nodeStartPosition < fMethodStartPosition) {
      return false;
    }

    if (nodeEndPosition > fMethodEndPosition) {
      return false;
    }

    return true;
  }
  /**
   * Adds the specified method binding to the search results.
   *
   * @param calledMethodBinding
   * @param node
   */
  protected void addMethodCall(IMethodBinding calledMethodBinding, ASTNode node) {
    try {
      if (calledMethodBinding != null) {
        fProgressMonitor.worked(1);

        ITypeBinding calledTypeBinding = calledMethodBinding.getDeclaringClass();
        IType calledType = null;

        if (!calledTypeBinding.isAnonymous()) {
          calledType = (IType) calledTypeBinding.getJavaElement();
        } else {
          if (!"java.lang.Object"
              .equals(calledTypeBinding.getSuperclass().getQualifiedName())) { // $NON-NLS-1$
            calledType = (IType) calledTypeBinding.getSuperclass().getJavaElement();
          } else {
            calledType = (IType) calledTypeBinding.getInterfaces()[0].getJavaElement();
          }
        }

        IMethod calledMethod =
            findIncludingSupertypes(calledMethodBinding, calledType, fProgressMonitor);

        IMember referencedMember = null;
        if (calledMethod == null) {
          if (calledMethodBinding.isConstructor()
              && calledMethodBinding.getParameterTypes().length == 0) {
            referencedMember = calledType;
          }
        } else {
          if (calledType.isInterface()) {
            calledMethod = findImplementingMethods(calledMethod);
          }

          if (!isIgnoredBySearchScope(calledMethod)) {
            referencedMember = calledMethod;
          }
        }
        final int position = node.getStartPosition();
        final int number = fCompilationUnit.getLineNumber(position);
        fSearchResults.addMember(
            fMember,
            referencedMember,
            position,
            position + node.getLength(),
            number < 1 ? 1 : number);
      }
    } catch (JavaModelException jme) {
      JavaPlugin.log(jme);
    }
  }
  @Override
  public boolean visit(LambdaExpression node) {
    Selection selection = getSelection();
    int selectionStart = selection.getOffset();
    int selectionExclusiveEnd = selection.getExclusiveEnd();
    int lambdaStart = node.getStartPosition();
    int lambdaExclusiveEnd = lambdaStart + node.getLength();
    ASTNode body = node.getBody();
    int bodyStart = body.getStartPosition();
    int bodyExclusiveEnd = bodyStart + body.getLength();

    boolean isValidSelection = false;
    if ((body instanceof Block)
        && (bodyStart < selectionStart && selectionExclusiveEnd <= bodyExclusiveEnd)) {
      // if selection is inside lambda body's block
      isValidSelection = true;
    } else if (body instanceof Expression) {
      try {
        TokenScanner scanner = new TokenScanner(fCUnit);
        int arrowExclusiveEnd =
            scanner.getTokenEndOffset(ITerminalSymbols.TokenNameARROW, lambdaStart);
        if (selectionStart >= arrowExclusiveEnd) {
          isValidSelection = true;
        }
      } catch (CoreException e) {
        // ignore
      }
    }
    if (selectionStart <= lambdaStart && selectionExclusiveEnd >= lambdaExclusiveEnd) {
      // if selection covers the lambda node
      isValidSelection = true;
    }

    if (!isValidSelection) {
      return false;
    }
    return super.visit(node);
  }
  /*(non-Javadoc)
   * @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
   */
  @Override
  protected ASTRewrite getRewrite() {
    AST ast = fMethodDecl.getAST();

    ITypeBinding returnBinding = getReturnTypeBinding();

    if (fExistingReturn != null) {
      ASTRewrite rewrite = ASTRewrite.create(ast);

      Expression expression =
          evaluateReturnExpressions(ast, returnBinding, fExistingReturn.getStartPosition());
      if (expression != null) {
        rewrite.set(fExistingReturn, ReturnStatement.EXPRESSION_PROPERTY, expression, null);

        addLinkedPosition(rewrite.track(expression), true, RETURN_EXPRESSION_KEY);
      }
      return rewrite;
    } else {
      ASTRewrite rewrite = ASTRewrite.create(ast);

      Block block = fMethodDecl.getBody();

      List<Statement> statements = block.statements();
      int nStatements = statements.size();
      ASTNode lastStatement = null;
      if (nStatements > 0) {
        lastStatement = statements.get(nStatements - 1);
      }

      if (returnBinding != null
          && lastStatement instanceof ExpressionStatement
          && lastStatement.getNodeType() != ASTNode.ASSIGNMENT) {
        Expression expression = ((ExpressionStatement) lastStatement).getExpression();
        ITypeBinding binding = expression.resolveTypeBinding();
        if (binding != null && binding.isAssignmentCompatible(returnBinding)) {
          Expression placeHolder = (Expression) rewrite.createMoveTarget(expression);

          ReturnStatement returnStatement = ast.newReturnStatement();
          returnStatement.setExpression(placeHolder);

          rewrite.replace(lastStatement, returnStatement, null);
          return rewrite;
        }
      }

      int offset;
      if (lastStatement == null) {
        offset = block.getStartPosition() + 1;
      } else {
        offset = lastStatement.getStartPosition() + lastStatement.getLength();
      }
      ReturnStatement returnStatement = ast.newReturnStatement();
      Expression expression = evaluateReturnExpressions(ast, returnBinding, offset);

      returnStatement.setExpression(expression);

      rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertLast(returnStatement, null);

      addLinkedPosition(
          rewrite.track(returnStatement.getExpression()), true, RETURN_EXPRESSION_KEY);
      return rewrite;
    }
  }
 public boolean visit(VariableDeclarationFragment node) {
   String name = getFieldName(node);
   ASTNode parent = node.getParent();
   push(JavaNode.FIELD, name, parent.getStartPosition(), parent.getLength());
   return false;
 }
Ejemplo n.º 13
0
  private boolean isClosed(IDocument document, int offset, int length) {

    CompilationUnitInfo info = getCompilationUnitForMethod(document, offset);
    if (info == null) return false;

    CompilationUnit compilationUnit = null;
    try {
      ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
      parser.setSource(info.buffer);
      compilationUnit = (CompilationUnit) parser.createAST(null);
    } catch (ArrayIndexOutOfBoundsException x) {
      // work around for parser problem
      return false;
    }

    IProblem[] problems = compilationUnit.getProblems();
    for (int i = 0; i != problems.length; ++i) {
      if (problems[i].getID() == IProblem.UnmatchedBracket) return true;
    }

    final int relativeOffset = offset - info.delta;

    ASTNode node = NodeFinder.perform(compilationUnit, relativeOffset, length);

    if (length == 0) {
      while (node != null
          && (relativeOffset == node.getStartPosition()
              || relativeOffset == node.getStartPosition() + node.getLength()))
        node = node.getParent();
    }

    if (node == null) return false;

    switch (node.getNodeType()) {
      case ASTNode.BLOCK:
        return getBlockBalance(document, offset, fPartitioning) <= 0;

      case ASTNode.IF_STATEMENT:
        {
          IfStatement ifStatement = (IfStatement) node;
          Expression expression = ifStatement.getExpression();
          IRegion expressionRegion = createRegion(expression, info.delta);
          Statement thenStatement = ifStatement.getThenStatement();
          IRegion thenRegion = createRegion(thenStatement, info.delta);

          // between expression and then statement
          if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset
              && offset + length <= thenRegion.getOffset()) return thenStatement != null;

          Statement elseStatement = ifStatement.getElseStatement();
          IRegion elseRegion = createRegion(elseStatement, info.delta);

          if (elseStatement != null) {
            int sourceOffset = thenRegion.getOffset() + thenRegion.getLength();
            int sourceLength = elseRegion.getOffset() - sourceOffset;
            IRegion elseToken =
                getToken(
                    document,
                    new Region(sourceOffset, sourceLength),
                    ITerminalSymbols.TokenNameelse);
            return elseToken != null
                && elseToken.getOffset() + elseToken.getLength() <= offset
                && offset + length < elseRegion.getOffset();
          }
        }
        break;

      case ASTNode.WHILE_STATEMENT:
      case ASTNode.FOR_STATEMENT:
        {
          Expression expression =
              node.getNodeType() == ASTNode.WHILE_STATEMENT
                  ? ((WhileStatement) node).getExpression()
                  : ((ForStatement) node).getExpression();
          IRegion expressionRegion = createRegion(expression, info.delta);
          Statement body =
              node.getNodeType() == ASTNode.WHILE_STATEMENT
                  ? ((WhileStatement) node).getBody()
                  : ((ForStatement) node).getBody();
          IRegion bodyRegion = createRegion(body, info.delta);

          // between expression and body statement
          if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset
              && offset + length <= bodyRegion.getOffset()) return body != null;
        }
        break;

      case ASTNode.DO_STATEMENT:
        {
          DoStatement doStatement = (DoStatement) node;
          IRegion doRegion = createRegion(doStatement, info.delta);
          Statement body = doStatement.getBody();
          IRegion bodyRegion = createRegion(body, info.delta);

          if (doRegion.getOffset() + doRegion.getLength() <= offset
              && offset + length <= bodyRegion.getOffset()) return body != null;
        }
        break;
    }

    return true;
  }
Ejemplo n.º 14
0
 private static IRegion createRegion(ASTNode node, int delta) {
   return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength());
 }
Ejemplo n.º 15
0
  @Test
  public void testOneMethod() {
    System.out.println("filetypes in given file");
    System.out.println("inheritance " + resolver.getSuperType());
    System.out.println("interfaces " + resolver.getInterfaces());
    Map<String, String> types = resolver.getClassesInFile();
    for (MethodInvocationResolver.TypeDecl typeDeclaration : resolver.getTypeDeclarations()) {
      System.out.println(
          types.get(typeDeclaration.getClassName())
              + "   "
              + unit.getLineNumber(typeDeclaration.getLoc())
              + "  "
              + unit.getColumnNumber(typeDeclaration.getLoc()));
    }

    Map<ASTNode, String> typesAtPos = resolver.getVariableTypesAtPosition();
    System.out.println("~~~~~~variable Typeaatposition  ");
    for (Entry<ASTNode, String> e : typesAtPos.entrySet()) {
      Integer line = unit.getLineNumber(e.getKey().getStartPosition());
      Integer col = unit.getColumnNumber(e.getKey().getStartPosition());
      System.out.println(
          line + " , " + col + " , " + e.getKey().getLength() + " : " + e.getValue());
    }

    System.out.println("########  Import name position");
    for (Entry<ASTNode, String> e : resolver.getImportsDeclarationNode().entrySet()) {
      Integer line = unit.getLineNumber(e.getKey().getStartPosition());
      Integer col = unit.getColumnNumber(e.getKey().getStartPosition());
      System.out.println(
          line + " , " + col + " , " + e.getKey().getLength() + " : " + e.getValue());
    }

    System.out.println("--------------Type at positions ");
    for (Entry<ASTNode, String> e : resolver.getTypesAtPosition().entrySet()) {
      Integer line = unit.getLineNumber(e.getKey().getStartPosition());
      Integer col = unit.getColumnNumber(e.getKey().getStartPosition());
      System.out.println(
          line + " , " + col + " , " + e.getKey().getLength() + " : " + e.getValue());
    }

    for (Entry<ASTNode, ASTNode> e : resolver.getVariableDependencies().entrySet()) {
      ASTNode child = e.getKey();
      Integer chline = unit.getLineNumber(child.getStartPosition());
      Integer chcol = unit.getColumnNumber(child.getStartPosition());
      Integer chLength = child.getLength();
      ASTNode parent = e.getValue();
      Integer pline = unit.getLineNumber(parent.getStartPosition());
      Integer pcol = unit.getColumnNumber(parent.getStartPosition());
      Integer plength = parent.getLength();
      System.out.println(
          "**** "
              + child
              + "["
              + chline
              + ", "
              + chcol
              + ", "
              + chLength
              + "] ==> "
              + parent.toString()
              + "["
              + pline
              + ", "
              + pcol
              + ", "
              + plength
              + "]");
    }

    for (Entry<String, List<MethodInvokRef>> entry : resolver.getMethodInvoks().entrySet()) {
      System.out.println(" ~~~~~~~~~~~ For method " + entry.getKey() + " ~~~~~~~~~~~");
      for (MethodInvokRef m : entry.getValue()) {
        Integer loc = m.getLocation();
        Integer line = unit.getLineNumber(loc);
        Integer col = unit.getColumnNumber(loc);
        System.out.println("[" + line + ", " + col + ", " + m.getLength() + " ] ==> " + m);
      }
    }

    for (MethodDecl m : resolver.getDeclaredMethods()) {
      System.out.println("~~~~~~~~~~~~~~~~~ Declared Methods ~~~~~~~~~~~~~~~~~");
      System.out.println(m);
    }
    System.out.println(resolver.getVariableTypes());
  }