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

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

Introduction

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

Prototype

public final ITypeBinding resolveTypeBinding() 

Source Link

Document

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

Usage

From source file:com.google.gdt.eclipse.designer.builders.participant.MyCompilationParticipant.java

License:Open Source License

/**
 * Adds error markers for types that are not visible in inherited "source" packages.
 *///from   w w w .  ja v  a  2s .co  m
private void addMarkers_notImportedTypes(final List<MarkerInfo> newMarkers,
        final IResourcesProvider resourcesProvider, ModuleDescription moduleDescription,
        CompilationUnit astUnit, final IFile file, final IDocument document) throws Exception {
    final IJavaProject javaProject = JavaCore.create(file.getProject());
    // prepare list of source packages
    final List<SourcePackageDescriptor> sourcePackages = Lists.newArrayList();
    ModuleVisitor.accept(moduleDescription, new ModuleVisitor() {
        @Override
        public void visitSourcePackage(ModuleElement module, String packageName, boolean superSource)
                throws Exception {
            sourcePackages.add(new SourcePackageDescriptor(packageName, superSource));
        }
    });
    // validate all types in CompilationUnit
    astUnit.accept(new ASTVisitor() {
        private final Set<String> m_validClasses = Sets.newTreeSet();
        private final Set<String> m_invalidClasses = Sets.newTreeSet();

        @Override
        public boolean visit(SingleMemberAnnotation node) {
            return false;
        }

        @Override
        public boolean visit(NormalAnnotation node) {
            return false;
        }

        @Override
        public void postVisit(final ASTNode node) {
            ExecutionUtils.runIgnore(new RunnableEx() {
                public void run() throws Exception {
                    postVisitEx(node);
                }
            });
        }

        private void postVisitEx(ASTNode node) throws Exception {
            // ignore imports
            if (AstNodeUtils.getEnclosingNode(node, ImportDeclaration.class) != null) {
                return;
            }
            // check known cases
            if (node instanceof SimpleType) {
                SimpleType simpleType = (SimpleType) node;
                ITypeBinding typeBinding = simpleType.resolveBinding();
                checkNode(node, typeBinding);
            } else if (node instanceof SimpleName) {
                SimpleName simpleName = (SimpleName) node;
                if (simpleName.resolveBinding().getKind() == IBinding.TYPE
                        && node.getLocationInParent() == MethodInvocation.EXPRESSION_PROPERTY) {
                    ITypeBinding typeBinding = simpleName.resolveTypeBinding();
                    checkNode(node, typeBinding);
                }
            }
        }

        private void checkNode(ASTNode node, ITypeBinding typeBinding) throws Exception {
            if (typeBinding != null) {
                // ignore generics type variable
                if (typeBinding.isTypeVariable()) {
                    return;
                }
                // only top level types can be found as source
                while (typeBinding.getDeclaringClass() != null) {
                    typeBinding = typeBinding.getDeclaringClass();
                }
                // check this type
                String typeName = AstNodeUtils.getFullyQualifiedName(typeBinding, true);
                if (isSecondarySourceType(typeName)) {
                    return;
                }
                checkClass(node, typeName);
            }
        }

        private boolean isSecondarySourceType(String typeName) throws Exception {
            // usually secondary type can not be found using this way
            IType type = javaProject.findType(typeName);
            if (type == null) {
                return true;
            }
            // "secondary source type" has compilation unit
            ICompilationUnit compilationUnit = type.getCompilationUnit();
            if (compilationUnit == null) {
                return false;
            }
            // check if type name in same as unit name
            String unitName = compilationUnit.getElementName();
            unitName = StringUtils.removeEnd(unitName, ".java");
            return !typeName.endsWith("." + unitName);
        }

        /**
         * Check that class with given name is defined in this or inherited module.
         */
        private void checkClass(ASTNode node, String className) throws Exception {
            if (!isValid(className)) {
                markAsInvalid(node, className);
            }
        }

        /**
         * @return <code>true</code> if given class is valid.
         */
        private boolean isValid(String className) {
            // check cached valid classes
            if (m_validClasses.contains(className)) {
                return true;
            }
            // check cached invalid classes
            if (m_invalidClasses.contains(className)) {
                return false;
            }
            // no information in caches, do checks 
            for (SourcePackageDescriptor sourcePackageDescriptor : sourcePackages) {
                if (sourcePackageDescriptor.isValidClass(resourcesProvider, className)) {
                    m_validClasses.add(className);
                    return true;
                }
            }
            // mark as invalid
            m_invalidClasses.add(className);
            return false;
        }

        private void markAsInvalid(ASTNode node, String className) throws Exception {
            String message = className + " can not be found in source packages. "
                    + "Check the inheritance chain from your module; "
                    + "it may not be inheriting a required module or a module "
                    + "may not be adding its source path entries properly.";
            String moduleNameToImport = getEnclosingModule(resourcesProvider, className);
            newMarkers.add(createMarkerInfo_importModule(file, document, node.getStartPosition(),
                    node.getLength(), message, moduleNameToImport));
        }
    });
}

From source file:de.jevopi.j2og.simpleParser.Visitor.java

License:Open Source License

/**
 * {@inheritDoc}//w w w  . j  a va 2  s. c  o m
 * 
 * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.SimpleName)
 * @since Aug 20, 2011
 */
@Override
public boolean visit(SimpleName i_node) {

    if (!classifierStack.isEmpty()) {

        ITypeBinding typeBinding = i_node.resolveTypeBinding();
        if (typeBinding != null) {

            Type type = getType(typeBinding, true);
            if (type != classifierStack.peek() && !type.getFqn().startsWith(classifierStack.peek().getFqn())) {
                classifierStack.peek().addDependency(type);
            }
        }
    }
    return super.visit(i_node);
}

From source file:lang.java.jdt.internal.FullyQualifyTypeNames.java

License:Open Source License

@Override
public boolean visit(FieldAccess node) {
    Expression exp = node.getExpression();
    if (exp instanceof SimpleName) {
        SimpleName sn = (SimpleName) exp;
        ITypeBinding tb = sn.resolveTypeBinding();
        if (tb != null && (tb.isClass() || tb.isInterface())) {
            IPackageBinding pb = tb.getPackage();
            if (pb != null && !pb.isUnnamed()) {
                String qualifiedTypeName = "";
                if (tb.isNested()) {
                    ITypeBinding parent = tb.getDeclaringClass();
                    String parentString = parent.getName();
                    while (parent != null && parent.isNested()) {
                        parent = parent.getDeclaringClass();
                        parentString = parent.getName() + "." + parentString;
                    }/*from  w w w.j  a  v a 2  s .  c o  m*/
                    qualifiedTypeName = pb.getName() + "." + parentString + ".";
                } else {
                    qualifiedTypeName = pb.getName() + ".";
                }
                qualifiedTypeName = qualifiedTypeName + sn.toString();
                Name n = node.getAST().newName(qualifiedTypeName);
                rewriter.replace(exp, n, null);
            }
        }
    }
    return true;
}

From source file:lang.java.jdt.internal.FullyQualifyTypeNames.java

License:Open Source License

@Override
public boolean visit(MethodInvocation node) {
    Expression exp = node.getExpression();
    if (exp instanceof SimpleName) {
        SimpleName sn = (SimpleName) exp;
        IBinding b = sn.resolveBinding();
        if (b.getKind() == IBinding.TYPE) {
            ITypeBinding tb = sn.resolveTypeBinding();
            if (tb != null && (tb.isClass() || tb.isInterface())) {
                IPackageBinding pb = tb.getPackage();
                if (pb != null && !pb.isUnnamed()) {
                    String qualifiedTypeName = "";
                    if (tb.isNested()) {
                        ITypeBinding parent = tb.getDeclaringClass();
                        String parentString = parent.getName();
                        while (parent != null && parent.isNested()) {
                            parent = parent.getDeclaringClass();
                            parentString = parent.getName() + "." + parentString;
                        }/* w ww  . ja va 2  s.com*/
                        qualifiedTypeName = pb.getName() + "." + parentString + ".";
                    } else {
                        qualifiedTypeName = pb.getName() + ".";
                    }
                    qualifiedTypeName = qualifiedTypeName + sn.toString();
                    Name n = node.getAST().newName(qualifiedTypeName);
                    rewriter.replace(exp, n, null);
                }
            }
        }
    }
    return true;
}

From source file:lang.java.jdt.internal.UnqualifyTypeNames.java

License:Open Source License

@Override
public boolean visit(FieldAccess node) {
    Expression exp = node.getExpression();
    if (exp instanceof SimpleName) {
        SimpleName sn = (SimpleName) exp;
        ITypeBinding tb = sn.resolveTypeBinding();
        if (tb != null && (tb.isClass() || tb.isInterface() || tb.isEnum())) {
            String typeName = "";
            if (tb.getErasure() != null)
                typeName = tb.getErasure().getName();
            else//w  ww  . jav  a 2 s.  c om
                typeName = tb.getName();

            ITypeBinding declaringClass = tb.getDeclaringClass();
            while (declaringClass != null) {
                typeName = declaringClass.getErasure().getName() + "." + typeName;
                declaringClass = declaringClass.getDeclaringClass();
            }

            IPackageBinding pb = tb.getPackage();
            if (pb != null && !pb.isUnnamed()) {
                typeName = pb.getName() + "." + typeName;
            }

            if (unqualifiedTypes.containsKey(typeName)) {
                Name n = node.getAST().newName(unqualifiedTypes.get(typeName));
                rewriter.replace(exp, n, null);
            }
        }
    }
    return true;
}

From source file:lang.java.jdt.internal.UnqualifyTypeNames.java

License:Open Source License

@Override
public boolean visit(MethodInvocation node) {
    Expression exp = node.getExpression();
    if (exp instanceof SimpleName) {
        SimpleName sn = (SimpleName) exp;
        IBinding b = sn.resolveBinding();
        if (b.getKind() == IBinding.TYPE) {
            ITypeBinding tb = sn.resolveTypeBinding();
            if (tb != null && (tb.isClass() || tb.isInterface())) {
                String typeName = "";
                if (tb.getErasure() != null)
                    typeName = tb.getErasure().getName();
                else
                    typeName = tb.getName();

                ITypeBinding declaringClass = tb.getDeclaringClass();
                while (declaringClass != null) {
                    typeName = declaringClass.getErasure().getName() + "." + typeName;
                    declaringClass = declaringClass.getDeclaringClass();
                }//from   w  w  w.  java  2s  .c  om

                IPackageBinding pb = tb.getPackage();
                if (pb != null && !pb.isUnnamed()) {
                    typeName = pb.getName() + "." + typeName;
                }

                if (unqualifiedTypes.containsKey(typeName)) {
                    Name n = node.getAST().newName(unqualifiedTypes.get(typeName));
                    rewriter.replace(exp, n, null);
                }
            }
        }
    }
    return true;
}

From source file:navclus.userinterface.classdiagram.java.analyzer.TypePartVisitor.java

License:Open Source License

@Override
public boolean visit(SimpleName node) {

    ITypeBinding tbinding = node.resolveTypeBinding();

    IBinding mbinding = node.resolveBinding();
    if (mbinding instanceof IMethodBinding) {
        tbinding = ((IMethodBinding) mbinding).getDeclaringClass();
    } else if (mbinding instanceof IVariableBinding) {
        tbinding = ((IVariableBinding) mbinding).getDeclaringClass();
    }//www  .j a  va  2  s.  c  om
    //      else
    //         return true;

    if (tbinding == null)
        return true;
    //      if (mbinding == null) return true;

    // if type 2's methods and fields are found in the type 1
    if (node2.getType().getFullyQualifiedName().equals(tbinding.getQualifiedName())) {

        // draw a line between node 1 and node 2
        if (!isConnected(node1, node2)) {
            //            ConnectionNode connection = createConnectionPart(node1, node2);
            //            connection.setText("refers");
        }

        // add the methods including the methods or fields for node 1
        try {
            IJavaElement element = node1.getType().getTypeRoot().getElementAt(node.getStartPosition());

            if (element instanceof IMethod) {
                //               IType parentType = (IType) element.getAncestor(IJavaElement.TYPE);

                //               if (node1.getType().getElementName().equals(parentType.getElementName()))
                //                  node1.relMethods.put((IMethod) element, node2.getType());
            } else if (element instanceof IField) {
                //               IType parentType = (IType) element.getAncestor(IJavaElement.TYPE);

                //               if (node1.getType().getElementName().equals(parentType.getElementName()))
                //                  node1.relFields.put((IField) element, node2.getType());
            }
        } catch (JavaModelException e) {
            e.printStackTrace();
        }

        // add methods or fields for node 2
        if (mbinding instanceof IMethodBinding) {
            //            IMethod element = (IMethod) mbinding.getJavaElement();      
            //            node2.relMethods.put((IMethod) mbinding.getJavaElement(), node1.getType());
        } else if (mbinding instanceof IVariableBinding) {
            //            IField element = (IField) mbinding.getJavaElement();
            //            node2.relFields.put((IField) element, node1.getType());
        }
    }
    return super.visit(node);
}

From source file:net.sf.j2s.core.astvisitors.ASTKeywordVisitor.java

License:Open Source License

public boolean visit(VariableDeclarationFragment node) {
    SimpleName name = node.getName();
    IBinding binding = name.resolveBinding();
    if (binding != null) {
        String identifier = name.getIdentifier();
        ASTFinalVariable f = null;//from  www .  j a v a2  s. c om
        if (methodDeclareStack.size() == 0) {
            f = new ASTFinalVariable(blockLevel, identifier, null);
        } else {
            String methodSig = (String) methodDeclareStack.peek();
            f = new ASTFinalVariable(blockLevel, identifier, methodSig);
        }
        List finalVars = ((ASTVariableVisitor) getAdaptable(ASTVariableVisitor.class)).finalVars;
        List normalVars = ((ASTVariableVisitor) getAdaptable(ASTVariableVisitor.class)).normalVars;
        f.toVariableName = getIndexedVarName(identifier, normalVars.size());
        normalVars.add(f);
        if ((binding.getModifiers() & Modifier.FINAL) != 0) {
            finalVars.add(f);
        }
    }
    name.accept(this);
    Expression initializer = node.getInitializer();
    if (initializer != null) {
        buffer.append(" = ");
        ITypeBinding typeBinding = initializer.resolveTypeBinding();
        if (typeBinding != null && "char".equals(typeBinding.getName())) {
            ITypeBinding nameTypeBinding = name.resolveTypeBinding();
            String nameType = nameTypeBinding.getName();
            if (initializer instanceof CharacterLiteral) {
                CharacterLiteral cl = (CharacterLiteral) initializer;
                if ("char".equals(nameType)) {
                    String constValue = checkConstantValue(initializer);
                    buffer.append(constValue);
                } else {
                    buffer.append(0 + cl.charValue());
                }
                return false;
            } else {
                if (nameType != null && !"char".equals(nameType) && nameType.indexOf("String") == -1) {
                    int idx1 = buffer.length();
                    buffer.append("(");
                    initializer.accept(this);
                    buffer.append(")");
                    boolean appendingCode = true;
                    int length = buffer.length();
                    if (initializer instanceof MethodInvocation) {
                        MethodInvocation m = (MethodInvocation) initializer;
                        if ("charAt".equals(m.getName().toString())) {
                            int idx2 = buffer.indexOf(".charAt ", idx1);
                            if (idx2 != -1) {
                                StringBuffer newMethodBuffer = new StringBuffer();
                                newMethodBuffer.append(buffer.substring(idx1 + 1, idx2));
                                newMethodBuffer.append(".charCodeAt ");
                                newMethodBuffer.append(buffer.substring(idx2 + 8, length - 1));
                                buffer.delete(idx1, length);
                                buffer.append(newMethodBuffer.toString());
                                appendingCode = false;
                            }
                        }
                    }
                    if (appendingCode) {
                        buffer.append(".charCodeAt (0)");
                    }
                    return false;
                }
            }
        }
        ITypeBinding nameTypeBinding = name.resolveTypeBinding();
        if (nameTypeBinding != null) {
            String nameType = nameTypeBinding.getName();
            if ("char".equals(nameType)) {
                if (typeBinding != null && !"char".equals(typeBinding.getName())) {
                    buffer.append("String.fromCharCode (");
                    initializer.accept(this);
                    buffer.append(")");
                    return false;
                }
            }
        }
        boxingNode(initializer);
    }
    return false;
}

From source file:net.sf.j2s.core.astvisitors.ASTScriptVisitor.java

License:Open Source License

public boolean visit(SimpleName node) {
    String constValue = checkConstantValue(node);
    if (constValue != null) {
        buffer.append(constValue);//from w ww  .  j  a v a  2s.  co  m
        return false;
    }
    IBinding binding = node.resolveBinding();
    if (binding != null && binding instanceof ITypeBinding) {
        ITypeBinding typeBinding = (ITypeBinding) binding;
        if (typeBinding != null) {
            String name = typeBinding.getQualifiedName();
            if (name.startsWith("org.eclipse.swt.internal.xhtml.") || name.startsWith("net.sf.j2s.html.")) {
                buffer.append(node.getIdentifier());
                return false;
            }
        }
    }
    ASTNode xparent = node.getParent();
    if (xparent == null) {
        buffer.append(node);
        return false;
    }
    char ch = 0;
    if (buffer.length() > 0) {
        ch = buffer.charAt(buffer.length() - 1);
    }
    if (ch == '.' && xparent instanceof QualifiedName) {
        if (binding != null && binding instanceof IVariableBinding) {
            IVariableBinding varBinding = (IVariableBinding) binding;
            IVariableBinding variableDeclaration = varBinding.getVariableDeclaration();
            ITypeBinding declaringClass = variableDeclaration.getDeclaringClass();
            String fieldName = getJ2SName(node);
            if (checkSameName(declaringClass, fieldName)) {
                buffer.append('$');
            }
            if (checkKeyworkViolation(fieldName)) {
                buffer.append('$');
            }
            if (declaringClass != null && isInheritedFieldName(declaringClass, fieldName)) {
                fieldName = getFieldName(declaringClass, fieldName);
            }
            buffer.append(fieldName);
            return false;
        }
        buffer.append(node);
        return false;
    }
    if (xparent instanceof ClassInstanceCreation && !(binding instanceof IVariableBinding)) {
        ITypeBinding binding2 = node.resolveTypeBinding();
        if (binding != null) {
            String name = binding2.getQualifiedName();
            name = assureQualifiedName(shortenQualifiedName(name));
            buffer.append(name);
        } else {
            String nodeId = getJ2SName(node);
            buffer.append(assureQualifiedName(shortenQualifiedName(nodeId)));
        }
        return false;
    }
    if (binding == null) {
        String name = getJ2SName(node);
        name = shortenQualifiedName(name);
        if (checkKeyworkViolation(name)) {
            buffer.append('$');
        }
        buffer.append(name);
        return false;
    }
    if (binding instanceof IVariableBinding) {
        IVariableBinding varBinding = (IVariableBinding) binding;
        simpleNameInVarBinding(node, ch, varBinding);
    } else if (binding instanceof IMethodBinding) {
        IMethodBinding mthBinding = (IMethodBinding) binding;
        simpleNameInMethodBinding(node, ch, mthBinding);
    } else {
        ITypeBinding typeBinding = node.resolveTypeBinding();
        //            String name = NameConverterUtil.getJ2SName(node);
        if (typeBinding != null) {
            String name = typeBinding.getQualifiedName();
            name = assureQualifiedName(shortenQualifiedName(name));
            if (checkKeyworkViolation(name)) {
                buffer.append('$');
            }
            buffer.append(name);
        } else {
            String name = node.getFullyQualifiedName();
            if (checkKeyworkViolation(name)) {
                buffer.append('$');
            }
            buffer.append(name);
        }
    }
    return false;
}

From source file:net.sf.j2s.core.astvisitors.DependencyASTVisitor.java

License:Open Source License

public boolean visit(SimpleName node) {
    Object constValue = node.resolveConstantExpressionValue();
    if (constValue != null && (constValue instanceof Number || constValue instanceof Character
            || constValue instanceof Boolean)) {
        return false;
    }/*from  w w w  . jav a2  s .  co  m*/
    ITypeBinding typeBinding = node.resolveTypeBinding();
    IBinding binding = node.resolveBinding();
    boolean isCasting = false;
    boolean isQualified = false;
    ASTNode nodeParent = node.getParent();
    while (nodeParent != null && nodeParent instanceof QualifiedName) {
        isQualified = true;
        nodeParent = nodeParent.getParent();
    }
    if (nodeParent != null && nodeParent instanceof SimpleType) {
        isCasting = true;
    }
    if (typeBinding != null && !isCasting && isQualified && !(binding instanceof IVariableBinding)) {
        QNTypeBinding qn = new QNTypeBinding();
        String qualifiedName = null;
        if (!typeBinding.isPrimitive()) {
            if (typeBinding.isArray()) {
                ITypeBinding elementType = typeBinding.getElementType();
                while (elementType.isArray()) {
                    elementType = elementType.getElementType();
                }
                if (!elementType.isPrimitive()) {
                    ITypeBinding declaringClass = elementType.getDeclaringClass();
                    if (declaringClass != null) {
                        ITypeBinding dclClass = null;
                        while ((dclClass = declaringClass.getDeclaringClass()) != null) {
                            declaringClass = dclClass;
                        }
                        qualifiedName = declaringClass.getQualifiedName();
                        qn.binding = declaringClass;
                    } else {
                        qualifiedName = elementType.getQualifiedName();
                        qn.binding = elementType;
                    }
                }
            } else {
                ITypeBinding declaringClass = typeBinding.getDeclaringClass();
                if (declaringClass != null) {
                    ITypeBinding dclClass = null;
                    while ((dclClass = declaringClass.getDeclaringClass()) != null) {
                        declaringClass = dclClass;
                    }
                    qualifiedName = declaringClass.getQualifiedName();
                    qn.binding = declaringClass;
                } else {
                    qualifiedName = typeBinding.getQualifiedName();
                    qn.binding = typeBinding;
                }
            }
        }
        if (isQualifiedNameOK(qualifiedName, node) && !musts.contains(qualifiedName)
                && !requires.contains(qualifiedName)) {
            qn.qualifiedName = qualifiedName;
            optionals.add(qn);
        }
    } else if (binding instanceof IVariableBinding) {
        IVariableBinding varBinding = (IVariableBinding) binding;
        if ((varBinding.getModifiers() & Modifier.STATIC) != 0) {
            QNTypeBinding qn = new QNTypeBinding();
            String qualifiedName = null;

            IVariableBinding variableDeclaration = varBinding.getVariableDeclaration();
            ITypeBinding declaringClass = variableDeclaration.getDeclaringClass();

            ITypeBinding dclClass = null;
            while ((dclClass = declaringClass.getDeclaringClass()) != null) {
                declaringClass = dclClass;
            }
            qualifiedName = declaringClass.getQualifiedName();
            if (isQualifiedNameOK(qualifiedName, node) && !musts.contains(qualifiedName)
                    && !requires.contains(qualifiedName)) {
                qn.qualifiedName = qualifiedName;
                optionals.add(qn);
            }

        }

    }
    return super.visit(node);
}