Example usage for org.eclipse.jdt.internal.compiler.lookup ReferenceBinding isAbstract

List of usage examples for org.eclipse.jdt.internal.compiler.lookup ReferenceBinding isAbstract

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.lookup ReferenceBinding isAbstract.

Prototype

public final boolean isAbstract() 

Source Link

Document

Answer true if the receiver is an abstract type

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MethodLocator.java

License:Open Source License

/**
 * Returns whether the given reference type binding matches or is a subtype of a type
 * that matches the given qualified pattern.
 * Returns ACCURATE_MATCH if it does./* w  ww.j a  v a2  s  .c  o  m*/
 * Returns INACCURATE_MATCH if resolve fails
 * Returns IMPOSSIBLE_MATCH if it doesn't.
 */
protected int resolveLevelAsSubtype(char[] simplePattern, char[] qualifiedPattern, ReferenceBinding type,
        char[] methodName, TypeBinding[] argumentTypes, char[] packageName, boolean isDefault) {
    if (type == null)
        return INACCURATE_MATCH;

    int level = resolveLevelForType(simplePattern, qualifiedPattern, type);
    if (level != IMPOSSIBLE_MATCH) {
        if (isDefault && !CharOperation.equals(packageName, type.qualifiedPackageName())) {
            return IMPOSSIBLE_MATCH;
        }
        MethodBinding method = argumentTypes == null ? null : getMethodBinding(type, methodName, argumentTypes);
        if (((method != null && !method.isAbstract()) || !type.isAbstract()) && !type.isInterface()) { // if concrete, then method is overridden
            level |= OVERRIDDEN_METHOD_FLAVOR;
        }
        return level;
    }

    // matches superclass
    if (!type.isInterface() && !CharOperation.equals(type.compoundName, TypeConstants.JAVA_LANG_OBJECT)) {
        level = resolveLevelAsSubtype(simplePattern, qualifiedPattern, type.superclass(), methodName,
                argumentTypes, packageName, isDefault);
        if (level != IMPOSSIBLE_MATCH) {
            if (argumentTypes != null) {
                // need to verify if method may be overridden
                MethodBinding method = getMethodBinding(type, methodName, argumentTypes);
                if (method != null) { // one method match in hierarchy
                    if ((level & OVERRIDDEN_METHOD_FLAVOR) != 0) {
                        // this method is already overridden on a super class, current match is impossible
                        return IMPOSSIBLE_MATCH;
                    }
                    if (!method.isAbstract() && !type.isInterface()) {
                        // store the fact that the method is overridden
                        level |= OVERRIDDEN_METHOD_FLAVOR;
                    }
                }
            }
            return level | SUB_INVOCATION_FLAVOR; // add flavor to returned level
        }
    }

    // matches interfaces
    ReferenceBinding[] interfaces = type.superInterfaces();
    if (interfaces == null)
        return INACCURATE_MATCH;
    for (int i = 0; i < interfaces.length; i++) {
        level = resolveLevelAsSubtype(simplePattern, qualifiedPattern, interfaces[i], methodName, null,
                packageName, isDefault);
        if (level != IMPOSSIBLE_MATCH) {
            if (!type.isAbstract() && !type.isInterface()) { // if concrete class, then method is overridden
                level |= OVERRIDDEN_METHOD_FLAVOR;
            }
            return level | SUB_INVOCATION_FLAVOR; // add flavor to returned level
        }
    }
    return IMPOSSIBLE_MATCH;
}

From source file:com.google.gwt.dev.javac.Shared.java

License:Open Source License

public static int bindingToModifierBits(ReferenceBinding binding) {
    int bits = 0;
    bits |= (binding.isPublic() ? MOD_PUBLIC : 0);
    bits |= (binding.isPrivate() ? MOD_PRIVATE : 0);
    bits |= (binding.isProtected() ? MOD_PROTECTED : 0);
    bits |= (binding.isStatic() ? MOD_STATIC : 0);
    bits |= (binding.isFinal() ? MOD_FINAL : 0);
    bits |= (binding.isAbstract() ? MOD_ABSTRACT : 0);
    return bits;//w w  w.  j  av  a 2  s  . c om
}

From source file:com.google.gwt.dev.jdt.WebModeCompilerFrontEnd.java

License:Apache License

private void checkRebindResultInstantiable(MessageSendSite site, String typeName) {
    /*//ww w  .ja v a 2 s.co  m
     * This causes the compiler to find the additional type, possibly winding
     * its back to ask for the compilation unit from the source oracle.
     */
    ReferenceBinding type = resolvePossiblyNestedType(typeName);

    // Sanity check rebind results.
    if (type == null) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' could not be found");
        return;
    }
    if (!type.isClass()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' must be a class");
        return;
    }
    if (type.isAbstract()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' cannot be abstract");
        return;
    }
    if (type.isNestedType() && !type.isStatic()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' cannot be a non-static nested class");
        return;
    }
    if (type.isLocalType()) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' cannot be a local class");
        return;
    }
    // Look for a noArg ctor.
    MethodBinding noArgCtor = type.getExactConstructor(Binding.NO_PARAMETERS);
    if (noArgCtor == null) {
        FindDeferredBindingSitesVisitor.reportRebindProblem(site,
                "Rebind result '" + typeName + "' has no default (zero argument) constructors");
        return;
    }
}

From source file:com.google.gwt.dev.jjs.impl.BuildTypeMap.java

License:Apache License

private JDeclaredType createType(String name, SourceInfo info, ReferenceBinding binding) {

    JDeclaredType newType;// w w  w . j a  v  a  2  s .  com
    if (binding.isClass()) {
        newType = program.createClass(info, name, binding.isAbstract(), binding.isFinal());
    } else if (binding.isInterface() || binding.isAnnotationType()) {
        newType = program.createInterface(info, name);
    } else if (binding.isEnum()) {
        if (binding.isAnonymousType()) {
            // Don't model an enum subclass as a JEnumType.
            newType = program.createClass(info, name, false, true);
        } else {
            newType = program.createEnum(info, name, binding.isAbstract());
        }
    } else {
        throw new InternalCompilerException("ReferenceBinding is not a class, interface, or enum.");
    }

    info.addCorrelation(info.getCorrelator().by(newType));

    /**
     * We emulate static initializers and instance initializers as methods. As
     * in other cases, this gives us: simpler AST, easier to optimize, more like
     * output JavaScript. Clinit is always in slot 0, init (if it exists) is
     * always in slot 1.
     */
    SourceInfo child = info.makeChild();
    JMethod clinit = program.createMethod(child, "$clinit", newType, program.getTypeVoid(), false, true, true,
            AccessModifier.PRIVATE, false);
    clinit.freezeParamTypes();
    clinit.setSynthetic();
    child.addCorrelation(info.getCorrelator().by(clinit));

    if (newType instanceof JClassType) {
        child = info.makeChild();
        JMethod init = program.createMethod(child, "$init", newType, program.getTypeVoid(), false, false, true,
                AccessModifier.PRIVATE, false);
        init.freezeParamTypes();
        init.setSynthetic();
        child.addCorrelation(info.getCorrelator().by(init));
    }

    newType.setExternal(linker.isExternalType(newType.getName()));
    return newType;
}

From source file:com.google.gwt.dev.jjs.impl.ReferenceMapper.java

License:Apache License

private JDeclaredType createType(ReferenceBinding binding) {
    String name = JdtUtil.asDottedString(binding.compoundName);
    SourceInfo info = SourceOrigin.UNKNOWN;
    if (binding.isClass()) {
        return new JClassType(info, name, binding.isAbstract(), binding.isFinal());
    } else if (binding.isInterface() || binding.isAnnotationType()) {
        return new JInterfaceType(info, name);
    } else if (binding.isEnum()) {
        if (binding.isAnonymousType()) {
            // Don't model an enum subclass as a JEnumType.
            return new JClassType(info, name, false, true);
        } else {//from   ww  w.  j  a v  a  2  s.  c  o  m
            return new JEnumType(info, name, binding.isAbstract());
        }
    } else {
        throw new InternalCompilerException("ReferenceBinding is not a class, interface, or enum.");
    }
}

From source file:com.redhat.ceylon.eclipse.core.model.mirror.UnknownClassMirror.java

License:Open Source License

public JDTClass(ReferenceBinding klass, IType type) {
    this.type = type;
    bindingRef = new WeakReference<ReferenceBinding>(klass);
    pkg = new JDTPackage(klass.getPackage());
    simpleName = new String(klass.sourceName());
    qualifiedName = JDTUtils.getFullyQualifiedName(klass);
    isPublic = klass.isPublic();//from w  w  w.j a  va 2  s  .c o  m
    isInterface = klass.isInterface();
    isAbstract = klass.isAbstract();
    isProtected = klass.isProtected();
    isDefaultAccess = klass.isDefault();
    isLocalType = klass.isLocalType();
    isStatic = (klass.modifiers & ClassFileConstants.AccStatic) != 0;
    isFinal = klass.isFinal();
    isEnum = klass.isEnum();
    isBinary = klass.isBinaryBinding();
    isAnonymous = klass.isAnonymousType();
    isJavaSource = (klass instanceof SourceTypeBinding)
            && new String(((SourceTypeBinding) klass).getFileName()).endsWith(".java");
    isAnnotationType = klass.isAnnotationType();
    bindingKey = klass.computeUniqueKey();

    char[] bindingFileName = klass.getFileName();
    int start = CharOperation.lastIndexOf('/', bindingFileName) + 1;
    if (start == 0 || start < CharOperation.lastIndexOf('\\', bindingFileName))
        start = CharOperation.lastIndexOf('\\', bindingFileName) + 1;
    fileName = new String(CharOperation.subarray(bindingFileName, start, -1));

    int jarFileEntrySeparatorIndex = CharOperation.indexOf(IDependent.JAR_FILE_ENTRY_SEPARATOR,
            bindingFileName);
    if (jarFileEntrySeparatorIndex > 0) {
        char[] jarPart = CharOperation.subarray(bindingFileName, 0, jarFileEntrySeparatorIndex);
        IJavaElement jarPackageFragmentRoot = JavaCore.create(new String(jarPart));
        String jarPath = jarPackageFragmentRoot.getPath().toOSString();
        char[] entryPart = CharOperation.subarray(bindingFileName, jarFileEntrySeparatorIndex + 1,
                bindingFileName.length);
        fullPath = new StringBuilder(jarPath).append("!/").append(entryPart).toString();
    } else {
        fullPath = new String(bindingFileName);
    }

    ReferenceBinding sourceOrClass = klass;
    if (!klass.isBinaryBinding()) {
        sourceOrClass = klass.outermostEnclosingType();
    }
    char[] classFullName = new char[0];
    for (char[] part : sourceOrClass.compoundName) {
        classFullName = CharOperation.concat(classFullName, part, '/');
    }
    char[][] temp = CharOperation.splitOn('.', sourceOrClass.getFileName());
    String extension = temp.length > 1 ? "." + new String(temp[temp.length - 1]) : "";
    javaModelPath = new String(classFullName) + extension;

    if (type == null) {
        annotations = new HashMap<>();
        methods = Collections.emptyList();
        interfaces = Collections.emptyList();
        typeParams = Collections.emptyList();
        fields = Collections.emptyList();
        innerClasses = Collections.emptyList();
    }
}

From source file:lombok.eclipse.handlers.HandleActionFunctionAndPredicate.java

License:Open Source License

private TemplateData templateDataFor(final AbstractMethodDeclaration methodDecl,
        final ReferenceBinding template, final String forcedReturnType) {
    if (!template.isPublic())
        return null;
    if (!template.isInterface() && !template.isAbstract())
        return null;
    final List<TypeVariableBinding> templateTypeArguments = As.list(template.typeVariables());
    final List<MethodBinding> enclosedMethods = enclosedMethodsOf(template);
    if (enclosedMethods.size() != 1)
        return null;
    final MethodBinding enclosedMethod = enclosedMethods.get(0);
    if (!matchesReturnType(enclosedMethod, forcedReturnType))
        return null;
    final List<TypeBinding> methodTypeArguments = As.list(enclosedMethod.parameters);
    if (forcedReturnType == null)
        methodTypeArguments.add(enclosedMethod.returnType);
    if (!templateTypeArguments.equals(methodTypeArguments))
        return null;
    if (forcedReturnType == null) {
        if ((numberOfParameters(methodDecl) + 1) != templateTypeArguments.size())
            return null;
    } else {// w w  w . ja  v  a2s.c o  m
        if (numberOfParameters(methodDecl) != templateTypeArguments.size())
            return null;
    }
    return new TemplateData(qualifiedName(template), As.string(enclosedMethod.selector), forcedReturnType);
}

From source file:org.eclipse.jdt.internal.compiler.lookup.Scope.java

License:Open Source License

public MethodBinding findMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes,
        InvocationSite invocationSite, boolean inStaticContext) {
    ReferenceBinding currentType = receiverType;
    boolean receiverTypeIsInterface = receiverType.isInterface();
    ObjectVector found = new ObjectVector(3);
    CompilationUnitScope unitScope = compilationUnitScope();
    unitScope.recordTypeReferences(argumentTypes);

    if (receiverTypeIsInterface) {
        unitScope.recordTypeReference(receiverType);
        MethodBinding[] receiverMethods = receiverType.getMethods(selector, argumentTypes.length);
        if (receiverMethods.length > 0)
            found.addAll(receiverMethods);
        findMethodInSuperInterfaces(receiverType, selector, found, invocationSite);
        currentType = getJavaLangObject();
    }/*w  w w  . j  ava 2s .  c  om*/

    // superclass lookup
    long complianceLevel = compilerOptions().complianceLevel;
    boolean isCompliant14 = complianceLevel >= ClassFileConstants.JDK1_4;
    boolean isCompliant15 = complianceLevel >= ClassFileConstants.JDK1_5;
    ReferenceBinding classHierarchyStart = currentType;
    MethodVerifier verifier = environment().methodVerifier();
    while (currentType != null) {
        unitScope.recordTypeReference(currentType);
        currentType = (ReferenceBinding) currentType.capture(this,
                invocationSite == null ? 0 : invocationSite.sourceEnd());
        MethodBinding[] currentMethods = currentType.getMethods(selector, argumentTypes.length);
        int currentLength = currentMethods.length;
        if (currentLength > 0) {
            if (isCompliant14 && (receiverTypeIsInterface || found.size > 0)) {
                nextMethod: for (int i = 0, l = currentLength; i < l; i++) { // currentLength can be modified inside the loop
                    MethodBinding currentMethod = currentMethods[i];
                    if (currentMethod == null)
                        continue nextMethod;
                    if (receiverTypeIsInterface && !currentMethod.isPublic()) { // only public methods from Object are visible to interface receiverTypes
                        currentLength--;
                        currentMethods[i] = null;
                        continue nextMethod;
                    }

                    // if 1.4 compliant, must filter out redundant protected methods from superclasses
                    // protected method need to be checked only - default access is already dealt with in #canBeSeen implementation
                    // when checking that p.C -> q.B -> p.A cannot see default access members from A through B.
                    // if ((currentMethod.modifiers & AccProtected) == 0) continue nextMethod;
                    // BUT we can also ignore any overridden method since we already know the better match (fixes 80028)
                    for (int j = 0, max = found.size; j < max; j++) {
                        MethodBinding matchingMethod = (MethodBinding) found.elementAt(j);
                        MethodBinding matchingOriginal = matchingMethod.original();
                        MethodBinding currentOriginal = matchingOriginal
                                .findOriginalInheritedMethod(currentMethod);
                        if (currentOriginal != null
                                && verifier.isParameterSubsignature(matchingOriginal, currentOriginal)) {
                            if (isCompliant15) {
                                if (matchingMethod.isBridge() && !currentMethod.isBridge())
                                    continue nextMethod; // keep inherited methods to find concrete method over a bridge method
                            }
                            currentLength--;
                            currentMethods[i] = null;
                            continue nextMethod;
                        }
                    }
                }
            }

            if (currentLength > 0) {
                // append currentMethods, filtering out null entries
                if (currentMethods.length == currentLength) {
                    found.addAll(currentMethods);
                } else {
                    for (int i = 0, max = currentMethods.length; i < max; i++) {
                        MethodBinding currentMethod = currentMethods[i];
                        if (currentMethod != null)
                            found.add(currentMethod);
                    }
                }
            }
        }
        currentType = currentType.superclass();
    }

    // if found several candidates, then eliminate those not matching argument types
    int foundSize = found.size;
    MethodBinding[] candidates = null;
    int candidatesCount = 0;
    MethodBinding problemMethod = null;
    boolean searchForDefaultAbstractMethod = isCompliant14 && !receiverTypeIsInterface
            && (receiverType.isAbstract() || receiverType.isTypeVariable());
    if (foundSize > 0) {
        // argument type compatibility check
        for (int i = 0; i < foundSize; i++) {
            MethodBinding methodBinding = (MethodBinding) found.elementAt(i);
            MethodBinding compatibleMethod = computeCompatibleMethod(methodBinding, argumentTypes,
                    invocationSite);
            if (compatibleMethod != null) {
                if (compatibleMethod.isValidBinding()) {
                    if (foundSize == 1 && compatibleMethod.canBeSeenBy(receiverType, invocationSite, this)) {
                        // return the single visible match now
                        if (searchForDefaultAbstractMethod)
                            return findDefaultAbstractMethod(receiverType, selector, argumentTypes,
                                    invocationSite, classHierarchyStart, found, compatibleMethod);
                        unitScope.recordTypeReferences(compatibleMethod.thrownExceptions);
                        return compatibleMethod;
                    }
                    if (candidatesCount == 0)
                        candidates = new MethodBinding[foundSize];
                    candidates[candidatesCount++] = compatibleMethod;
                } else if (problemMethod == null) {
                    problemMethod = compatibleMethod;
                }
            }
        }
    }

    // no match was found
    if (candidatesCount == 0) {
        if (problemMethod != null) {
            switch (problemMethod.problemId()) {
            case ProblemReasons.TypeArgumentsForRawGenericMethod:
            case ProblemReasons.TypeParameterArityMismatch:
                return problemMethod;
            }
        }
        // abstract classes may get a match in interfaces; for non abstract
        // classes, reduces secondary errors since missing interface method
        // error is already reported
        MethodBinding interfaceMethod = findDefaultAbstractMethod(receiverType, selector, argumentTypes,
                invocationSite, classHierarchyStart, found, null);
        if (interfaceMethod != null)
            return interfaceMethod;
        if (found.size == 0)
            return null;
        if (problemMethod != null)
            return problemMethod;

        // still no match; try to find a close match when the parameter
        // order is wrong or missing some parameters

        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=69471
        // bad guesses are foo(), when argument types have been supplied
        // and foo(X, Y), when the argument types are (int, float, Y)
        // so answer the method with the most argType matches and least parameter type mismatches
        int bestArgMatches = -1;
        MethodBinding bestGuess = (MethodBinding) found.elementAt(0); // if no good match so just use the first one found
        int argLength = argumentTypes.length;
        foundSize = found.size;
        nextMethod: for (int i = 0; i < foundSize; i++) {
            MethodBinding methodBinding = (MethodBinding) found.elementAt(i);
            TypeBinding[] params = methodBinding.parameters;
            int paramLength = params.length;
            int argMatches = 0;
            next: for (int a = 0; a < argLength; a++) {
                TypeBinding arg = argumentTypes[a];
                for (int p = a == 0 ? 0 : a - 1; p < paramLength && p < a + 1; p++) { // look one slot before & after to see if the type matches
                    if (params[p] == arg) {
                        argMatches++;
                        continue next;
                    }
                }
            }
            if (argMatches < bestArgMatches)
                continue nextMethod;
            if (argMatches == bestArgMatches) {
                int diff1 = paramLength < argLength ? 2 * (argLength - paramLength) : paramLength - argLength;
                int bestLength = bestGuess.parameters.length;
                int diff2 = bestLength < argLength ? 2 * (argLength - bestLength) : bestLength - argLength;
                if (diff1 >= diff2)
                    continue nextMethod;
            }
            bestArgMatches = argMatches;
            bestGuess = methodBinding;
        }
        return new ProblemMethodBinding(bestGuess, bestGuess.selector, argumentTypes, ProblemReasons.NotFound);
    }

    // tiebreak using visibility check
    int visiblesCount = 0;
    if (receiverTypeIsInterface) {
        if (candidatesCount == 1) {
            unitScope.recordTypeReferences(candidates[0].thrownExceptions);
            return candidates[0];
        }
        visiblesCount = candidatesCount;
    } else {
        for (int i = 0; i < candidatesCount; i++) {
            MethodBinding methodBinding = candidates[i];
            if (methodBinding.canBeSeenBy(receiverType, invocationSite, this)) {
                if (visiblesCount != i) {
                    candidates[i] = null;
                    candidates[visiblesCount] = methodBinding;
                }
                visiblesCount++;
            }
        }
        switch (visiblesCount) {
        case 0:
            MethodBinding interfaceMethod = findDefaultAbstractMethod(receiverType, selector, argumentTypes,
                    invocationSite, classHierarchyStart, found, null);
            if (interfaceMethod != null)
                return interfaceMethod;
            return new ProblemMethodBinding(candidates[0], candidates[0].selector, candidates[0].parameters,
                    ProblemReasons.NotVisible);
        case 1:
            if (searchForDefaultAbstractMethod)
                return findDefaultAbstractMethod(receiverType, selector, argumentTypes, invocationSite,
                        classHierarchyStart, found, candidates[0]);
            unitScope.recordTypeReferences(candidates[0].thrownExceptions);
            return candidates[0];
        default:
            break;
        }
    }

    if (complianceLevel <= ClassFileConstants.JDK1_3) {
        ReferenceBinding declaringClass = candidates[0].declaringClass;
        return !declaringClass.isInterface()
                ? mostSpecificClassMethodBinding(candidates, visiblesCount, invocationSite)
                : mostSpecificInterfaceMethodBinding(candidates, visiblesCount, invocationSite);
    }

    // check for duplicate parameterized methods
    if (compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) {
        for (int i = 0; i < visiblesCount; i++) {
            MethodBinding candidate = candidates[i];
            if (candidate instanceof ParameterizedGenericMethodBinding)
                candidate = ((ParameterizedGenericMethodBinding) candidate).originalMethod;
            if (candidate.hasSubstitutedParameters()) {
                for (int j = i + 1; j < visiblesCount; j++) {
                    MethodBinding otherCandidate = candidates[j];
                    if (otherCandidate.hasSubstitutedParameters()) {
                        if (otherCandidate == candidate
                                || (candidate.declaringClass == otherCandidate.declaringClass
                                        && candidate.areParametersEqual(otherCandidate))) {
                            return new ProblemMethodBinding(candidates[i], candidates[i].selector,
                                    candidates[i].parameters, ProblemReasons.Ambiguous);
                        }
                    }
                }
            }
        }
    }
    if (inStaticContext) {
        MethodBinding[] staticCandidates = new MethodBinding[visiblesCount];
        int staticCount = 0;
        for (int i = 0; i < visiblesCount; i++)
            if (candidates[i].isStatic())
                staticCandidates[staticCount++] = candidates[i];
        if (staticCount == 1)
            return staticCandidates[0];
        if (staticCount > 1)
            return mostSpecificMethodBinding(staticCandidates, staticCount, argumentTypes, invocationSite,
                    receiverType);
    }

    MethodBinding mostSpecificMethod = mostSpecificMethodBinding(candidates, visiblesCount, argumentTypes,
            invocationSite, receiverType);
    if (searchForDefaultAbstractMethod) { // search interfaces for a better match
        if (mostSpecificMethod.isValidBinding())
            // see if there is a better match in the interfaces - see AutoBoxingTest 99, LookupTest#81
            return findDefaultAbstractMethod(receiverType, selector, argumentTypes, invocationSite,
                    classHierarchyStart, found, mostSpecificMethod);
        // see if there is a match in the interfaces - see LookupTest#84
        MethodBinding interfaceMethod = findDefaultAbstractMethod(receiverType, selector, argumentTypes,
                invocationSite, classHierarchyStart, found, null);
        if (interfaceMethod != null
                && interfaceMethod.isValidBinding() /* else return the same error as before */)
            return interfaceMethod;
    }
    return mostSpecificMethod;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.lifting.Lifting.java

License:Open Source License

/**
  * Create a liftTo method an add it to the team, including creation of bindings.
  *//from  w w  w.  ja v a2s.c  om
  * @param teamTypeDeclaration type to add the lift method to.
  * @param roleNode the Role for which the LiftTo Method is to be created
  * @param caseObjects all informations for creating case statements,.
  *   i.e., the role classes to which lifting could occur.
  */
public void createLiftToMethod(TypeDeclaration teamTypeDeclaration, TreeNode roleNode,
        final RoleModel[] caseObjects) {

    TreeNode boundRootRoleNode = roleNode.getTopmostBoundParent(true);
    if (boundRootRoleNode == null)
        return;

    final RoleModel roleModel = roleNode.getTreeObject();

    TypeDeclaration typeDecl = roleModel.getAst(); // only for positions
    if (typeDecl == null)
        typeDecl = teamTypeDeclaration;

    if (boundRootRoleNode == TreeNode.ProblemNode) {
        typeDecl.scope.problemReporter().overlappingRoleHierarchies(typeDecl, TreeNode.ProblemNode.toString());
        return;
    }

    this._boundRootRoleModel = boundRootRoleNode.getTreeObject();
    this._gen = new AstGenerator(typeDecl.sourceStart, typeDecl.sourceEnd);
    this._gen.replaceableEnclosingClass = teamTypeDeclaration.binding;
    this._sourceLevel = typeDecl.scope.compilerOptions().sourceLevel;

    try {
        final ReferenceBinding teamBinding = teamTypeDeclaration.binding;
        final ReferenceBinding roleClassBinding = roleModel.getBinding();
        final ReferenceBinding baseClassBinding = roleClassBinding.baseclass();

        if (RoleModel.hasTagBit(roleClassBinding, RoleModel.HasLiftingProblem)) {
            this._boundRootRoleModel = null;
            this._gen = null;
            return; // lift method won't work
        }

        char[] methodName = getLiftMethodName(roleClassBinding.sourceName());
        Argument[] arguments = new Argument[] {
                this._gen.argument(BASE, this._gen.baseclassReference(baseClassBinding)) };

        MethodDeclaration liftToMethodDeclaration = AstConverter.findAndAdjustCopiedMethod(teamTypeDeclaration,
                methodName, arguments);

        boolean needToAdd = false;
        if (liftToMethodDeclaration == null) {
            liftToMethodDeclaration = createLiftToMethodDeclaration(teamTypeDeclaration, roleClassBinding,
                    methodName, arguments, baseClassBinding);
            this._gen.maybeAddTypeParametersToMethod(baseClassBinding, liftToMethodDeclaration);
            needToAdd = true;
        }

        final int problemId = teamBinding.getTeamModel().canLiftingFail(roleClassBinding);
        if (caseObjects.length == 0 && teamBinding.isAbstract()) {
            liftToMethodDeclaration.modifiers |= AccAbstract | AccSemicolonBody;
            if (liftToMethodDeclaration.binding != null)
                liftToMethodDeclaration.binding.modifiers |= AccAbstract;
        } else {
            final MethodDeclaration newMethod = liftToMethodDeclaration;
            final AstGenerator gen = this._gen;
            final RoleModel boundRootRole = this._boundRootRoleModel;
            MethodModel.getModel(newMethod).setStatementsGenerator(new AbstractStatementsGenerator() {
                @SuppressWarnings("synthetic-access")
                public boolean generateStatements(AbstractMethodDeclaration methodDecl) {
                    try {
                        Lifting.this._gen = gen;
                        Lifting.this._boundRootRoleModel = boundRootRole;
                        return createLiftToMethodStatements(newMethod, teamBinding, roleModel, baseClassBinding,
                                caseObjects, problemId);
                    } finally {
                        Lifting.this._gen = null;
                        Lifting.this._boundRootRoleModel = null;
                    }
                }
            });
        }

        if (needToAdd) {
            if (problemId != 0) {
                liftToMethodDeclaration.thrownExceptions = new TypeReference[] {
                        this._gen.qualifiedTypeReference(O_O_LIFTING_FAILED_EXCEPTION) };
            }
            if (teamTypeDeclaration.isRole()) {
                TypeDeclaration interfaceAst = teamTypeDeclaration.getRoleModel().getInterfaceAst();
                if (interfaceAst != null) {
                    MethodDeclaration ifcMethod = AstConverter.genRoleIfcMethod(interfaceAst,
                            liftToMethodDeclaration);
                    AstEdit.addMethod(interfaceAst, ifcMethod);
                    liftToMethodDeclaration.modifiers = liftToMethodDeclaration.modifiers & ~AccProtected
                            | AccPublic;
                }
            }
            AstEdit.addMethod(teamTypeDeclaration, liftToMethodDeclaration);
        }

    } finally {
        this._boundRootRoleModel = null;
        this._gen = null;
    }
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.model.TeamModel.java

License:Open Source License

/**
 * Can lifting to the given role potentially fail at runtime?
 * @param role role to lift to./*w  w  w .  j  a v a  2s  .  c o m*/
 * @return the IProblem value to be used when reporting hidden-lifting-problem against a callin binding or 0.
 */
public int canLiftingFail(ReferenceBinding role) {
    if ((this.tagBits & HasAbstractRelevantRole) != 0 && role.isAbstract())
        return IProblem.CallinDespiteAbstractRole;
    for (Pair<ReferenceBinding, ReferenceBinding> pair : this.ambigousLifting) {
        if (role.getRealClass().isCompatibleWith(pair.second) && pair.first.isCompatibleWith(role.baseclass()))
            return IProblem.CallinDespiteBindingAmbiguity;
    }
    return 0;
}