Search in sources :

Example 71 with SimpleName

use of org.eclipse.jdt.core.dom.SimpleName in project AutoRefactor by JnRouvignac.

the class TryWithResourceRefactoring method newFragment.

private VariableDeclarationFragment newFragment(List<Statement> tryStmts, VariableDeclarationFragment existingFragment, List<ASTNode> nodesToRemove) {
    final VariableDefinitionsUsesVisitor visitor = new VariableDefinitionsUsesVisitor(existingFragment).find();
    final List<SimpleName> definitions = visitor.getDefinitions();
    final ASTBuilder b = ctx.getASTBuilder();
    if (!tryStmts.isEmpty()) {
        final Statement tryStmt = tryStmts.get(0);
        final Assignment assignResource = asExpression(tryStmt, Assignment.class);
        if (assignResource != null && isSameVariable(existingFragment, assignResource.getLeftHandSide())) {
            nodesToRemove.add(tryStmt);
            if (containsOnly(definitions, assignResource.getLeftHandSide(), existingFragment.getName())) {
                return b.declareFragment(b.move(existingFragment.getName()), b.move(assignResource.getRightHandSide()));
            }
            return null;
        }
    }
    return containsOnly(definitions, existingFragment.getName()) ? b.move(existingFragment) : null;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTBuilder(org.autorefactor.refactoring.ASTBuilder)

Example 72 with SimpleName

use of org.eclipse.jdt.core.dom.SimpleName in project processing by processing.

the class CompletionGenerator method preparePredictions.

/**
   * The main function that calculates possible code completion candidates
   *
   * @param pdePhrase
   * @param line
   * @param lineStartNonWSOffset
   */
public List<CompletionCandidate> preparePredictions(final PreprocessedSketch ps, final String pdePhrase, final int lineNumber) {
    Messages.log("* preparePredictions");
    ASTNode astRootNode = (ASTNode) ps.compilationUnit.types().get(0);
    // If the parsed code contains pde enhancements, take 'em out.
    // TODO: test this
    TextTransform transform = new TextTransform(pdePhrase);
    transform.addAll(SourceUtils.replaceTypeConstructors(pdePhrase));
    transform.addAll(SourceUtils.replaceHexLiterals(pdePhrase));
    transform.addAll(SourceUtils.replaceColorRegex(pdePhrase));
    transform.addAll(SourceUtils.fixFloatsRegex(pdePhrase));
    String phrase = transform.apply();
    //After typing 'arg.' all members of arg type are to be listed. This one is a flag for it
    boolean noCompare = phrase.endsWith(".");
    if (noCompare) {
        phrase = phrase.substring(0, phrase.length() - 1);
    }
    boolean incremental = !noCompare && phrase.length() > lastPredictedPhrase.length() && phrase.startsWith(lastPredictedPhrase);
    if (incremental) {
        log(pdePhrase + " starts with " + lastPredictedPhrase);
        log("Don't recalc");
        if (phrase.contains(".")) {
            int x = phrase.lastIndexOf('.');
            candidates = trimCandidates(phrase.substring(x + 1), candidates);
        } else {
            candidates = trimCandidates(phrase, candidates);
        }
        lastPredictedPhrase = phrase;
        return candidates;
    }
    // Ensure that we're not inside a comment. TODO: Binary search
    /*for (Comment comm : getCodeComments()) {
      int commLineNo = PdeToJavaLineNumber(compilationUnit
          .getLineNumber(comm.getStartPosition()));
      if(commLineNo == lineNumber){
        log("Found a comment line " + comm);
        log("Comment LSO "
            + javaCodeOffsetToLineStartOffset(compilationUnit
          .getLineNumber(comm.getStartPosition()),
                                              comm.getStartPosition()));
        break;
      }
    }*/
    // Now parse the expression into an ASTNode object
    ASTNode nearestNode;
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_EXPRESSION);
    parser.setSource(phrase.toCharArray());
    ASTNode testnode = parser.createAST(null);
    //Base.loge("PREDICTION PARSER PROBLEMS: " + parser);
    // Find closest ASTNode of the document to this word
    Messages.loge("Typed: " + phrase + "|" + " temp Node type: " + testnode.getClass().getSimpleName());
    if (testnode instanceof MethodInvocation) {
        MethodInvocation mi = (MethodInvocation) testnode;
        log(mi.getName() + "," + mi.getExpression() + "," + mi.typeArguments().size());
    }
    // find nearest ASTNode
    nearestNode = findClosestNode(lineNumber, astRootNode);
    if (nearestNode == null) {
        // Make sure nearestNode is not NULL if couldn't find a closest node
        nearestNode = astRootNode;
    }
    Messages.loge(lineNumber + " Nearest ASTNode to PRED " + getNodeAsString(nearestNode));
    candidates = new ArrayList<>();
    lastPredictedPhrase = phrase;
    if (testnode instanceof SimpleName && !noCompare) {
        Messages.loge("One word expression " + getNodeAsString(testnode));
        //nearestNode = nearestNode.getParent();
        while (nearestNode != null) {
            // definitions.
            if (nearestNode instanceof TypeDeclaration) {
                TypeDeclaration td = (TypeDeclaration) nearestNode;
                if (td.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY) != null) {
                    SimpleType st = (SimpleType) td.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY);
                    log("Superclass " + st.getName());
                    ArrayList<CompletionCandidate> tempCandidates = getMembersForType(ps, st.getName().toString(), phrase, false, false);
                    for (CompletionCandidate can : tempCandidates) {
                        candidates.add(can);
                    }
                //findDeclaration(st.getName())
                }
            }
            List<StructuralPropertyDescriptor> sprops = nearestNode.structuralPropertiesForType();
            for (StructuralPropertyDescriptor sprop : sprops) {
                ASTNode cnode;
                if (!sprop.isChildListProperty()) {
                    if (nearestNode.getStructuralProperty(sprop) instanceof ASTNode) {
                        cnode = (ASTNode) nearestNode.getStructuralProperty(sprop);
                        CompletionCandidate[] types = checkForTypes(cnode);
                        if (types != null) {
                            for (CompletionCandidate type : types) {
                                if (type.getElementName().toLowerCase().startsWith(phrase.toLowerCase()))
                                    candidates.add(type);
                            }
                        }
                    }
                } else {
                    // Childlist prop
                    List<ASTNode> nodelist = (List<ASTNode>) nearestNode.getStructuralProperty(sprop);
                    for (ASTNode clnode : nodelist) {
                        CompletionCandidate[] types = checkForTypes(clnode);
                        if (types != null) {
                            for (CompletionCandidate type : types) {
                                if (type.getElementName().toLowerCase().startsWith(phrase.toLowerCase()))
                                    candidates.add(type);
                            }
                        }
                    }
                }
            }
            nearestNode = nearestNode.getParent();
        }
        // We're seeing a simple name that's not defined locally or in
        // the parent class. So most probably a pre-defined type.
        log("Empty can. " + phrase);
        ClassPath classPath = ps.classPath;
        if (classPath != null) {
            RegExpResourceFilter regExpResourceFilter = new RegExpResourceFilter(Pattern.compile(".*"), Pattern.compile(phrase + "[a-zA-Z_0-9]*.class", Pattern.CASE_INSENSITIVE));
            String[] resources = classPath.findResources("", regExpResourceFilter);
            for (String matchedClass2 : resources) {
                //package name
                matchedClass2 = matchedClass2.replace('/', '.');
                String matchedClass = matchedClass2.substring(0, matchedClass2.length() - 6);
                int d = matchedClass.lastIndexOf('.');
                if (!ignorableSuggestionImport(ps, matchedClass)) {
                    //class name
                    matchedClass = matchedClass.substring(d + 1);
                    // display package name in grey
                    String html = "<html>" + matchedClass + " : <font color=#777777>" + matchedClass2.substring(0, d) + "</font></html>";
                    candidates.add(new CompletionCandidate(matchedClass, html, matchedClass, CompletionCandidate.PREDEF_CLASS));
                }
            }
        }
    } else {
        // ==> Complex expression of type blah.blah2().doIt,etc
        // Have to resolve it by carefully traversing AST of testNode
        Messages.loge("Complex expression " + getNodeAsString(testnode));
        log("candidates empty");
        ASTNode childExpr = getChildExpression(testnode);
        log("Parent expression : " + getParentExpression(testnode));
        log("Child expression : " + childExpr);
        if (!noCompare) {
            log("Original testnode " + getNodeAsString(testnode));
            testnode = getParentExpression(testnode);
            log("Corrected testnode " + getNodeAsString(testnode));
        }
        ClassMember expr = resolveExpression3rdParty(ps, nearestNode, testnode, noCompare);
        if (expr == null) {
            log("Expr is null");
        } else {
            boolean isArray = expr.thisclass != null && expr.thisclass.isArray();
            boolean isSimpleType = (expr.astNode != null) && expr.astNode.getNodeType() == ASTNode.SIMPLE_TYPE;
            boolean isMethod = expr.method != null;
            boolean staticOnly = !isMethod && !isArray && !isSimpleType;
            log("Expr is " + expr.toString());
            String lookFor = (noCompare || (childExpr == null)) ? "" : childExpr.toString();
            candidates = getMembersForType(ps, expr, lookFor, noCompare, staticOnly);
        }
    }
    return candidates;
}
Also used : ClassPath(com.google.classpath.ClassPath) SimpleName(org.eclipse.jdt.core.dom.SimpleName) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SimpleType(org.eclipse.jdt.core.dom.SimpleType) RegExpResourceFilter(com.google.classpath.RegExpResourceFilter) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) ASTParser(org.eclipse.jdt.core.dom.ASTParser) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 73 with SimpleName

use of org.eclipse.jdt.core.dom.SimpleName in project processing by processing.

the class CompletionGenerator method findDeclaration.

/*
  protected SketchOutline sketchOutline;

  public void showSketchOutline() {
    if (editor.hasJavaTabs()) return;

    sketchOutline = new SketchOutline(editor, codeTree);
    sketchOutline.show();
  }


  public void showTabOutline() {
    new TabOutline(editor).show();
  }
  */
/**
   * Give this thing a {@link Name} instance - a {@link SimpleName} from the
   * ASTNode for ex, and it tries its level best to locate its declaration in
   * the AST. It really does.
   *
   * @param findMe
   * @return
   */
protected static ASTNode findDeclaration(Name findMe) {
    // WARNING: You're entering the Rube Goldberg territory of Experimental Mode.
    // To debug this code, thou must take the Recursive Leap of Faith.
    // log("entering --findDeclaration1 -- " + findMe.toString());
    ASTNode declaringClass;
    ASTNode parent = findMe.getParent();
    ASTNode ret;
    ArrayList<Integer> constrains = new ArrayList<>();
    if (parent.getNodeType() == ASTNode.METHOD_INVOCATION) {
        Expression exp = (Expression) parent.getStructuralProperty(MethodInvocation.EXPRESSION_PROPERTY);
        // Possibly a bug here. Investigate later.
        if (((MethodInvocation) parent).getName().toString().equals(findMe.toString())) {
            constrains.add(ASTNode.METHOD_DECLARATION);
            if (exp != null) {
                constrains.add(ASTNode.TYPE_DECLARATION);
                //              + exp.getClass().getName() + " parent: " + exp.getParent());
                if (exp instanceof MethodInvocation) {
                    SimpleType stp = extracTypeInfo(findDeclaration(((MethodInvocation) exp).getName()));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration(stp.getName());
                    return definedIn(declaringClass, ((MethodInvocation) parent).getName().toString(), constrains);
                } else if (exp instanceof FieldAccess) {
                    SimpleType stp = extracTypeInfo(findDeclaration(((FieldAccess) exp).getName()));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration((stp.getName()));
                    return definedIn(declaringClass, ((MethodInvocation) parent).getName().toString(), constrains);
                }
                if (exp instanceof SimpleName) {
                    SimpleType stp = extracTypeInfo(findDeclaration(((SimpleName) exp)));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration(stp.getName());
                    //            log("MI.SN " + getNodeAsString(declaringClass));
                    constrains.add(ASTNode.METHOD_DECLARATION);
                    return definedIn(declaringClass, ((MethodInvocation) parent).getName().toString(), constrains);
                }
            }
        } else {
            // Move one up the ast. V V IMP!!
            parent = parent.getParent();
        }
    } else if (parent.getNodeType() == ASTNode.FIELD_ACCESS) {
        FieldAccess fa = (FieldAccess) parent;
        Expression exp = fa.getExpression();
        if (fa.getName().toString().equals(findMe.toString())) {
            constrains.add(ASTNode.FIELD_DECLARATION);
            if (exp != null) {
                constrains.add(ASTNode.TYPE_DECLARATION);
                //              + exp.getClass().getName() + " parent: " + exp.getParent());
                if (exp instanceof MethodInvocation) {
                    SimpleType stp = extracTypeInfo(findDeclaration(((MethodInvocation) exp).getName()));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration(stp.getName());
                    return definedIn(declaringClass, fa.getName().toString(), constrains);
                } else if (exp instanceof FieldAccess) {
                    SimpleType stp = extracTypeInfo(findDeclaration(((FieldAccess) exp).getName()));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration((stp.getName()));
                    constrains.add(ASTNode.TYPE_DECLARATION);
                    return definedIn(declaringClass, fa.getName().toString(), constrains);
                }
                if (exp instanceof SimpleName) {
                    SimpleType stp = extracTypeInfo(findDeclaration(((SimpleName) exp)));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration(stp.getName());
                    //            log("FA.SN " + getNodeAsString(declaringClass));
                    constrains.add(ASTNode.METHOD_DECLARATION);
                    return definedIn(declaringClass, fa.getName().toString(), constrains);
                }
            }
        } else {
            // Move one up the ast. V V IMP!!
            parent = parent.getParent();
        }
    } else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME) {
        QualifiedName qn = (QualifiedName) parent;
        if (!findMe.toString().equals(qn.getQualifier().toString())) {
            SimpleType stp = extracTypeInfo(findDeclaration((qn.getQualifier())));
            //        log(qn.getQualifier() + "->" + qn.getName());
            if (stp == null) {
                return null;
            }
            declaringClass = findDeclaration(stp.getName());
            //        log("QN decl class: " + getNodeAsString(declaringClass));
            constrains.clear();
            constrains.add(ASTNode.TYPE_DECLARATION);
            constrains.add(ASTNode.FIELD_DECLARATION);
            return definedIn(declaringClass, qn.getName().toString(), constrains);
        } else {
            if (findMe instanceof QualifiedName) {
                QualifiedName qnn = (QualifiedName) findMe;
                //          log("findMe is a QN, "
                //              + (qnn.getQualifier().toString() + " other " + qnn.getName()
                //                  .toString()));
                SimpleType stp = extracTypeInfo(findDeclaration((qnn.getQualifier())));
                if (stp == null) {
                    return null;
                }
                declaringClass = findDeclaration(stp.getName());
                constrains.clear();
                constrains.add(ASTNode.TYPE_DECLARATION);
                constrains.add(ASTNode.FIELD_DECLARATION);
                return definedIn(declaringClass, qnn.getName().toString(), constrains);
            }
        }
    } else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE) {
        constrains.add(ASTNode.TYPE_DECLARATION);
        if (parent.getParent().getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
            constrains.add(ASTNode.CLASS_INSTANCE_CREATION);
        }
    } else if (parent.getNodeType() == ASTNode.TYPE_DECLARATION) {
        // The condition where we look up the name of a class decl
        TypeDeclaration td = (TypeDeclaration) parent;
        if (findMe.equals(td.getName())) {
            return parent;
        }
    } else if (parent instanceof Expression) {
    //      constrains.add(ASTNode.TYPE_DECLARATION);
    //      constrains.add(ASTNode.METHOD_DECLARATION);
    //      constrains.add(ASTNode.FIELD_DECLARATION);
    }
    //    }
    while (parent != null) {
        //      log("findDeclaration1 -> " + getNodeAsString(parent));
        for (Object oprop : parent.structuralPropertiesForType()) {
            StructuralPropertyDescriptor prop = (StructuralPropertyDescriptor) oprop;
            if (prop.isChildProperty() || prop.isSimpleProperty()) {
                if (parent.getStructuralProperty(prop) instanceof ASTNode) {
                    //            log(prop + " C/S Prop of -> "
                    //                + getNodeAsString(parent));
                    ret = definedIn((ASTNode) parent.getStructuralProperty(prop), findMe.toString(), constrains);
                    if (ret != null)
                        return ret;
                }
            } else if (prop.isChildListProperty()) {
                //          log((prop) + " ChildList props of "
                //              + getNodeAsString(parent));
                List<ASTNode> nodelist = (List<ASTNode>) parent.getStructuralProperty(prop);
                for (ASTNode retNode : nodelist) {
                    ret = definedIn(retNode, findMe.toString(), constrains);
                    if (ret != null)
                        return ret;
                }
            }
        }
        parent = parent.getParent();
    }
    return null;
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 74 with SimpleName

use of org.eclipse.jdt.core.dom.SimpleName in project processing by processing.

the class ASTUtils method getSimpleNameAt.

public static SimpleName getSimpleNameAt(ASTNode root, int startJavaOffset, int stopJavaOffset) {
    Messages.log("* getSimpleNameAt");
    // Find node at offset
    ASTNode node = getASTNodeAt(root, startJavaOffset, stopJavaOffset);
    SimpleName result = null;
    if (node == null) {
        result = null;
    } else if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
        result = (SimpleName) node;
    } else {
        // Return SimpleName with highest coverage
        List<SimpleName> simpleNames = getSimpleNameChildren(node);
        if (!simpleNames.isEmpty()) {
            // Compute coverage <selection x node>
            int[] coverages = simpleNames.stream().mapToInt(name -> {
                int start = name.getStartPosition();
                int stop = start + name.getLength();
                return Math.min(stop, stopJavaOffset) - Math.max(startJavaOffset, start);
            }).toArray();
            // Select node with highest coverage
            int maxIndex = IntStream.range(0, simpleNames.size()).filter(i -> coverages[i] >= 0).reduce((i, j) -> coverages[i] > coverages[j] ? i : j).orElse(-1);
            if (maxIndex == -1)
                return null;
            result = simpleNames.get(maxIndex);
        }
    }
    if (result == null) {
        Messages.log("no simple name found");
    } else {
        Messages.log("found " + node.toString());
    }
    return result;
}
Also used : IntStream(java.util.stream.IntStream) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Arrays(java.util.Arrays) Messages(processing.app.Messages) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IBinding(org.eclipse.jdt.core.dom.IBinding) NodeFinder(org.eclipse.jdt.core.dom.NodeFinder) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ArrayList(java.util.ArrayList) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) Type(org.eclipse.jdt.core.dom.Type) List(java.util.List) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List)

Example 75 with SimpleName

use of org.eclipse.jdt.core.dom.SimpleName in project processing by processing.

the class CompletionGenerator method findDeclaration2.

/**
   * A variation of findDeclaration() but accepts an alternate parent ASTNode
   * @param findMe
   * @param alternateParent
   * @return
   */
protected static ASTNode findDeclaration2(Name findMe, ASTNode alternateParent) {
    ASTNode declaringClass;
    ASTNode parent = findMe.getParent();
    ASTNode ret;
    ArrayList<Integer> constrains = new ArrayList<>();
    if (parent.getNodeType() == ASTNode.METHOD_INVOCATION) {
        Expression exp = (Expression) parent.getStructuralProperty(MethodInvocation.EXPRESSION_PROPERTY);
        // Possibly a bug here. Investigate later.
        if (((MethodInvocation) parent).getName().toString().equals(findMe.toString())) {
            constrains.add(ASTNode.METHOD_DECLARATION);
            if (exp != null) {
                constrains.add(ASTNode.TYPE_DECLARATION);
                //              + exp.getClass().getName() + " parent: " + exp.getParent());
                if (exp instanceof MethodInvocation) {
                    SimpleType stp = extracTypeInfo(findDeclaration2(((MethodInvocation) exp).getName(), alternateParent));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration2(stp.getName(), alternateParent);
                    return definedIn(declaringClass, ((MethodInvocation) parent).getName().toString(), constrains);
                } else if (exp instanceof FieldAccess) {
                    SimpleType stp = extracTypeInfo(findDeclaration2(((FieldAccess) exp).getName(), alternateParent));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration2((stp.getName()), alternateParent);
                    return definedIn(declaringClass, ((MethodInvocation) parent).getName().toString(), constrains);
                }
                if (exp instanceof SimpleName) {
                    SimpleType stp = extracTypeInfo(findDeclaration2(((SimpleName) exp), alternateParent));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration2(stp.getName(), alternateParent);
                    //            log("MI.SN " + getNodeAsString(declaringClass));
                    constrains.add(ASTNode.METHOD_DECLARATION);
                    return definedIn(declaringClass, ((MethodInvocation) parent).getName().toString(), constrains);
                }
            }
        } else {
            // Move one up the ast. V V IMP!!
            parent = parent.getParent();
            alternateParent = alternateParent.getParent();
        }
    } else if (parent.getNodeType() == ASTNode.FIELD_ACCESS) {
        FieldAccess fa = (FieldAccess) parent;
        Expression exp = fa.getExpression();
        if (fa.getName().toString().equals(findMe.toString())) {
            constrains.add(ASTNode.FIELD_DECLARATION);
            if (exp != null) {
                constrains.add(ASTNode.TYPE_DECLARATION);
                //              + exp.getClass().getName() + " parent: " + exp.getParent());
                if (exp instanceof MethodInvocation) {
                    SimpleType stp = extracTypeInfo(findDeclaration2(((MethodInvocation) exp).getName(), alternateParent));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration2(stp.getName(), alternateParent);
                    return definedIn(declaringClass, fa.getName().toString(), constrains);
                } else if (exp instanceof FieldAccess) {
                    SimpleType stp = extracTypeInfo(findDeclaration2(((FieldAccess) exp).getName(), alternateParent));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration2((stp.getName()), alternateParent);
                    constrains.add(ASTNode.TYPE_DECLARATION);
                    return definedIn(declaringClass, fa.getName().toString(), constrains);
                }
                if (exp instanceof SimpleName) {
                    SimpleType stp = extracTypeInfo(findDeclaration2(((SimpleName) exp), alternateParent));
                    if (stp == null)
                        return null;
                    declaringClass = findDeclaration2(stp.getName(), alternateParent);
                    //            log("FA.SN " + getNodeAsString(declaringClass));
                    constrains.add(ASTNode.METHOD_DECLARATION);
                    return definedIn(declaringClass, fa.getName().toString(), constrains);
                }
            }
        } else {
            // Move one up the ast. V V IMP!!
            parent = parent.getParent();
            alternateParent = alternateParent.getParent();
        }
    } else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME) {
        QualifiedName qn = (QualifiedName) parent;
        if (!findMe.toString().equals(qn.getQualifier().toString())) {
            SimpleType stp = extracTypeInfo(findDeclaration2((qn.getQualifier()), alternateParent));
            if (stp == null)
                return null;
            declaringClass = findDeclaration2(stp.getName(), alternateParent);
            //        log(qn.getQualifier() + "->" + qn.getName());
            //        log("QN decl class: " + getNodeAsString(declaringClass));
            constrains.clear();
            constrains.add(ASTNode.TYPE_DECLARATION);
            constrains.add(ASTNode.FIELD_DECLARATION);
            return definedIn(declaringClass, qn.getName().toString(), constrains);
        } else {
            if (findMe instanceof QualifiedName) {
                QualifiedName qnn = (QualifiedName) findMe;
                //          log("findMe is a QN, "
                //              + (qnn.getQualifier().toString() + " other " + qnn.getName()
                //                  .toString()));
                SimpleType stp = extracTypeInfo(findDeclaration2((qnn.getQualifier()), alternateParent));
                if (stp == null) {
                    return null;
                }
                //          log(qnn.getQualifier() + "->" + qnn.getName());
                declaringClass = findDeclaration2(stp.getName(), alternateParent);
                //          log("QN decl class: "
                //              + getNodeAsString(declaringClass));
                constrains.clear();
                constrains.add(ASTNode.TYPE_DECLARATION);
                constrains.add(ASTNode.FIELD_DECLARATION);
                return definedIn(declaringClass, qnn.getName().toString(), constrains);
            }
        }
    } else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE) {
        constrains.add(ASTNode.TYPE_DECLARATION);
        if (parent.getParent().getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
            constrains.add(ASTNode.CLASS_INSTANCE_CREATION);
    } else if (parent instanceof Expression) {
    //      constrains.add(ASTNode.TYPE_DECLARATION);
    //      constrains.add(ASTNode.METHOD_DECLARATION);
    //      constrains.add(ASTNode.FIELD_DECLARATION);
    }
    //    log("Alternate parent: " + getNodeAsString(alternateParent));
    while (alternateParent != null) {
        //          + getNodeAsString(alternateParent));
        for (Object oprop : alternateParent.structuralPropertiesForType()) {
            StructuralPropertyDescriptor prop = (StructuralPropertyDescriptor) oprop;
            if (prop.isChildProperty() || prop.isSimpleProperty()) {
                if (alternateParent.getStructuralProperty(prop) instanceof ASTNode) {
                    //            log(prop + " C/S Prop of -> "
                    //                + getNodeAsString(alternateParent));
                    ret = definedIn((ASTNode) alternateParent.getStructuralProperty(prop), findMe.toString(), constrains);
                    if (ret != null)
                        return ret;
                }
            } else if (prop.isChildListProperty()) {
                //          log((prop) + " ChildList props of "
                //              + getNodeAsString(alternateParent));
                List<ASTNode> nodelist = (List<ASTNode>) alternateParent.getStructuralProperty(prop);
                for (ASTNode retNode : nodelist) {
                    ret = definedIn(retNode, findMe.toString(), constrains);
                    if (ret != null)
                        return ret;
                }
            }
        }
        alternateParent = alternateParent.getParent();
    }
    return null;
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Aggregations

SimpleName (org.eclipse.jdt.core.dom.SimpleName)291 ASTNode (org.eclipse.jdt.core.dom.ASTNode)122 IBinding (org.eclipse.jdt.core.dom.IBinding)70 Expression (org.eclipse.jdt.core.dom.Expression)67 AST (org.eclipse.jdt.core.dom.AST)63 ArrayList (java.util.ArrayList)60 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)57 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)55 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)53 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)47 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)46 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)44 QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)43 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)41 Name (org.eclipse.jdt.core.dom.Name)40 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)35 Type (org.eclipse.jdt.core.dom.Type)35 Block (org.eclipse.jdt.core.dom.Block)34 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)33 Assignment (org.eclipse.jdt.core.dom.Assignment)32