Search in sources :

Example 31 with MethodInvocation

use of org.eclipse.jdt.core.dom.MethodInvocation 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 32 with MethodInvocation

use of org.eclipse.jdt.core.dom.MethodInvocation 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 33 with MethodInvocation

use of org.eclipse.jdt.core.dom.MethodInvocation 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)

Example 34 with MethodInvocation

use of org.eclipse.jdt.core.dom.MethodInvocation in project xtext-eclipse by eclipse.

the class JvmImplementationOpener method openImplementations.

/**
 * Main parts of the logic is taken from {@link org.eclipse.jdt.internal.ui.javaeditor.JavaElementImplementationHyperlink}
 *
 * @param element - Element to show implementations for
 * @param textviewer - Viewer to show hierarchy view on
 * @param region - Region where to show hierarchy view
 */
public void openImplementations(final IJavaElement element, ITextViewer textviewer, IRegion region) {
    if (element instanceof IMethod) {
        ITypeRoot typeRoot = ((IMethod) element).getTypeRoot();
        CompilationUnit ast = SharedASTProvider.getAST(typeRoot, SharedASTProvider.WAIT_YES, null);
        if (ast == null) {
            openQuickHierarchy(textviewer, element, region);
            return;
        }
        try {
            ISourceRange nameRange = ((IMethod) element).getNameRange();
            ASTNode node = NodeFinder.perform(ast, nameRange);
            ITypeBinding parentTypeBinding = null;
            if (node instanceof SimpleName) {
                ASTNode parent = node.getParent();
                if (parent instanceof MethodInvocation) {
                    Expression expression = ((MethodInvocation) parent).getExpression();
                    if (expression == null) {
                        parentTypeBinding = Bindings.getBindingOfParentType(node);
                    } else {
                        parentTypeBinding = expression.resolveTypeBinding();
                    }
                } else if (parent instanceof SuperMethodInvocation) {
                    // Directly go to the super method definition
                    openEditor(element);
                    return;
                } else if (parent instanceof MethodDeclaration) {
                    parentTypeBinding = Bindings.getBindingOfParentType(node);
                }
            }
            final IType type = parentTypeBinding != null ? (IType) parentTypeBinding.getJavaElement() : null;
            if (type == null) {
                openQuickHierarchy(textviewer, element, region);
                return;
            }
            final String earlyExitIndicator = "EarlyExitIndicator";
            final ArrayList<IJavaElement> links = Lists.newArrayList();
            IRunnableWithProgress runnable = new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    if (monitor == null) {
                        monitor = new NullProgressMonitor();
                    }
                    try {
                        String methodLabel = JavaElementLabels.getElementLabel(element, JavaElementLabels.DEFAULT_QUALIFIED);
                        monitor.beginTask(Messages.format("Searching for implementors of  ''{0}''", methodLabel), 100);
                        SearchRequestor requestor = new SearchRequestor() {

                            @Override
                            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                                if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
                                    IJavaElement element = (IJavaElement) match.getElement();
                                    if (element instanceof IMethod && !JdtFlags.isAbstract((IMethod) element)) {
                                        links.add(element);
                                        if (links.size() > 1) {
                                            throw new OperationCanceledException(earlyExitIndicator);
                                        }
                                    }
                                }
                            }
                        };
                        int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
                        SearchPattern pattern = SearchPattern.createPattern(element, limitTo);
                        Assert.isNotNull(pattern);
                        SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
                        SearchEngine engine = new SearchEngine();
                        engine.search(pattern, participants, SearchEngine.createHierarchyScope(type), requestor, SubMonitor.convert(monitor, 100));
                        if (monitor.isCanceled()) {
                            throw new InterruptedException();
                        }
                    } catch (OperationCanceledException e) {
                        throw new InterruptedException(e.getMessage());
                    } catch (CoreException e) {
                        throw new InvocationTargetException(e);
                    } finally {
                        monitor.done();
                    }
                }
            };
            try {
                PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
            } catch (InvocationTargetException e) {
                IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format("An error occurred while searching for implementations of method ''{0}''. See error log for details.", element.getElementName()), e.getCause());
                JavaPlugin.log(status);
                ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Open Implementation", "Problems finding implementations.", status);
            } catch (InterruptedException e) {
                if (e.getMessage() != earlyExitIndicator) {
                    return;
                }
            }
            if (links.size() == 1) {
                openEditor(links.get(0));
            } else {
                openQuickHierarchy(textviewer, element, region);
            }
        } catch (JavaModelException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        } catch (PartInitException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IStatus(org.eclipse.core.runtime.IStatus) JavaModelException(org.eclipse.jdt.core.JavaModelException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IType(org.eclipse.jdt.core.IType) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) SearchParticipant(org.eclipse.jdt.core.search.SearchParticipant) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) PartInitException(org.eclipse.ui.PartInitException) ISourceRange(org.eclipse.jdt.core.ISourceRange) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IJavaElement(org.eclipse.jdt.core.IJavaElement) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeRoot(org.eclipse.jdt.core.ITypeRoot) InvocationTargetException(java.lang.reflect.InvocationTargetException) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) Expression(org.eclipse.jdt.core.dom.Expression)

Example 35 with MethodInvocation

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

the class AllInOneMethodRatherThanLoopRefactoring method replaceWithCollectionMethod.

private boolean replaceWithCollectionMethod(ForStatement node, ForLoopContent loopContent, String methodName, MethodInvocation colMI) {
    final Expression addArg0 = arg0(colMI);
    final MethodInvocation getMI = as(addArg0, MethodInvocation.class);
    if (isSameVariable(loopContent, getMI)) {
        return replaceWithCollectionMethod(node, methodName, colMI.getExpression(), getMI.getExpression());
    }
    return VISIT_SUBTREE;
}
Also used : Expression(org.eclipse.jdt.core.dom.Expression) ASTHelper.asExpression(org.autorefactor.refactoring.ASTHelper.asExpression) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation)

Aggregations

MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)265 Expression (org.eclipse.jdt.core.dom.Expression)112 SuperMethodInvocation (org.eclipse.jdt.core.dom.SuperMethodInvocation)59 ASTNode (org.eclipse.jdt.core.dom.ASTNode)53 SimpleName (org.eclipse.jdt.core.dom.SimpleName)53 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)51 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)48 ASTNodeFactory (org.autorefactor.jdt.internal.corext.dom.ASTNodeFactory)47 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)43 ArrayList (java.util.ArrayList)40 CastExpression (org.eclipse.jdt.core.dom.CastExpression)40 TextEditGroup (org.eclipse.text.edits.TextEditGroup)37 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)34 Block (org.eclipse.jdt.core.dom.Block)33 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)33 ClassInstanceCreation (org.eclipse.jdt.core.dom.ClassInstanceCreation)31 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)31 AST (org.eclipse.jdt.core.dom.AST)30 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)29 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)28