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

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

Introduction

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

Prototype

public boolean isEqualTo(IBinding binding);

Source Link

Document

Returns whether this binding has the same key as that of the given binding.

Usage

From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java

License:Open Source License

private IMethodBinding findReferenceMethod(ITypeBinding componentClass, ITypeBinding serviceType, String name) {
    ITypeBinding testedClass = componentClass;

    IMethodBinding candidate = null;/*from   ww w  .j ava2s .c om*/
    int priority = 0;
    // priority:
    // 0: <assignment-compatible-type>, Map
    // 1: <exact-type>, Map
    // 2: <assignment-compatible-type>
    // 3: <exact-type>
    do {
        for (IMethodBinding declaredMethod : testedClass.getDeclaredMethods()) {
            if (name.equals(declaredMethod.getName())
                    && Void.TYPE.getName().equals(declaredMethod.getReturnType().getName())
                    && (testedClass.isEqualTo(componentClass)
                            || Modifier.isPublic(declaredMethod.getModifiers())
                            || Modifier.isProtected(declaredMethod.getModifiers())
                            || (!Modifier.isPrivate(declaredMethod.getModifiers())
                                    && testedClass.getPackage().isEqualTo(componentClass.getPackage())))) {
                ITypeBinding[] paramTypes = declaredMethod.getParameterTypes();
                if (paramTypes.length == 1) {
                    if (ServiceReference.class.getName().equals(paramTypes[0].getErasure().getQualifiedName()))
                        // we have the winner
                        return declaredMethod;

                    if (priority < 3 && serviceType.isEqualTo(paramTypes[0]))
                        priority = 3;
                    else if (priority < 2 && serviceType.isAssignmentCompatible(paramTypes[0]))
                        priority = 2;
                    else
                        continue;

                    // we have a (better) candidate
                    candidate = declaredMethod;
                } else if (paramTypes.length == 2) {
                    if (priority < 1 && serviceType.isEqualTo(paramTypes[0])
                            && Map.class.getName().equals(paramTypes[1].getErasure().getQualifiedName()))
                        priority = 1;
                    else if (candidate != null || !serviceType.isAssignmentCompatible(paramTypes[0])
                            || !Map.class.getName().equals(paramTypes[1].getErasure().getQualifiedName()))
                        continue;

                    // we have a candidate
                    candidate = declaredMethod;
                }
            }
        }
    } while ((testedClass = testedClass.getSuperclass()) != null);

    return candidate;
}

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

License:Open Source License

public void makeSafeSecondary(ASTNode node, TypeFact typeFact) {
    SimpleName sName = (SimpleName) node;
    PPATypeRegistry typeRegistry = ppaEngine.getRegistry();
    PPADefaultBindingResolver resolver = getResolver(sName);
    ASTNode newContainerNode = PPAASTUtil.getFieldContainer(node, true, false);
    ITypeBinding newContainer = PPABindingsUtil.getTypeBinding(newContainerNode);

    if (newContainer == null) {
        return;//from  www  .j  av a  2 s .c  o  m
    }

    IVariableBinding varBinding = (IVariableBinding) sName.resolveBinding();
    IVariableBinding newFieldBinding = null;

    if (PPABindingsUtil.isMissingType(newContainer)) {
        newFieldBinding = typeRegistry.getFieldBinding(varBinding.getName(), newContainer, varBinding.getType(),
                resolver);
    } else {
        // Maybe we can find the field declaration
        newFieldBinding = PPABindingsUtil.findFieldHierarchy(newContainer, sName.getFullyQualifiedName());
        if (newFieldBinding == null) {
            // We did not find the field in the container, try to find a suitable container (missing type)
            ITypeBinding tempContainer = PPABindingsUtil.getFirstMissingSuperType(newContainer);
            if (tempContainer != null) {
                newContainer = tempContainer;
                newFieldBinding = typeRegistry.getFieldBinding(varBinding.getName(), newContainer,
                        varBinding.getType(), resolver);
            } else {
                newFieldBinding = typeRegistry.getFieldBinding(varBinding.getName(), newContainer,
                        varBinding.getType(), resolver);
            }
        } else {
            // In case we found the field in a super type of the container.
            newContainer = newFieldBinding.getDeclaringClass();
        }
    }

    // Check field type
    ITypeBinding newFieldType = newFieldBinding.getType();
    ITypeBinding oldFieldType = varBinding.getType();
    if (!newFieldType.isEqualTo(oldFieldType)) {
        if (PPABindingsUtil.isSafer(newFieldType, oldFieldType)) {
            resolver.fixFieldBinding(sName, newFieldBinding);
            TypeFact tFact = new TypeFact(indexer.getMainIndex(sName), oldFieldType, TypeFact.UNKNOWN,
                    newFieldType, TypeFact.EQUALS, TypeFact.FIELD_STRATEGY);
            ppaEngine.reportTypeFact(tFact);

        } else if (!PPABindingsUtil.isMissingType(newContainer)) {
            resolver.fixFieldBinding(sName, newFieldBinding);
            // This is the case where we found the field declaration and the field is "less" safe than the previous type.
            // XXX The oldType = Unknown is to ensure that the new type will be pushed.
            TypeFact tFact = new TypeFact(indexer.getMainIndex(sName), typeRegistry.getUnknownBinding(resolver),
                    TypeFact.UNKNOWN, newFieldType, TypeFact.EQUALS, TypeFact.FIELD_STRATEGY);
            ppaEngine.reportTypeFact(tFact);
        } else {
            // This is an odd case: we found a ppa generated field, but the type we got before was safer.
            newFieldBinding = typeRegistry.getFieldBindingWithType(varBinding.getName(), newContainer,
                    varBinding.getType(), resolver);
            resolver.fixFieldBinding(sName, newFieldBinding);
        }
    } else {
        resolver.fixFieldBinding(sName, newFieldBinding);
    }

}

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

License:Open Source License

public void makeSafe(ASTNode node, TypeFact typeFact) {
    QualifiedName qName = (QualifiedName) node;
    Name right = qName.getName();

    if (qNameChanged(node, typeFact)) {
        if (!indexer.isSafe(right)) {
            ITypeBinding oldBinding = typeFact.getOldType();
            ITypeBinding newBinding = typeFact.getNewType();
            ITypeBinding rightBinding = getRightBinding(right);
            if (rightBinding == null || !rightBinding.isEqualTo(newBinding)) {
                TypeFact tFact = new TypeFact(indexer.getMainIndex(right), oldBinding,
                        typeFact.getOldDirection(), newBinding, typeFact.getNewDirection(),
                        typeFact.getStrategy());
                ppaEngine.reportTypeFact(tFact);
            }//from   w w  w  .  j a  v a  2  s.  com
        }
        // } else if (nameChanged(node, typeFact)) {
    }
    // else {
    //         
    // }
}

From source file:com.google.devtools.j2cpp.gen.CppImplementationGenerator.java

License:Open Source License

private void printProperties(FieldDeclaration[] fields) {
    int nPrinted = 0;
    for (FieldDeclaration field : fields) {
        if ((field.getModifiers() & Modifier.STATIC) == 0) {
            @SuppressWarnings("unchecked")
            List<VariableDeclarationFragment> vars = field.fragments(); // safe by definition
            for (VariableDeclarationFragment var : vars) {
                if (var.getName().getIdentifier().startsWith("this$") && superDefinesVariable(var)) {
                    // Don't print, as it shadows an inner field in a super class.
                    continue;
                }/*w  w w .j  a  va2  s  .c o  m*/

                String name = NameTable.getName(var.getName());
                ITypeBinding type = Types.getTypeBinding(field.getType());
                String typeString = NameTable.javaRefToCpp(type);
                if (!typeString.endsWith("*")) {
                    typeString += " ";
                }

                // Don't emit the getter when there is already a method with the
                // same name.
                // TODO(user,user): Update when getters are merged with property
                // accessors (see issues).
                boolean noGetter = false;
                ITypeBinding declaringClass = Types.getTypeBinding(field.getParent());
                if (declaringClass != null) {
                    IMethodBinding[] methods = declaringClass.getDeclaredMethods();
                    for (IMethodBinding method : methods) {
                        if (method.getName().equals(name) && method.getParameterTypes().length == 0) {
                            noGetter = true;
                            break;
                        }
                    }
                }

                String objCFieldName = NameTable.javaFieldToCpp(name);

                // Getter
                if (!noGetter) {
                    printf(String.format("- (%s)%s {\n  return %s;\n}\n\n", typeString.trim(), name,
                            objCFieldName));
                }

                // Setter
                printf(String.format("- (void)set%s:(%s)new%s {\n", NameTable.capitalize(name),
                        typeString.trim(), NameTable.capitalize(name)));
                if (type.isPrimitive()) {
                    printf(String.format("  %s = new%s;\n}\n\n", objCFieldName, NameTable.capitalize(name)));
                } else if (Options.useReferenceCounting()
                        && !Types.isWeakReference(Types.getVariableBinding(var))) {
                    String retentionMethod = type.isEqualTo(Types.getNSString()) ? "copy" : "retain";
                    printf(String.format("  [%s autorelease];\n  %s = [new%s %s];\n}\n\n", objCFieldName,
                            objCFieldName, NameTable.capitalize(name), retentionMethod));
                } else {
                    printf(String.format("  %s = new%s;\n}\n\n", objCFieldName, NameTable.capitalize(name)));
                }
                nPrinted++;
            }
        }
    }
    if (nPrinted > 0) {
        newline();
    }
}

From source file:com.google.devtools.j2cpp.gen.CppStatementGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  w  w  w.ja  v  a2  s.co  m*/
public boolean visit(InfixExpression node) {
    InfixExpression.Operator op = node.getOperator();
    ITypeBinding type = Types.getTypeBinding(node);
    if (Types.isJavaStringType(type) && op.equals(InfixExpression.Operator.PLUS)) {
        printStringConcatenation(node.getLeftOperand(), node.getRightOperand(), node.extendedOperands(), false);
    } else if (op.equals(InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED)) {
        printUnsignedRightShift(node.getLeftOperand(), node.getRightOperand());
    } else if (op.equals(InfixExpression.Operator.REMAINDER) && isFloatingPoint(node)) {
        buffer.append(type.isEqualTo(node.getAST().resolveWellKnownType("float")) ? "fmodf" : "fmod");
        buffer.append('(');
        node.getLeftOperand().accept(this);
        buffer.append(", ");
        node.getRightOperand().accept(this);
        buffer.append(')');
    } else {
        node.getLeftOperand().accept(this);
        buffer.append(' ');
        buffer.append(node.getOperator().toString());
        buffer.append(' ');
        node.getRightOperand().accept(this);
        final List<Expression> extendedOperands = node.extendedOperands();
        if (extendedOperands.size() != 0) {
            buffer.append(' ');
            for (Iterator<Expression> it = extendedOperands.iterator(); it.hasNext();) {
                buffer.append(node.getOperator().toString()).append(' ');
                it.next().accept(this);
            }
        }
    }
    return false;
}

From source file:com.google.devtools.j2cpp.gen.CppStatementGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  w  ww . j a  va 2s  .  c  o  m*/
public boolean visit(MethodInvocation node) {
    invocations.push(node);
    String methodName = NameTable.getName(node.getName());
    IMethodBinding binding = Types.getMethodBinding(node);
    assert binding != null;
    // Object receiving the message, or null if it's a method in this class.
    Expression receiver = node.getExpression();
    ITypeBinding receiverType = receiver != null ? Types.getTypeBinding(receiver) : null;
    buffer.append(' ');
    if ((receiverType != null) && (receiver instanceof SimpleName)) {
        buffer.append(((SimpleName) receiver).getIdentifier()).append('.');
    }
    if (Types.isFunction(binding)) {
        buffer.append(methodName);
        buffer.append("(");
        for (Iterator<Expression> it = node.arguments().iterator(); it.hasNext();) {
            it.next().accept(this);
            if (it.hasNext()) {
                buffer.append(", ");
            }
        }
        buffer.append(")");
    } else {
        boolean castAttempted = false;
        boolean castReturnValue = false;
        if (node.getParent() instanceof Expression || node.getParent() instanceof ReturnStatement
                || node.getParent() instanceof VariableDeclarationFragment) {
            ITypeBinding actualType = binding.getMethodDeclaration().getReturnType();
            if (actualType.isArray()) {
                actualType = Types.resolveArrayType(actualType.getComponentType());
            }
            ITypeBinding expectedType;
            if (node.getParent() instanceof VariableDeclarationFragment) {
                expectedType = Types.getTypeBinding(node.getParent());
            } else {
                expectedType = binding.getReturnType();
            }
            if (expectedType.isArray()) {
                expectedType = Types.resolveArrayType(expectedType.getComponentType());
            }
            if (!actualType.isAssignmentCompatible(expectedType)) {
                if (!actualType.isEqualTo(node.getAST().resolveWellKnownType("void"))) {
                    // Since type parameters aren't passed to Obj-C, add cast for it.
                    // However, this is only needed with nested invocations.
                    if (invocations.size() > 0) {
                        // avoid a casting again below, and know to print a closing ')'
                        // after the method invocation.
                        castReturnValue = printCast(expectedType);
                        castAttempted = true;
                    }
                }
            }
        }
        ITypeBinding typeBinding = binding.getDeclaringClass();

        if (receiver != null) {
            boolean castPrinted = false;
            IMethodBinding methodReceiver = Types.getMethodBinding(receiver);
            if (methodReceiver != null) {
                if (methodReceiver.isConstructor()) {
                    // gcc sometimes fails to discern the constructor's type when
                    // chaining, so add a cast.
                    if (!castAttempted) {
                        castPrinted = printCast(typeBinding);
                        castAttempted = true;
                    }
                } else {
                    ITypeBinding receiverReturnType = methodReceiver.getReturnType();
                    if (receiverReturnType.isInterface()) {
                        // Add interface cast, so Obj-C knows the type node's receiver is.
                        if (!castAttempted) {
                            castPrinted = printCast(receiverReturnType);
                            castAttempted = true;
                        }
                    }
                }
            } else {
                IVariableBinding var = Types.getVariableBinding(receiver);
                if (var != null) {
                    if (Types.variableHasCast(var)) {
                        castPrinted = printCast(Types.getCastForVariable(var));
                    }
                }
            }
            //        printNilCheck(receiver, !castPrinted);
            if (castPrinted) {
                buffer.append(')');
            }
        } else {
            //        if ((binding.getModifiers() & Modifier.STATIC) > 0) {
            //          buffer.append(NameTable.getFullName(typeBinding));
            //        } else {
            //          buffer.append("self");
            //        }
        }
        if (binding instanceof IOSMethodBinding) {
            buffer.append(binding.getName());
        } else {
            buffer.append(methodName);
        }
        buffer.append("(");
        printArguments(binding, node.arguments());
        buffer.append(")");
        if (castReturnValue) {
            buffer.append(')');
        }
    }
    invocations.pop();
    return false;
}

From source file:com.google.devtools.j2cpp.gen.CppStatementGenerator.java

License:Open Source License

/**
 * Returns true if the caller should reference a static variable using its
 * accessor methods.//w ww  . j av a2  s.  c o m
 */
private boolean useStaticPublicAccessor(ASTNode expression, ITypeBinding owningType) {
    MethodDeclaration method = getOwningMethod(expression);
    if (method != null) {
        // Functions should always use public accessor, to trigger the var's
        // class loading if it hasn't happened yet.
        if (Types.isFunction(Types.getMethodBinding(method))) {
            return true;
        }
    }
    IVariableBinding var = Types.getVariableBinding(expression);
    return !owningType.isEqualTo(var.getDeclaringClass().getTypeDeclaration());
}

From source file:com.google.devtools.j2cpp.gen.CppStatementGenerator.java

License:Open Source License

@Override
public boolean visit(ReturnStatement node) {
    buffer.append("return");
    Expression expr = node.getExpression();
    if (expr != null) {
        buffer.append(' ');
        boolean needsCast = false;
        ITypeBinding expressionType = Types.getTypeBinding(expr);
        IBinding binding = Types.getBinding(expr);
        if (expr instanceof SuperMethodInvocation) {
            needsCast = true;//from  ww w.  j av  a2 s  .  co m
        } else if (expressionType.isParameterizedType()) {
            // Add a cast if expr is a superclass field or method, as its declared
            // type may be more general than expr's return type.
            if (binding instanceof IVariableBinding && ((IVariableBinding) binding).isField()) {
                IVariableBinding var = (IVariableBinding) binding;
                ITypeBinding remoteC = var.getDeclaringClass();
                ITypeBinding localC = Types.getMethodBinding(getOwningMethod(node)).getDeclaringClass();
                needsCast = !localC.isEqualTo(remoteC)
                        && var.getVariableDeclaration().getType().isTypeVariable();
            } else if (binding instanceof IMethodBinding) {
                IMethodBinding method = (IMethodBinding) binding;
                ITypeBinding remoteC = method.getDeclaringClass();
                ITypeBinding localC = Types.getMethodBinding(getOwningMethod(node)).getDeclaringClass();
                needsCast = !localC.isEqualTo(remoteC)
                        && method.getMethodDeclaration().getReturnType().isTypeVariable();
            }
        }
        if (needsCast) {
            buffer.append('(');
            buffer.append(NameTable.javaRefToCpp(expressionType));
            buffer.append(") ");
        }
        expr.accept(this);
    } else if (Types.getMethodBinding(getOwningMethod(node)).isConstructor()) {
        // A return statement without any expression is allowed in constructors.
        buffer.append(" self");
    }
    buffer.append(";\n");
    return false;
}

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.
 *///from www. j a  va  2 s  .c  o 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.Rewriter.java

License:Open Source License

/**
 * Given a AST node, return the appropriate printf() format specifier.
 *//*from  ww  w. j  a  v a 2 s .c  o m*/
private String getFormatArgument(ASTNode node) {
    ITypeBinding type = Types.getTypeBinding(node);
    AST ast = node.getAST();
    if (node instanceof CharacterLiteral || type.isEqualTo(ast.resolveWellKnownType("char"))) {
        return "%C";
    }
    if (node instanceof BooleanLiteral || type.isEqualTo(ast.resolveWellKnownType("boolean"))) {
        return "%d";
    }
    if (type.isEqualTo(ast.resolveWellKnownType("byte")) || type.isEqualTo(ast.resolveWellKnownType("int"))
            || type.isEqualTo(ast.resolveWellKnownType("short"))) {
        return "%d";
    }
    if (type.isEqualTo(ast.resolveWellKnownType("long"))) {
        return "%lld";
    }
    if (type.isEqualTo(ast.resolveWellKnownType("float"))
            || type.isEqualTo(ast.resolveWellKnownType("double"))) {
        return "%f";
    }
    if (node instanceof NumberLiteral) {
        String token = ((NumberLiteral) node).getToken();
        try {
            Integer.parseInt(token);
            return "%d";
        } catch (NumberFormatException e) {
            try {
                Long.parseLong(token);
                return "%lld";
            } catch (NumberFormatException e2) {
                try {
                    Double.parseDouble(token);
                    return "%f";
                } catch (NumberFormatException e3) {
                    throw new AssertionError("unknown number literal format: \"" + token + "\"");
                }
            }
        }
    }
    return "%@"; // object, including string
}