Search in sources :

Example 11 with StructuralPropertyDescriptor

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

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

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

use of org.eclipse.jdt.core.dom.StructuralPropertyDescriptor in project che by eclipse.

the class TightSourceRangeComputer method addTightSourceNode.

/**
	 * Add the given node to the set of "tight" nodes.
	 *
	 * @param reference a node
	 * @since 3.2
	 */
public void addTightSourceNode(ASTNode reference) {
    fTightSourceRangeNodes.add(reference);
    List<StructuralPropertyDescriptor> properties = reference.structuralPropertiesForType();
    for (Iterator<StructuralPropertyDescriptor> iterator = properties.iterator(); iterator.hasNext(); ) {
        StructuralPropertyDescriptor descriptor = iterator.next();
        if (descriptor.isChildProperty()) {
            ASTNode child = (ASTNode) reference.getStructuralProperty(descriptor);
            if (child != null && isExtending(child, reference)) {
                addTightSourceNode(child);
            }
        } else if (descriptor.isChildListProperty()) {
            List<? extends ASTNode> children = ASTNodes.getChildListProperty(reference, (ChildListPropertyDescriptor) descriptor);
            for (Iterator<? extends ASTNode> iterator2 = children.iterator(); iterator2.hasNext(); ) {
                ASTNode child = iterator2.next();
                if (isExtending(child, reference)) {
                    addTightSourceNode(child);
                }
            }
        }
    }
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode) Iterator(java.util.Iterator) List(java.util.List) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor)

Example 15 with StructuralPropertyDescriptor

use of org.eclipse.jdt.core.dom.StructuralPropertyDescriptor in project che by eclipse.

the class UnresolvedElementsSubProcessor method getVariableProposals.

public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, IVariableBinding resolvedField, Collection<ICommandAccess> proposals) throws CoreException {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveredNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    // type that defines the variable
    ITypeBinding binding = null;
    ITypeBinding declaringTypeBinding = Bindings.getBindingOfParentTypeContext(selectedNode);
    if (declaringTypeBinding == null) {
        return;
    }
    // possible type kind of the node
    boolean suggestVariableProposals = true;
    int typeKind = 0;
    while (selectedNode instanceof ParenthesizedExpression) {
        selectedNode = ((ParenthesizedExpression) selectedNode).getExpression();
    }
    Name node = null;
    switch(selectedNode.getNodeType()) {
        case ASTNode.SIMPLE_NAME:
            node = (SimpleName) selectedNode;
            ASTNode parent = node.getParent();
            StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
            if (locationInParent == ExpressionMethodReference.EXPRESSION_PROPERTY) {
                typeKind = SimilarElementsRequestor.REF_TYPES;
            } else if (locationInParent == MethodInvocation.EXPRESSION_PROPERTY) {
                if (JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
                    typeKind = SimilarElementsRequestor.CLASSES | SimilarElementsRequestor.INTERFACES | SimilarElementsRequestor.ENUMS;
                } else {
                    typeKind = SimilarElementsRequestor.CLASSES;
                }
            } else if (locationInParent == FieldAccess.NAME_PROPERTY) {
                Expression expression = ((FieldAccess) parent).getExpression();
                if (expression != null) {
                    binding = expression.resolveTypeBinding();
                    if (binding == null) {
                        node = null;
                    }
                }
            } else if (parent instanceof SimpleType || parent instanceof NameQualifiedType) {
                suggestVariableProposals = false;
                typeKind = SimilarElementsRequestor.REF_TYPES_AND_VAR;
            } else if (parent instanceof QualifiedName) {
                Name qualifier = ((QualifiedName) parent).getQualifier();
                if (qualifier != node) {
                    binding = qualifier.resolveTypeBinding();
                } else {
                    typeKind = SimilarElementsRequestor.REF_TYPES;
                }
                ASTNode outerParent = parent.getParent();
                while (outerParent instanceof QualifiedName) {
                    outerParent = outerParent.getParent();
                }
                if (outerParent instanceof SimpleType || outerParent instanceof NameQualifiedType) {
                    typeKind = SimilarElementsRequestor.REF_TYPES;
                    suggestVariableProposals = false;
                }
            } else if (locationInParent == SwitchCase.EXPRESSION_PROPERTY) {
                ITypeBinding switchExp = ((SwitchStatement) node.getParent().getParent()).getExpression().resolveTypeBinding();
                if (switchExp != null && switchExp.isEnum()) {
                    binding = switchExp;
                }
            } else if (locationInParent == SuperFieldAccess.NAME_PROPERTY) {
                binding = declaringTypeBinding.getSuperclass();
            }
            break;
        case ASTNode.QUALIFIED_NAME:
            QualifiedName qualifierName = (QualifiedName) selectedNode;
            ITypeBinding qualifierBinding = qualifierName.getQualifier().resolveTypeBinding();
            if (qualifierBinding != null) {
                node = qualifierName.getName();
                binding = qualifierBinding;
            } else {
                node = qualifierName.getQualifier();
                typeKind = SimilarElementsRequestor.REF_TYPES;
                suggestVariableProposals = node.isSimpleName();
            }
            if (selectedNode.getParent() instanceof SimpleType || selectedNode.getParent() instanceof NameQualifiedType) {
                typeKind = SimilarElementsRequestor.REF_TYPES;
                suggestVariableProposals = false;
            }
            break;
        case ASTNode.FIELD_ACCESS:
            FieldAccess access = (FieldAccess) selectedNode;
            Expression expression = access.getExpression();
            if (expression != null) {
                binding = expression.resolveTypeBinding();
                if (binding != null) {
                    node = access.getName();
                }
            }
            break;
        case ASTNode.SUPER_FIELD_ACCESS:
            binding = declaringTypeBinding.getSuperclass();
            node = ((SuperFieldAccess) selectedNode).getName();
            break;
        default:
    }
    if (node == null) {
        return;
    }
    // add type proposals
    if (typeKind != 0) {
        if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
            typeKind &= ~(SimilarElementsRequestor.ANNOTATIONS | SimilarElementsRequestor.ENUMS | SimilarElementsRequestor.VARIABLES);
        }
        int relevance = Character.isUpperCase(ASTNodes.getSimpleNameIdentifier(node).charAt(0)) ? IProposalRelevance.VARIABLE_TYPE_PROPOSAL_1 : IProposalRelevance.VARIABLE_TYPE_PROPOSAL_2;
        addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
        typeKind &= ~SimilarElementsRequestor.ANNOTATIONS;
        addNewTypeProposals(cu, node, typeKind, relevance, proposals);
        ReorgCorrectionsSubProcessor.addProjectSetupFixProposal(context, problem, node.getFullyQualifiedName(), proposals);
    }
    if (!suggestVariableProposals) {
        return;
    }
    SimpleName simpleName = node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
    boolean isWriteAccess = ASTResolving.isWriteAccess(node);
    // similar variables
    addSimilarVariableProposals(cu, astRoot, binding, resolvedField, simpleName, isWriteAccess, proposals);
    if (binding == null) {
        addStaticImportFavoriteProposals(context, simpleName, false, proposals);
    }
    if (resolvedField == null || binding == null || resolvedField.getDeclaringClass() != binding.getTypeDeclaration() && Modifier.isPrivate(resolvedField.getModifiers())) {
        // new fields
        addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals);
        // new parameters and local variables
        if (binding == null) {
            addNewVariableProposals(cu, node, simpleName, proposals);
        }
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) SimpleType(org.eclipse.jdt.core.dom.SimpleType) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Aggregations

StructuralPropertyDescriptor (org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)28 ASTNode (org.eclipse.jdt.core.dom.ASTNode)21 Expression (org.eclipse.jdt.core.dom.Expression)10 AST (org.eclipse.jdt.core.dom.AST)7 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)7 SimpleName (org.eclipse.jdt.core.dom.SimpleName)7 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)7 Block (org.eclipse.jdt.core.dom.Block)6 CastExpression (org.eclipse.jdt.core.dom.CastExpression)6 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)6 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)6 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)6 List (java.util.List)5 Assignment (org.eclipse.jdt.core.dom.Assignment)5 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)5 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)5 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)5 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)5 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)5