Example usage for org.eclipse.jdt.core.dom Name resolveTypeBinding

List of usage examples for org.eclipse.jdt.core.dom Name resolveTypeBinding

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom Name resolveTypeBinding.

Prototype

public final ITypeBinding resolveTypeBinding() 

Source Link

Document

Resolves and returns the binding for the type of this expression.

Usage

From source file:ca.mcgill.cs.swevo.ppa.inference.QNameInferenceStrategy.java

License:Open Source License

/**
 * This method is necessary because resolveTypeBinding for a qualified name may result in
 * checking the declared class of a field instead of looking at the type of the previous field.
 * /*from w w w  . j a  v  a2s .  c om*/
 * @param right
 * @return
 */
private ITypeBinding getRightBinding(Name right) {
    IBinding binding = right.resolveBinding();
    ITypeBinding typeBinding = null;
    if (binding != null && binding instanceof IVariableBinding) {
        IVariableBinding varBinding = (IVariableBinding) binding;
        typeBinding = varBinding.getType();
    } else {
        typeBinding = right.resolveTypeBinding();
    }

    return typeBinding;
}

From source file:changetypes.ASTVisitorAtomicChange.java

License:Open Source License

public boolean visit(MethodDeclaration node) {
    IMethodBinding mtb = node.resolveBinding();
    this.mtbStack.push(mtb);
    String nodeStr = node.toString();

    String modifier = "protected";
    int dex = nodeStr.indexOf(' ');
    if (dex >= 0) {
        String temp = nodeStr.substring(0, dex);
        if (temp.equals("public")) {
            modifier = "public";
        } else if (temp.equals("private")) {
            modifier = "private";
        }//from w w  w. ja  va  2 s .c o m
    }
    try {
        String visibility = getModifier(mtb);
        this.facts.add(Fact.makeMethodFact(getQualifiedName(mtb), getSimpleName(mtb),
                getQualifiedName(mtb.getDeclaringClass()), visibility));
    } catch (Exception localException1) {
        System.err.println("Cannot resolve return method bindings for method " + node.getName().toString());
    }
    try {
        String returntype = getQualifiedName(mtb.getReturnType());
        this.facts.add(Fact.makeReturnsFact(getQualifiedName(mtb), returntype));
    } catch (Exception localException2) {
        System.err.println("Cannot resolve return type bindings for method " + node.getName().toString());
    }
    try {
        this.facts.add(Fact.makeModifierMethodFact(getQualifiedName(mtb), modifier));
    } catch (Exception localException3) {
        System.err.println(
                "Cannot resolve return type bindings for method modifier " + node.getName().toString());
    }
    try {
        String bodystring = node.getBody() != null ? node.getBody().toString() : "";
        bodystring = bodystring.replace('\n', ' ');

        bodystring = bodystring.replace('"', ' ');
        bodystring = bodystring.replace('"', ' ');
        bodystring = bodystring.replace('\\', ' ');

        this.facts.add(Fact.makeMethodBodyFact(getQualifiedName(mtb), bodystring));
    } catch (Exception localException4) {
        System.err.println("Cannot resolve bindings for body");
    }
    SingleVariableDeclaration param;
    try {
        List<SingleVariableDeclaration> parameters = node.parameters();

        StringBuilder sb = new StringBuilder();
        for (Iterator localIterator = parameters.iterator(); localIterator.hasNext();) {
            param = (SingleVariableDeclaration) localIterator.next();
            if (sb.length() != 0) {
                sb.append(", ");
            }
            sb.append(param.getType().toString());
            sb.append(":");
            sb.append(param.getName().toString());
        }
        this.facts.add(Fact.makeParameterFact(getQualifiedName(mtb), sb.toString(), ""));
    } catch (Exception localException5) {
        System.err.println("Cannot resolve bindings for parameters");
    }
    try {
        List<Name> thrownTypes = node.thrownExceptions();
        for (Name n : thrownTypes) {
            this.facts.add(Fact.makeThrownExceptionFact(getQualifiedName(mtb),
                    getQualifiedName(n.resolveTypeBinding())));
        }
    } catch (Exception localException6) {
        System.err.println("Cannot resolve bindings for exceptions");
    }
    return true;
}

From source file:com.intel.ide.eclipse.mpt.ast.UnresolvedElementsSubProcessor.java

License:Open Source License

public static void getVariableProposals(IInvocationContext context, IProblemLocation problem,
        IVariableBinding resolvedField, Map<String, Map> proposals) throws CoreException {

    ICompilationUnit cu = context.getCompilationUnit();

    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveredNode(astRoot);
    if (selectedNode == null) {
        return;//  w w  w. j a v  a  2 s .co  m
    }

    // 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;
    while (selectedNode instanceof ParenthesizedExpression) {
        selectedNode = ((ParenthesizedExpression) selectedNode).getExpression();
    }

    Name node = null;

    switch (selectedNode.getNodeType()) {
    case ASTNode.SIMPLE_NAME:
        node = (SimpleName) selectedNode;

        if (!isVariableProposalSafe(node))
            return;
        ASTNode parent = node.getParent();
        StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
        if (locationInParent == MethodInvocation.EXPRESSION_PROPERTY) {
        } 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) {
            suggestVariableProposals = false;
        } else if (parent instanceof QualifiedName) {
            Name qualifier = ((QualifiedName) parent).getQualifier();
            if (qualifier != node) {
                binding = qualifier.resolveTypeBinding();
            } else {
            }
            ASTNode outerParent = parent.getParent();
            while (outerParent instanceof QualifiedName) {
                outerParent = outerParent.getParent();
            }
            if (outerParent instanceof SimpleType) {
                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();
            suggestVariableProposals = node.isSimpleName();
        }
        if (selectedNode.getParent() instanceof SimpleType) {
            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;
    }

    if (!suggestVariableProposals) {
        return;
    }

    SimpleName simpleName = node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
    boolean isWriteAccess = ASTResolving.isWriteAccess(node);

    if (resolvedField == null || binding == null
            || resolvedField.getDeclaringClass() != binding.getTypeDeclaration()
                    && Modifier.isPrivate(resolvedField.getModifiers())) {

        // new fields
        addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals);
    }
}

From source file:de.akra.idocit.java.services.JavaInterfaceParser.java

License:Apache License

/**
 * Create the list of thrown exceptions. The list is wrapped in {@link JavaParameters}
 * ./*from   ww  w . ja  va 2 s . c o  m*/
 * 
 * @param parent
 *            The parent {@link SignatureElement}.
 * @param thrownExceptions
 *            The {@link List} of {@link SimpleName} of the thrown exceptions to
 *            process.
 * @return a new {@link JavaParameters}.
 */
private JavaParameters processThrownExceptions(final SignatureElement parent,
        final List<Name> thrownExceptions) {
    final JavaParameters exceptions = new JavaParameters(parent, Constants.CATEGORY_THROWS, Numerus.SINGULAR,
            false);
    exceptions.setDocumentationAllowed(false);
    exceptions.setIdentifier(StringUtils.EMPTY);
    exceptions.setQualifiedIdentifier(StringUtils.EMPTY);

    for (Name name : thrownExceptions) {
        final ITypeBinding typeBinding = name.resolveTypeBinding();
        final JavaParameter exception = new JavaParameter(exceptions,
                reflectionHelper.deriveNumerus(typeBinding),
                reflectionHelper.hasPublicAccessableAttributes(typeBinding));

        if (typeBinding != null) {
            // TODO should be the inner structure of Exceptions be
            // documentable? It
            // might be make sense for custom Exceptions.
            exception.setIdentifier(typeBinding.getName());
            exception.setQualifiedIdentifier(typeBinding.getQualifiedName());
            exception.setDataTypeName(typeBinding.getName());
            exception.setQualifiedDataTypeName(typeBinding.getQualifiedName());
        } else {
            String identifier;
            final String qIdentifier = name.getFullyQualifiedName();

            if (name.isQualifiedName()) {
                final QualifiedName qName = (QualifiedName) name;
                identifier = qName.getName().getIdentifier();
            } else {
                final SimpleName sName = (SimpleName) name;
                identifier = sName.getIdentifier();
            }
            exception.setIdentifier(identifier);
            exception.setQualifiedIdentifier(qIdentifier);
            exception.setDataTypeName(identifier);
            exception.setQualifiedDataTypeName(qIdentifier);
        }

        SignatureElementUtils.setParametersPaths(delimiters, exceptions.getQualifiedIdentifier(), exception);

        exceptions.addParameter(exception);
    }
    return exceptions;
}

From source file:de.ovgu.cide.typing.jdt.BindingProjectColorCache.java

License:Open Source License

/**
 * called after an item's color is changed. cycles through all children an
 * searches for java elements that need to be updated.
 * //ww  w .jav a  2s.co  m
 * @param nodes
 * @param file
 */
void updateASTColors(ASTNode node, final ColoredSourceFile file) {
    node.accept(new ASTVisitor() {
        public boolean visit(MethodDeclaration node) {
            String key = null;
            IMethodBinding binding = node.resolveBinding();
            if (binding != null) {
                IJavaElement javaElement = binding.getJavaElement();
                if (javaElement instanceof IMethod)
                    key = ((IMethod) javaElement).getKey();

            }
            if (key != null) {
                Set<IFeature> colors = getColor(file, node);
                update(bindingKeys2colors, key, colors);

                //add param keys
                for (int paramIdx = 0; paramIdx < node.parameters().size(); paramIdx++) {
                    ASTNode param = (ASTNode) node.parameters().get(paramIdx);

                    update(bindingKeys2colors, getParamKey(key, paramIdx), getColor(file, param));

                }

                //add exception keys
                for (int excIdx = 0; excIdx < node.thrownExceptions().size(); excIdx++) {
                    Name exception = (Name) node.thrownExceptions().get(excIdx);

                    ITypeBinding excBinding = exception.resolveTypeBinding();

                    if (excBinding == null)
                        continue;

                    update(bindingKeys2colors, getExceptionKey(key, excBinding.getKey()),
                            getColor(file, exception));

                }

            }
            return super.visit(node);
        }

        private Set<IFeature> getColor(final ColoredSourceFile file, ASTNode node) {
            return file.getColorManager().getColors(new AstidWrapperWithParents(node));
        }

        private void update(HashMap<String, Set<IFeature>> map, String key, Set<IFeature> colors) {

            if (colors != null && colors.size() > 0)
                map.put(key, colors);
            else
                map.remove(key);
        }

        public boolean visit(VariableDeclarationFragment node) {
            visitVD(node);
            return super.visit(node);
        }

        public boolean visit(SingleVariableDeclaration node) {
            visitVD(node);
            return super.visit(node);
        }

        public void visitVD(VariableDeclaration node) {
            String key = null;
            IVariableBinding binding = node.resolveBinding();
            if (binding != null) {
                IJavaElement javaElement = binding.getJavaElement();
                if (javaElement instanceof IField)
                    key = ((IField) javaElement).getKey();
            }
            if (key != null)
                update(bindingKeys2colors, key, getColor(file, node));
        }

        @Override
        public boolean visit(TypeDeclaration node) {
            ITypeBinding binding = node.resolveBinding();
            if (binding != null) {
                update(bindingKeys2colors, binding.getKey(), getColor(file, node));

            }
            return super.visit(node);
        }
    });
}

From source file:edu.buffalo.cse.green.relationship.alternateassociation.AssociationRecognizer.java

License:Open Source License

/**
 * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Assignment)
 *//*from   ww w.ja v  a2  s . c om*/
public boolean visit(Assignment node) {

    while (_lock)
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    Expression eLHS = node.getLeftHandSide();
    Expression eRHS = node.getRightHandSide();

    if (inConstructor()) {
        if (eLHS instanceof Name) {
            Name LHS = (Name) eLHS;

            if (isField(LHS)) {
                if (eRHS.getNodeType() == CLASS_INSTANCE_CREATION) {
                    _nots.add(LHS);
                } else if (eRHS.getNodeType() == STRING_LITERAL) {
                    _nots.add(LHS);
                }
            }
        }
    }

    if (eLHS instanceof Name && eRHS instanceof Name) {
        Name LHS = (Name) eLHS;
        Name RHS = (Name) eRHS;

        if (!isField(LHS))
            return true;
        if (!isParameter(RHS))
            return true;

        System.out.println("Booyah: found this d00d: " + LHS.getFullyQualifiedName());

        AbstractList<ASTNode> features = new ArrayList<ASTNode>();
        features.add(node.getParent());
        features.add(getMethodDeclaration());

        processAddInvocations(features, LHS, node);

        //fireFoundRelationship(getCurrentType(), LHS.resolveTypeBinding(),
        //      AssociationPart.class, features);

        _potentials.add(new Potential(features, getCurrentType(), LHS.resolveTypeBinding(), LHS));
    }

    return true;
}

From source file:edu.buffalo.cse.green.relationship.association.AssociationRecognizer.java

License:Open Source License

/**
 * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Assignment)
 *//* w  w  w.j av  a  2 s  .  c o  m*/
public boolean visit(Assignment node) {
    if (!inConstructor())
        return true;

    Expression eLHS = node.getLeftHandSide();
    Expression eRHS = node.getRightHandSide();

    if (eLHS instanceof Name && eRHS instanceof Name) {
        Name LHS = (Name) eLHS;
        Name RHS = (Name) eRHS;

        if (!isField(LHS))
            return true;
        if (!isParameter(RHS))
            return true;

        AbstractList<ASTNode> features = new ArrayList<ASTNode>();
        features.add(node.getParent());
        features.add(getMethodDeclaration());

        processAddInvocations(features, LHS, node);
        fireFoundRelationship(getCurrentType(), LHS.resolveTypeBinding(), AssociationPart.class, features);
    }

    return true;
}

From source file:edu.buffalo.cse.green.relationship.composition.CompositionRecognizer.java

License:Open Source License

/**
 * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Assignment)
 *//* w w w . ja v a 2s .co m*/
public boolean visit(Assignment node) {
    if (!inConstructor())
        return true;

    Expression eLHS = node.getLeftHandSide();
    Expression eRHS = node.getRightHandSide();

    if (eLHS instanceof Name) {
        Name LHS = (Name) eLHS;

        if (!isField(LHS))
            return true;

        if (eRHS.getNodeType() == CLASS_INSTANCE_CREATION) {
            AbstractList<ASTNode> features = new ArrayList<ASTNode>();
            features.add(node.getParent());
            features.add(getMethodDeclaration());

            processAddInvocations(features, LHS, node);
            fireFoundRelationship(getCurrentType(), LHS.resolveTypeBinding(), CompositionPart.class, features);
        } else if (eRHS.getNodeType() == STRING_LITERAL) {
            AbstractList<ASTNode> features = new ArrayList<ASTNode>();
            features.add(node.getParent());
            features.add(getMethodDeclaration());

            fireFoundRelationship(getCurrentType(), LHS.resolveTypeBinding(), CompositionPart.class, features);
        }
    }

    return true;
}

From source file:edu.cmu.cs.crystal.cfg.eclipse.EclipseCFG.java

License:Open Source License

@Override
public boolean visit(MethodDeclaration node) {
    EclipseCFGNode method = nodeMap.get(node);
    EclipseCFGNode implicitCatch;/*from   w ww.  ja v a  2 s . com*/

    excpReturns = new HashMap<ITypeBinding, EclipseCFGNode>();

    undeclExit = new EclipseCFGNode(null);
    createEdge(undeclExit, method);
    undeclExit.setName("(error)");
    exceptionMap.pushCatch(undeclExit, node.getAST().resolveWellKnownType("java.lang.Throwable"));

    for (Name name : (List<Name>) node.thrownExceptions()) {
        implicitCatch = new EclipseCFGNode(null);
        createEdge(implicitCatch, method);
        implicitCatch.setName("(throws)");
        exceptionMap.pushCatch(implicitCatch, (ITypeBinding) name.resolveBinding());
        excpReturns.put(name.resolveTypeBinding(), implicitCatch);
    }

    uberReturn = new EclipseCFGNode(null);
    uberReturn.setName("(uber-return)");
    createEdge(uberReturn, method);

    if (node.isConstructor()) {
        TypeDeclaration type = (TypeDeclaration) node.getParent();
        for (FieldDeclaration field : type.getFields()) {
            if (!Modifier.isStatic(field.getModifiers()))
                field.accept(this);
        }
    }

    // visit the statements individually.
    // we'll need to put them together by hand later so we can insert the
    // field decls
    // into constructors.
    for (ASTNode param : (List<ASTNode>) node.parameters())
        param.accept(this);
    if (node.getBody() != null)
        for (ASTNode stmt : (List<ASTNode>) node.getBody().statements())
            stmt.accept(this);

    return false;
}

From source file:edu.uci.ics.sourcerer.extractor.ast.ReferenceExtractorVisitor.java

License:Open Source License

/**
 * This method writes:/*from  w  ww  .java 2  s. com*/
 * <ul>
 *   <li>Constructor entity to <code>IEntityWriter</code>.
 *   <ul>
 *     <li>Inside relation to <code>IRelationWriter</code>.</li>
 *     <li>Throws relation to <code>IRelationWriter</code>.</li>
 *     
 *   </ul></li>
 *   <li>Method entity to <code>IEntityWriter</code>.
 *   <ul>
 *     <li>Inside relation to <code>IRelationWriter</code>.</li>
 *     <li>Returns relation to <code>IRelationWriter</code>.</li>
 *     <li>Throws relation to <code>IRelationWriter</code>.</li>
 *   </ul></li>
 * </ul>
 * 
 * Method fully qualified names (FQNs) adhere to the following format:<br> 
 * parent fqn + . + simple name + ( + parameter list + )
 * <p>
 * Constructor FQNs adhere to the following format:<br>
 * parent fqn + . + <init> + ( + parameter list + )
 */
@SuppressWarnings("unchecked")
@Override
public boolean visit(MethodDeclaration node) {
    // Build the fqn and type
    String fqn = null;
    Entity type = null;
    if (node.isConstructor()) {
        type = Entity.CONSTRUCTOR;
        fqn = getFuzzyConstructorFqn(node);

        // Write the entity
        entityWriter.writeConstructor(fqn, node.getModifiers(),
                MetricsCalculator.computeLinesOfCode(getSource(node)), getLocation(node));
    } else {
        type = Entity.METHOD;
        fqn = getFuzzyMethodFqn(node);

        // Write the entity
        entityWriter.writeMethod(fqn, node.getModifiers(),
                MetricsCalculator.computeLinesOfCode(getSource(node)), getLocation(node));

        // Write the returns relation
        Type returnType = node.getReturnType2();
        if (returnType == null) {
            logger.severe("Null return type for " + fqn);
        } else {
            relationWriter.writeReturns(fqn, getTypeFqn(returnType), getLocation(returnType));
        }
    }

    // Write the inside relation
    relationWriter.writeInside(fqn, fqnStack.getFqn(), getUnknownLocation());

    // Write the throws relation
    for (Name name : (List<Name>) node.thrownExceptions()) {
        ITypeBinding exceptionBinding = name.resolveTypeBinding();
        if (exceptionBinding == null) {
            relationWriter.writeThrows(fqn, getUnknownFqn(name.getFullyQualifiedName()), getLocation(node));
        } else {
            relationWriter.writeThrows(fqn, getTypeFqn(exceptionBinding), getLocation(name));
        }
    }

    // Attempt to determine overrides relations
    Deque<ITypeBinding> bindingStack = Helper.newStack();
    IMethodBinding method = node.resolveBinding();
    if (method != null) {
        ITypeBinding declaringClass = method.getDeclaringClass();
        if (declaringClass != null && declaringClass.getSuperclass() != null) {
            bindingStack.add(declaringClass.getSuperclass());
        }
        for (ITypeBinding interfaceBinding : declaringClass.getInterfaces()) {
            bindingStack.add(interfaceBinding);
        }
        while (!bindingStack.isEmpty()) {
            ITypeBinding top = bindingStack.pop();
            for (IMethodBinding methodBinding : top.getDeclaredMethods()) {
                if (method.overrides(methodBinding)) {
                    relationWriter.writeOverrides(fqn, getMethodFqn(methodBinding, false), getLocation(node));
                }
            }
            ITypeBinding superType = top.getSuperclass();
            if (superType != null) {
                bindingStack.add(superType);
            }
            for (ITypeBinding interfaceBinding : top.getInterfaces()) {
                bindingStack.add(interfaceBinding);
            }
        }
    }

    fqnStack.push(fqn, type);

    return true;
}