Example usage for org.eclipse.jdt.core.dom ITypeBinding isSubTypeCompatible

List of usage examples for org.eclipse.jdt.core.dom ITypeBinding isSubTypeCompatible

Introduction

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

Prototype

public boolean isSubTypeCompatible(ITypeBinding type);

Source Link

Document

Returns whether this type is subtype compatible with the given type, as specified in section 4.10 of The Java Language Specification, Third Edition (JLS3).

Usage

From source file:cideplus.ui.astview.TrayContentProvider.java

License:Open Source License

private void addTypeBindingComparions(ArrayList result, Binding trayElement) {
    class IsSubTypeCompatibleProperty extends DynamicBindingProperty {
        public IsSubTypeCompatibleProperty(Binding parent) {
            super(parent);
        }//from w  ww.j a v  a  2s  . c o m

        protected String getName() {
            return "*.isSubTypeCompatible(this): "; //$NON-NLS-1$
        }

        protected String executeQuery(IBinding viewerBinding, IBinding trayBinding) {
            if (viewerBinding instanceof ITypeBinding) {
                ITypeBinding viewerTB = (ITypeBinding) viewerBinding;
                ITypeBinding trayTB = (ITypeBinding) trayBinding;
                return Boolean.toString(viewerTB.isSubTypeCompatible(trayTB));
            } else {
                return "* not an ITypeBinding"; //$NON-NLS-1$
            }
        }
    }
    result.add(new IsSubTypeCompatibleProperty(trayElement));

    class IsCastCompatibleProperty extends DynamicBindingProperty {
        public IsCastCompatibleProperty(Binding parent) {
            super(parent);
        }

        protected String getName() {
            return "*.isCastCompatible(this): "; //$NON-NLS-1$
        }

        protected String executeQuery(IBinding viewerBinding, IBinding trayBinding) {
            if (viewerBinding instanceof ITypeBinding) {
                ITypeBinding viewerTB = (ITypeBinding) viewerBinding;
                ITypeBinding trayTB = (ITypeBinding) trayBinding;
                return Boolean.toString(viewerTB.isCastCompatible(trayTB));
            } else {
                return "* not an ITypeBinding"; //$NON-NLS-1$
            }
        }
    }
    result.add(new IsCastCompatibleProperty(trayElement));

    class IsAssignmentCompatibleProperty extends DynamicBindingProperty {
        public IsAssignmentCompatibleProperty(Binding parent) {
            super(parent);
        }

        protected String getName() {
            return "*.isAssignmentCompatible(this): "; //$NON-NLS-1$
        }

        protected String executeQuery(IBinding viewerBinding, IBinding trayBinding) {
            if (viewerBinding instanceof ITypeBinding) {
                ITypeBinding viewerTB = (ITypeBinding) viewerBinding;
                ITypeBinding trayTB = (ITypeBinding) trayBinding;
                return Boolean.toString(viewerTB.isAssignmentCompatible(trayTB));
            } else {
                return "* not an ITypeBinding"; //$NON-NLS-1$
            }
        }
    }
    result.add(new IsAssignmentCompatibleProperty(trayElement));
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Determines whether one type is return-type-substitutable by another, as
 * determined by the Java Language Specification 3.0, section 8.4.5.
 *//*w w w  .j av a2  s  .co  m*/
private static final Predicate<ITypeBinding> isSubstitutableBy(final ITypeBinding subtype) {
    return new Predicate<ITypeBinding>() {
        @Override
        public boolean apply(ITypeBinding supertype) {
            // http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#296201
            return subtype.isPrimitive() && subtype.isEqualTo(supertype)
                    || subtype.isSubTypeCompatible(supertype) || subtype.isEqualTo(supertype.getErasure())
                    || subtype.getName().equals("void") && supertype.getName().equals("void");
        }
    };
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Determines whether an overriding method has a throws clause that does not
 * conflict with the throws clause of another method, as determined by JLS3,
 * section 8.4.6./*w w w  .jav  a 2 s .  c  om*/
 */
private boolean compatibleThrowsClauses(IMethodBinding overrider, IMethodBinding overridee) {
    for (ITypeBinding type1 : overrider.getExceptionTypes()) {
        // Overriding methods can only declare all or a subset of the checked
        // exceptions declared by the overridden method.  Therefore, each
        // exception declared by the overriding method must be equal to or a
        // subtype of an exception declared by the overridden method.
        // http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#308526
        boolean present = false;
        for (ITypeBinding type2 : overridee.getExceptionTypes()) {
            if (type1.isSubTypeCompatible(type2)) {
                present = true;
                break;
            }
        }
        if (!present) {
            return false;
        }
    }
    return true;
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

/**
 * Populate children, starting at index 2, for the invocation of methodBinding. If varargs are used this function will collapse
 * the proper arguments into an array.//from   ww  w  . j  a  v  a  2 s  .c o  m
 * 
 * If the number of actuals equals the number of formals and the function is varargs, we have to check the type of the last
 * argument to see if we should "box" it in an array. If the arguments[arguments.length-1] is not an Expression, we cannot get the
 * type, so we do not box it. (Making covariant varargs functions require this behavior)
 * 
 * @param children
 * @param methodBinding
 * @param arguments
 * @param context
 */
private void populateArguments(CAstNode[] children, IMethodBinding methodBinding,
        List/* CAstNode or Expression */ arguments, WalkContext context) {
    int nFormals = methodBinding.getParameterTypes().length;
    assert children.length == nFormals + 2;
    int nActuals = arguments.size();

    ITypeBinding lastArgType = null;
    if (nActuals > 0 && arguments.get(nActuals - 1) instanceof Expression)
        lastArgType = ((Expression) arguments.get(nActuals - 1)).resolveTypeBinding();
    // if the # of actuals equals the # of formals, AND the function is varargs, we have to check
    // to see if the lastArgType is subtype compatible with the type of last parameter (which will be an array).
    // If it is, we pass this array in directly. Otherwise this it is wrapped in an array init.
    // Example: 'void foo(int... x)' can be run via 'foo(5)' or 'foo(new int[] { 5, 6 })' -- both have one argument so we must check
    // the type

    if (nActuals == nFormals && (!methodBinding.isVarargs() || lastArgType == null
            || lastArgType.isSubTypeCompatible(methodBinding.getParameterTypes()[nFormals - 1]))) {
        int i = 2;
        for (Object arg : arguments)
            children[i++] = (arg instanceof CAstNode) ? ((CAstNode) arg) : visitNode((Expression) arg, context);
    } else {
        assert nActuals >= (nFormals - 1)
                && methodBinding.isVarargs() : "Invalid number of parameters for constructor call";
        for (int i = 0; i < nFormals - 1; i++) {
            Object arg = arguments.get(i);
            children[i + 2] = (arg instanceof CAstNode) ? ((CAstNode) arg)
                    : visitNode((Expression) arg, context);
        }

        CAstNode subargs[] = new CAstNode[nActuals - nFormals + 2];
        // nodes for args and one extra for NEW expression
        TypeReference newTypeRef = fIdentityMapper.getTypeRef(methodBinding.getParameterTypes()[nFormals - 1]);
        subargs[0] = makeNode(context, fFactory, null, CAstNode.NEW, fFactory.makeConstant(newTypeRef),
                fFactory.makeConstant(subargs.length - 1));
        for (int j = 1; j < subargs.length; j++) {
            Object arg = arguments.get(j + nFormals - 2);
            subargs[j] = (arg instanceof CAstNode) ? ((CAstNode) arg) : visitNode((Expression) arg, context);
        }
        children[nFormals + 1] = makeNode(context, fFactory, (ASTNode) null, CAstNode.ARRAY_LITERAL, subargs);
    }
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

/**
 * Sees if a field defined in owningTypeRef is contained & accessible to a type of typeOfThis. That is, if owningTypeRef ==
 * typeOfThis or typeOfThis is a subtype and isPrivate is false. If this is not that case, looks in the enclosing class of
 * typeOfThis and tries again, and its enclosing class, ...
 * // w ww.  j a va  2 s. c o m
 * Essentially if we have a field/method referenced only by name and we know its type (owningTypeRef), this function will return
 * owningTypeRef or the subtype that the field is accessed thru, for expanding "f = 5" into "TheClass.this.f = 5".
 * 
 * @param typeOfThis
 * @param owningTypeRef
 * @param isPrivate
 * @return
 */
private ITypeBinding findClosestEnclosingClassSubclassOf(ITypeBinding typeOfThis, ITypeBinding owningType,
        boolean isPrivate) {
    // GENERICS
    //    if (owningType.isParameterizedType())
    //      owningType = owningType.getTypeDeclaration();
    //    if (typeOfThis.isParameterizedType())
    //      typeOfThis = typeOfThis.getTypeDeclaration();
    //    // typeOfThis.getTypeDeclaration()
    owningType = owningType.getErasure();

    ITypeBinding current = typeOfThis;
    while (current != null) {
        current = current.getErasure();
        // Walk the hierarchy rather than using isSubTypeCompatible to handle
        // generics -- we need to perform erasure of super types
        boolean isInSubtype = false;//current.isSubTypeCompatible(owningType);
        ITypeBinding supertp = current;
        while (supertp != null) {
            supertp = supertp.getErasure();
            // Use isSubTypeCompatible even though we are manually walking type hierarchy --
            // that way interfaces are handled without us having to do it manually.
            if (supertp.isSubTypeCompatible(owningType)) {
                isInSubtype = true;
                break;
            }
            supertp = supertp.getSuperclass();
        }

        // how could it be in the subtype and private? this only happens the supertype is also an
        // enclosing type. in that case the variable refers to the field in the enclosing instance.

        if (current.isEqualTo(owningType) || (isInSubtype && !isPrivate))
            return current;

        current = current.getDeclaringClass();
    }

    Assertions.UNREACHABLE("Couldn't find field in class or enclosing class or superclasses of these");
    return null;
}

From source file:edu.cmu.cs.crystal.cfg.ExceptionMap.java

License:Open Source License

/**
 * @param exception//from  w w  w  . j av  a 2 s .c om
 *            An exception to find a catch node for, considering subtyping
 * @return the catch node that will catch this exception, or null if one could not be found
 */
public Node getCatchNode(ITypeBinding exception) {
    for (int ndx = catchStack.size() - 1; ndx >= 0; ndx--) {
        CatchBlock block = catchStack.get(ndx);
        if (exception != null && exception.isSubTypeCompatible(block.exception))
            return block.catchNode;
    }
    return null;
}

From source file:edu.cmu.cs.crystal.cfg.ExceptionMap.java

License:Open Source License

/**
 * Returns a stack of nodes that are the finally nodes up to the exception. This will not
 * include the finally node at the exception catch. The returned stack will be that the nearest
 * finally is at the top of the stack. If the exception is null, then this returns the entire
 * stack of nodes./*from  w  w w.  j  av  a  2  s . c  om*/
 * 
 * @param exceptionToStopAt
 *            The exception we should stop at. This might be a subtype of the actual exception
 *            that we stop at.
 * @return The stack to the exception point, or the entire stack if the exception is null.
 */
public Stack<Node> getFinallyToException(ITypeBinding exceptionToStopAt) {
    Stack<Node> newStack = new Stack<Node>();
    CatchBlock block = null;

    if (exceptionToStopAt == null)
        return (Stack<Node>) finallyStack.clone();

    for (int ndx = catchStack.size() - 1; ndx >= 0; ndx--) {
        block = catchStack.get(ndx);
        if (exceptionToStopAt.isSubTypeCompatible(block.exception))
            break;
    }

    int ndx = 0;

    if (block.finallyNode == null)
        ndx = 0;
    else
        ndx = finallyStack.size() - finallyStack.search(block.finallyNode) + 1;

    for (Node node : finallyStack.subList(ndx, finallyStack.size()))
        newStack.push(node);

    return newStack;
}

From source file:edu.cmu.cs.plural.states.StateSpaceRepository.java

License:Open Source License

/**
 * <b>Return value is useless if <code>shortCicuit</code> is false.</b>
 * @param type/*from   ww  w  .ja va 2s.c om*/
 * @param overriding
 * @param seen
 * @param result
 * @param shortCircuit
 * @param skipGivenType
 * @return <b>useless if <code>shortCicuit</code> is false</b>; otherwise,
 * indicates whether a method was found (<code>result</code> set is non-empty).
 */
private boolean findOverriddenMethodsWithSpecification(ITypeBinding type, IMethodBinding overriding,
        Set<ITypeBinding> seen, Set<IMethodBinding> result, boolean shortCircuit, boolean skipGivenType) {
    if (type == null || seen.add(type) == false)
        return false;

    if (!skipGivenType) {
        next_method: for (IMethodBinding m : type.getDeclaredMethods()) {
            if (overriding.isSubsignature(m)) {
                if (hasSpecification(m)) {
                    for (Iterator<IMethodBinding> it = result.iterator(); it.hasNext();) {
                        IMethodBinding other = it.next();
                        ITypeBinding otherType = other.getDeclaringClass();
                        if (type.isSubTypeCompatible(otherType))
                            // will replace other with m in the result set
                            it.remove();
                        else if (otherType.isSubTypeCompatible(type))
                            // ignore m in favor of other
                            continue next_method;
                    }
                    result.add(m);
                    if (shortCircuit)
                        return true;
                }
            }
        }
    }

    // 2.1 search the superclass, if any
    if (type.isClass()) {
        if (findOverriddenMethodsWithSpecification(type.getSuperclass(), overriding, seen, result, shortCircuit,
                false) && shortCircuit)
            return true;
    }
    // 2.2 search interfaces, if any
    for (ITypeBinding t : type.getInterfaces()) {
        if (findOverriddenMethodsWithSpecification(t, overriding, seen, result, shortCircuit, false)
                && shortCircuit)
            return true;
    }

    // 3. nothing
    return false;
}

From source file:edu.virginia.aid.visitors.ControlFlowGraphVisitor.java

License:Apache License

private void handleTryCatchFinally(Statement stmt) {
    // does this statement throw any checked exceptions?
    final Set<ITypeBinding> exceptions = new HashSet<ITypeBinding>();
    stmt.accept(new ASTVisitor() {
        @Override/*from w  w  w.  j  a  v  a  2 s  .c  om*/
        public boolean visit(MethodInvocation node) {
            IMethodBinding binding = node.resolveMethodBinding();
            if (binding != null) {
                for (ITypeBinding itb : binding.getExceptionTypes()) {
                    if (isCheckedException(itb)) {
                        exceptions.add(itb);
                    }
                }
            }
            return true;
        }
    });
    // if this statement does not throw any exceptions, 
    // no extra edges are necessary
    if (exceptions.size() == 0)
        return;
    // move from top to bottom of stack and remove exceptions
    // as they are caught by catch clauses. Add edges on the way
    // while observing a ny intermediate finally-clauses
    int index = tryStack.size() - 1;
    //List<Block> finallyBlocks = new ArrayList<Block>();
    while (index >= 0) {
        TryStatement tryStmt = tryStack.get(index);
        for (int j = 0; j < tryStmt.catchClauses().size(); j++) {
            CatchClause clause = (CatchClause) tryStmt.catchClauses().get(j);
            SingleVariableDeclaration svd = clause.getException();
            ITypeBinding caught = svd.getType().resolveBinding();
            // ignore unchecked exceptions
            if (!isCheckedException(caught))
                continue;
            Set<ITypeBinding> caughtExceptions = new HashSet<ITypeBinding>();
            // iterate through thrown exceptions and 
            // check if they catch this exception
            for (ITypeBinding thrown : exceptions) {
                if (thrown.isSubTypeCompatible(caught)) {
                    // note this exception, so it can be filtered out on next iteration
                    caughtExceptions.add(thrown);
                    // what succeeds this try-stmt
                    Statement next = try2Successor.get(tryStmt);
                    // add extra edges for intermediate finally-blocks
                    Statement beginning = stmt;
                    for (int k = tryStack.size() - 1; k > index; k--) {
                        TryStatement intermediate = tryStack.get(k);
                        if (intermediate.getFinally() != null
                                && !intermediate.getFinally().statements().isEmpty()) {
                            addEdge(beginning, first(intermediate.getFinally().statements()));
                            beginning = last(intermediate.getFinally().statements());
                        }
                    }
                    // add edge into catch clause
                    if (!clause.getBody().statements().isEmpty()) {
                        addEdge(beginning, first(clause.getBody().statements()));
                        // add edge into finally clause
                        if (tryStmt.getFinally() != null && !tryStmt.getFinally().statements().isEmpty()) {
                            // case 1: non-empty catch and non-empty finally
                            addEdge(last(clause.getBody().statements()),
                                    first(tryStmt.getFinally().statements()));
                            addEdge(last(tryStmt.getFinally().statements()), next);
                        } else {
                            // case 2: non-empty catch and empty finally
                            addEdge(last(clause.getBody().statements()), next);
                        }
                    } else {
                        // add edge into finally clause
                        if (tryStmt.getFinally() != null && !tryStmt.getFinally().statements().isEmpty()) {
                            // case 3: empty catch and non-empty finally
                            addEdge(beginning, first(tryStmt.getFinally().statements()));
                            addEdge(last(tryStmt.getFinally().statements()), next);
                        } else {
                            // case 4: empty catch and empty finally
                            addEdge(beginning, next);
                        }
                    }

                }
            }
            // remove exceptions as they are caught
            // cannot be done inside loop
            exceptions.removeAll(caughtExceptions);
        }
        index--;
    }
}

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

License:Open Source License

private static boolean areSubTypeCompatible(IMethodBinding overridden, IMethodBinding overridable) {

    if (overridden.getParameterTypes().length != overridable.getParameterTypes().length)
        return false;

    ITypeBinding overriddenReturn = overridden.getReturnType();
    ITypeBinding overridableReturn = overridable.getReturnType();
    if (overriddenReturn == null || overridableReturn == null)
        return false;

    if (!overriddenReturn.getErasure().isSubTypeCompatible(overridableReturn.getErasure()))
        return false;

    ITypeBinding[] overriddenTypes = overridden.getParameterTypes();
    ITypeBinding[] overridableTypes = overridable.getParameterTypes();
    Assert.isTrue(overriddenTypes.length == overridableTypes.length);
    for (int index = 0; index < overriddenTypes.length; index++) {
        final ITypeBinding overridableErasure = overridableTypes[index].getErasure();
        final ITypeBinding overriddenErasure = overriddenTypes[index].getErasure();
        if (!overridableErasure.isSubTypeCompatible(overriddenErasure)
                || !overridableErasure.getKey().equals(overriddenErasure.getKey()))
            return false;
    }//ww w .j  a  v a2s . c  om
    ITypeBinding[] overriddenExceptions = overridden.getExceptionTypes();
    ITypeBinding[] overridableExceptions = overridable.getExceptionTypes();
    boolean checked = false;
    for (int index = 0; index < overriddenExceptions.length; index++) {
        checked = false;
        for (int offset = 0; offset < overridableExceptions.length; offset++) {
            if (overriddenExceptions[index].isSubTypeCompatible(overridableExceptions[offset]))
                checked = true;
        }
        if (!checked)
            return false;
    }
    return true;
}