Example usage for org.eclipse.jdt.internal.compiler.util ObjectVector add

List of usage examples for org.eclipse.jdt.internal.compiler.util ObjectVector add

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.util ObjectVector add.

Prototype

public void add(Object newElement) 

Source Link

Usage

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

License:Open Source License

private static IJavaElement[] getFocusedElementsAndTypes(SearchPattern pattern, IJavaElement focusElement,
        ObjectVector superTypes) throws JavaModelException {
    if (pattern instanceof MethodPattern) {
        // For method pattern, it needs to walk along the focus type super hierarchy
        // and add jars/projects of all the encountered types.
        IType type = (IType) pattern.focus.getAncestor(IJavaElement.TYPE);
        MethodPattern methodPattern = (MethodPattern) pattern;
        String selector = new String(methodPattern.selector);
        int parameterCount = methodPattern.parameterCount;
        ITypeHierarchy superHierarchy = type.newSupertypeHierarchy(null);
        IType[] allTypes = superHierarchy.getAllSupertypes(type);
        int length = allTypes.length;
        SimpleSet focusSet = new SimpleSet(length + 1);
        if (focusElement != null)
            focusSet.add(focusElement);//from   w w w  .  j ava2s .  c om
        for (int i = 0; i < length; i++) {
            IMethod[] methods = allTypes[i].getMethods();
            int mLength = methods.length;
            for (int m = 0; m < mLength; m++) {
                if (parameterCount == methods[m].getNumberOfParameters()
                        && methods[m].getElementName().equals(selector)) {
                    IPackageFragmentRoot root = (IPackageFragmentRoot) allTypes[i]
                            .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
                    IJavaElement element = root.isArchive() ? root : root.getParent();
                    focusSet.add(element);
                    if (superTypes != null)
                        superTypes.add(allTypes[i]);
                    break;
                }
            }
        }
        // Rebuilt a contiguous array
        IJavaElement[] focuses = new IJavaElement[focusSet.elementSize];
        Object[] values = focusSet.values;
        int count = 0;
        for (int i = values.length; --i >= 0;) {
            if (values[i] != null) {
                focuses[count++] = (IJavaElement) values[i];
            }
        }
        return focuses;
    }
    if (focusElement == null)
        return new IJavaElement[0];
    return new IJavaElement[] { focusElement };
}

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

License:Open Source License

public void add(PossibleMatch possibleMatch) {
    IPath path = possibleMatch.openable.getPackageFragmentRoot().getPath();
    ObjectVector possibleMatches = (ObjectVector) this.rootsToPossibleMatches.get(path);
    if (possibleMatches != null) {
        PossibleMatch storedMatch = (PossibleMatch) possibleMatches.find(possibleMatch);
        if (storedMatch != null) {
            while (storedMatch.getSimilarMatch() != null) {
                storedMatch = storedMatch.getSimilarMatch();
            }//from w  w w.  j  a v a  2  s . co  m
            storedMatch.setSimilarMatch(possibleMatch);
            return;
        }
    } else {
        this.rootsToPossibleMatches.put(path, possibleMatches = new ObjectVector());
    }

    possibleMatches.add(possibleMatch);
    this.elementCount++;
}

From source file:org.eclipse.che.jdt.internal.core.JavaProject.java

License:Open Source License

/**
 * Returns the package fragment roots identified by the given entry. In case it refers to
 * a project, it will follow its classpath so as to find exported roots as well.
 * Only works with resolved entry//from  w w w .  j  av a2 s  . c  om
 *
 * @param resolvedEntry
 *         IClasspathEntry
 * @param accumulatedRoots
 *         ObjectVector
 * @param rootIDs
 *         HashSet
 * @param referringEntry
 *         the CP entry (project) referring to this entry, or null if initial project
 * @param retrieveExportedRoots
 *         boolean
 * @throws JavaModelException
 */
public void computePackageFragmentRoots(IClasspathEntry resolvedEntry, ObjectVector accumulatedRoots,
        HashSet rootIDs, IClasspathEntry referringEntry, boolean retrieveExportedRoots,
        Map rootToResolvedEntries) throws JavaModelException {

    String rootID = ((ClasspathEntry) resolvedEntry).rootID();
    if (rootIDs.contains(rootID))
        return;

    IPath projectPath = this.getFullPath();
    IPath entryPath = resolvedEntry.getPath();
    //        IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IPackageFragmentRoot root = null;

    switch (resolvedEntry.getEntryKind()) {

    // source folder
    case IClasspathEntry.CPE_SOURCE:

        //                if (projectPath.isPrefixOf(entryPath)) {
        Object target1 = JavaModelManager.getTarget(entryPath, true/*check existency*/);
        if (target1 == null)
            return;

        if (target1 instanceof File && ((File) target1).isDirectory()) {
            root = getPackageFragmentRoot((File) target1);
        }
        //                }
        break;

    // internal/external JAR or folder
    case IClasspathEntry.CPE_LIBRARY:
        if (referringEntry != null && !resolvedEntry.isExported())
            return;
        Object target = JavaModelManager.getTarget(entryPath, true/*check existency*/);
        if (target == null)
            return;

        //                if (target instanceof IResource){
        //                    // internal target
        //                } else
        if (target instanceof File) {
            // external target
            if (JavaModelManager.isFile(target)) {
                root = new JarPackageFragmentRoot((File) target, this, manager);
            } else if (((File) target).isDirectory()) {
                root = getPackageFragmentRoot((File) target, entryPath);
                //                        root = new ExternalPackageFragmentRoot(entryPath, this);
            }
        }
        break;

    // recurse into required project
    case IClasspathEntry.CPE_PROJECT:

        if (!retrieveExportedRoots)
            return;
        if (referringEntry != null && !resolvedEntry.isExported())
            return;
        //todo multiproject
        //                IResource member = workspaceRoot.findMember(entryPath);
        //                if (member != null && member.getType() == IResource.PROJECT) {// double check if bound to project (23977)
        //                    IProject requiredProjectRsc = (IProject)member;
        //                    if (JavaProject.hasJavaNature(requiredProjectRsc)) { // special builder binary output
        //                        rootIDs.add(rootID);
        //                        JavaProject requiredProject = (JavaProject)JavaCore.create(requiredProjectRsc);
        //                        requiredProject.computePackageFragmentRoots(
        //                                requiredProject.getResolvedClasspath(),
        //                                accumulatedRoots,
        //                                rootIDs,
        //                                rootToResolvedEntries == null ? resolvedEntry
        //                                                              : ((org.eclipse.jdt.internal.core.ClasspathEntry)resolvedEntry)
        //                                        .combineWith((org.eclipse.jdt.internal.core.ClasspathEntry)referringEntry),
        //                                // only combine if need to build the reverse map
        //                                retrieveExportedRoots,
        //                                rootToResolvedEntries);
        //                    }
        //                    break;
        //                }
    }
    if (root != null) {
        accumulatedRoots.add(root);
        rootIDs.add(rootID);
        if (rootToResolvedEntries != null)
            rootToResolvedEntries.put(root,
                    ((ClasspathEntry) resolvedEntry).combineWith((ClasspathEntry) referringEntry));
    }
}

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();
    }//from   ww w  .  j av  a  2  s.  c  o m

    // 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.jdt.internal.compiler.lookup.Scope.java

License:Open Source License

protected void findMethodInSuperInterfaces(ReferenceBinding currentType, char[] selector, ObjectVector found,
        InvocationSite invocationSite) {
    ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
    if (itsInterfaces != null && itsInterfaces != Binding.NO_SUPERINTERFACES) {
        ReferenceBinding[] interfacesToVisit = itsInterfaces;
        int nextPosition = interfacesToVisit.length;
        for (int i = 0; i < nextPosition; i++) {
            currentType = interfacesToVisit[i];
            compilationUnitScope().recordTypeReference(currentType);
            currentType = (ReferenceBinding) currentType.capture(this,
                    invocationSite == null ? 0 : invocationSite.sourceEnd());
            MethodBinding[] currentMethods = currentType.getMethods(selector);
            if (currentMethods.length > 0) {
                int foundSize = found.size;
                if (foundSize > 0) {
                    // its possible to walk the same superinterface from different classes in the hierarchy
                    next: for (int c = 0, l = currentMethods.length; c < l; c++) {
                        MethodBinding current = currentMethods[c];
                        for (int f = 0; f < foundSize; f++)
                            if (current == found.elementAt(f))
                                continue next;
                        found.add(current);
                    }//  ww  w .ja v  a  2 s  . c  o m
                } else {
                    found.addAll(currentMethods);
                }
            }
            if ((itsInterfaces = currentType.superInterfaces()) != null
                    && itsInterfaces != Binding.NO_SUPERINTERFACES) {
                int itsLength = itsInterfaces.length;
                if (nextPosition + itsLength >= interfacesToVisit.length)
                    System.arraycopy(interfacesToVisit, 0,
                            interfacesToVisit = new ReferenceBinding[nextPosition + itsLength + 5], 0,
                            nextPosition);
                nextInterface: for (int a = 0; a < itsLength; a++) {
                    ReferenceBinding next = itsInterfaces[a];
                    for (int b = 0; b < nextPosition; b++)
                        if (next == interfacesToVisit[b])
                            continue nextInterface;
                    interfacesToVisit[nextPosition++] = next;
                }
            }
        }
    }
}

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

License:Open Source License

public MethodBinding getImplicitMethod(char[] selector, TypeBinding[] argumentTypes,
        InvocationSite invocationSite) {

    boolean insideStaticContext = false;
    boolean insideConstructorCall = false;
    boolean insideTypeAnnotation = false;
    MethodBinding foundMethod = null;//from  w  w w .  j  a v  a  2 s.  c o m
    MethodBinding foundProblem = null;
    boolean foundProblemVisible = false;
    Scope scope = this;
    int depth = 0;
    // in 1.4 mode (inherited visible shadows enclosing)
    CompilerOptions options;
    boolean inheritedHasPrecedence = (options = compilerOptions()).complianceLevel >= ClassFileConstants.JDK1_4;

    done: while (true) { // done when a COMPILATION_UNIT_SCOPE is found
        switch (scope.kind) {
        case METHOD_SCOPE:
            MethodScope methodScope = (MethodScope) scope;
            insideStaticContext |= methodScope.isStatic;
            insideConstructorCall |= methodScope.isConstructorCall;
            insideTypeAnnotation = methodScope.insideTypeAnnotation;
            break;
        case CLASS_SCOPE:
            ClassScope classScope = (ClassScope) scope;
            ReferenceBinding receiverType = classScope.enclosingReceiverType();
            if (!insideTypeAnnotation) {
                // retrieve an exact visible match (if possible)
                // compilationUnitScope().recordTypeReference(receiverType);   not needed since receiver is the source type
                MethodBinding methodBinding = classScope.findExactMethod(receiverType, selector, argumentTypes,
                        invocationSite);
                if (methodBinding == null)
                    methodBinding = classScope.findMethod(receiverType, selector, argumentTypes,
                            invocationSite);
                if (methodBinding != null) { // skip it if we did not find anything
                    if (foundMethod == null) {
                        if (methodBinding.isValidBinding()) {
                            if (!methodBinding.isStatic() && (insideConstructorCall || insideStaticContext)) {
                                if (foundProblem != null
                                        && foundProblem.problemId() != ProblemReasons.NotVisible)
                                    return foundProblem; // takes precedence
                                return new ProblemMethodBinding(methodBinding, // closest match
                                        methodBinding.selector, methodBinding.parameters,
                                        insideConstructorCall
                                                ? ProblemReasons.NonStaticReferenceInConstructorInvocation
                                                : ProblemReasons.NonStaticReferenceInStaticContext);
                            }
                            if (inheritedHasPrecedence || receiverType == methodBinding.declaringClass
                                    || (receiverType.getMethods(selector)) != Binding.NO_METHODS) {
                                // found a valid method in the 'immediate' scope (i.e. not inherited)
                                // OR in 1.4 mode (inherited visible shadows enclosing)
                                // OR the receiverType implemented a method with the correct name
                                // return the methodBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
                                if (foundProblemVisible) {
                                    return foundProblem;
                                }
                                if (depth > 0) {
                                    invocationSite.setDepth(depth);
                                    invocationSite.setActualReceiverType(receiverType);
                                }
                                // special treatment for Object.getClass() in 1.5 mode (substitute parameterized return type)
                                if (argumentTypes == Binding.NO_PARAMETERS
                                        && CharOperation.equals(selector, TypeConstants.GETCLASS)
                                        && methodBinding.returnType.isParameterizedType()/*1.5*/) {
                                    return environment().createGetClassMethod(receiverType, methodBinding,
                                            this);
                                }
                                return methodBinding;
                            }

                            if (foundProblem == null || foundProblem.problemId() == ProblemReasons.NotVisible) {
                                if (foundProblem != null)
                                    foundProblem = null;
                                // only remember the methodBinding if its the first one found
                                // remember that private methods are visible if defined directly by an enclosing class
                                if (depth > 0) {
                                    invocationSite.setDepth(depth);
                                    invocationSite.setActualReceiverType(receiverType);
                                }
                                foundMethod = methodBinding;
                            }
                        } else { // methodBinding is a problem method
                            if (methodBinding.problemId() != ProblemReasons.NotVisible
                                    && methodBinding.problemId() != ProblemReasons.NotFound)
                                return methodBinding; // return the error now
                            if (foundProblem == null) {
                                foundProblem = methodBinding; // hold onto the first not visible/found error and keep the second not found if first is not visible
                            }
                            if (!foundProblemVisible && methodBinding.problemId() == ProblemReasons.NotFound) {
                                MethodBinding closestMatch = ((ProblemMethodBinding) methodBinding).closestMatch;
                                if (closestMatch != null
                                        && closestMatch.canBeSeenBy(receiverType, invocationSite, this)) {
                                    foundProblem = methodBinding; // hold onto the first not visible/found error and keep the second not found if first is not visible
                                    foundProblemVisible = true;
                                }
                            }
                        }
                    } else { // found a valid method so check to see if this is a hiding case
                        if (methodBinding.problemId() == ProblemReasons.Ambiguous
                                || (foundMethod.declaringClass != methodBinding.declaringClass
                                        && (receiverType == methodBinding.declaringClass
                                                || receiverType.getMethods(selector) != Binding.NO_METHODS)))
                            // ambiguous case -> must qualify the method (javac generates an ambiguous error instead)
                            // otherwise if a method was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
                            // NOTE: Unlike fields, a non visible method hides a visible method
                            return new ProblemMethodBinding(methodBinding, // closest match
                                    selector, argumentTypes, ProblemReasons.InheritedNameHidesEnclosingName);
                    }
                }
            }
            insideTypeAnnotation = false;
            depth++;
            insideStaticContext |= receiverType.isStatic();
            // 1EX5I8Z - accessing outer fields within a constructor call is permitted
            // in order to do so, we change the flag as we exit from the type, not the method
            // itself, because the class scope is used to retrieve the fields.
            MethodScope enclosingMethodScope = scope.methodScope();
            insideConstructorCall = enclosingMethodScope == null ? false
                    : enclosingMethodScope.isConstructorCall;
            break;
        case COMPILATION_UNIT_SCOPE:
            break done;
        }
        scope = scope.parent;
    }

    if (insideStaticContext && options.sourceLevel >= ClassFileConstants.JDK1_5) {
        if (foundProblem != null) {
            if (foundProblem.declaringClass != null
                    && foundProblem.declaringClass.id == TypeIds.T_JavaLangObject)
                return foundProblem; // static imports lose to methods from Object
            if (foundProblem.problemId() == ProblemReasons.NotFound && foundProblemVisible) {
                return foundProblem; // visible method selectors take precedence
            }
        }

        // at this point the scope is a compilation unit scope & need to check for imported static methods
        CompilationUnitScope unitScope = (CompilationUnitScope) scope;
        unitScope.faultInImports(); // field constants can cause static imports to be accessed before they're resolved
        ImportBinding[] imports = unitScope.imports;
        if (imports != null) {
            ObjectVector visible = null;
            boolean skipOnDemand = false; // set to true when matched static import of method name so stop looking for on demand methods
            for (int i = 0, length = imports.length; i < length; i++) {
                ImportBinding importBinding = imports[i];
                if (importBinding.isStatic()) {
                    Binding resolvedImport = importBinding.resolvedImport;
                    MethodBinding possible = null;
                    if (importBinding.onDemand) {
                        if (!skipOnDemand && resolvedImport instanceof ReferenceBinding)
                            // answers closest approximation, may not check argumentTypes or visibility
                            possible = findMethod((ReferenceBinding) resolvedImport, selector, argumentTypes,
                                    invocationSite, true);
                    } else {
                        if (resolvedImport instanceof MethodBinding) {
                            MethodBinding staticMethod = (MethodBinding) resolvedImport;
                            if (CharOperation.equals(staticMethod.selector, selector))
                                // answers closest approximation, may not check argumentTypes or visibility
                                possible = findMethod(staticMethod.declaringClass, selector, argumentTypes,
                                        invocationSite, true);
                        } else if (resolvedImport instanceof FieldBinding) {
                            // check to see if there are also methods with the same name
                            FieldBinding staticField = (FieldBinding) resolvedImport;
                            if (CharOperation.equals(staticField.name, selector)) {
                                // must find the importRef's type again since the field can be from an inherited type
                                char[][] importName = importBinding.reference.tokens;
                                TypeBinding referencedType = getType(importName, importName.length - 1);
                                if (referencedType != null)
                                    // answers closest approximation, may not check argumentTypes or visibility
                                    possible = findMethod((ReferenceBinding) referencedType, selector,
                                            argumentTypes, invocationSite, true);
                            }
                        }
                    }
                    if (possible != null && possible != foundProblem) {
                        if (!possible.isValidBinding()) {
                            if (foundProblem == null)
                                foundProblem = possible; // answer as error case match
                        } else if (possible.isStatic()) {
                            MethodBinding compatibleMethod = computeCompatibleMethod(possible, argumentTypes,
                                    invocationSite);
                            if (compatibleMethod != null) {
                                if (compatibleMethod.isValidBinding()) {
                                    if (compatibleMethod.canBeSeenBy(unitScope.fPackage)) {
                                        if (visible == null || !visible.contains(compatibleMethod)) {
                                            ImportReference importReference = importBinding.reference;
                                            if (importReference != null) {
                                                importReference.bits |= ASTNode.Used;
                                            }
                                            if (!skipOnDemand && !importBinding.onDemand) {
                                                visible = null; // forget previous matches from on demand imports
                                                skipOnDemand = true;
                                            }
                                            if (visible == null)
                                                visible = new ObjectVector(3);
                                            visible.add(compatibleMethod);
                                        }
                                    } else if (foundProblem == null) {
                                        foundProblem = new ProblemMethodBinding(compatibleMethod, selector,
                                                compatibleMethod.parameters, ProblemReasons.NotVisible);
                                    }
                                } else if (foundProblem == null) {
                                    foundProblem = compatibleMethod;
                                }
                            } else if (foundProblem == null) {
                                foundProblem = new ProblemMethodBinding(possible, selector, argumentTypes,
                                        ProblemReasons.NotFound);
                            }
                        }
                    }
                }
            }
            if (visible != null) {
                MethodBinding[] temp = new MethodBinding[visible.size];
                visible.copyInto(temp);
                foundMethod = mostSpecificMethodBinding(temp, temp.length, argumentTypes, invocationSite, null);
            }
        }
    }

    if (foundMethod != null) {
        invocationSite.setActualReceiverType(foundMethod.declaringClass);
        return foundMethod;
    }
    if (foundProblem != null)
        return foundProblem;

    return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
}

From source file:org.eclipse.jdt.internal.core.JavaProject.java

License:Open Source License

/**
 * Internal computation of an expanded classpath. It will eliminate duplicates, and produce copies
 * of exported or restricted classpath entries to avoid possible side-effects ever after.
 *//*from w  ww. j a  v  a 2  s.  c  o m*/
private void computeExpandedClasspath(ClasspathEntry referringEntry, HashSet rootIDs,
        ObjectVector accumulatedEntries) throws JavaModelException {

    String projectRootId = rootID();
    if (rootIDs.contains(projectRootId)) {
        return; // break cycles if any
    }
    rootIDs.add(projectRootId);

    IClasspathEntry[] resolvedClasspath = getResolvedClasspath();

    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    boolean isInitialProject = referringEntry == null;
    for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
        ClasspathEntry entry = (ClasspathEntry) resolvedClasspath[i];
        if (isInitialProject || entry.isExported()) {
            String rootID = entry.rootID();
            if (rootIDs.contains(rootID)) {
                continue;
            }
            // combine restrictions along the project chain
            ClasspathEntry combinedEntry = entry.combineWith(referringEntry);
            accumulatedEntries.add(combinedEntry);

            // recurse in project to get all its indirect exports (only consider exported entries from there on)
            if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IResource member = workspaceRoot.findMember(entry.getPath());
                if (member != null && member.getType() == IResource.PROJECT) { // double check if bound to project (23977)
                    IProject projRsc = (IProject) member;
                    if (JavaProject.hasJavaNature(projRsc)) {
                        JavaProject javaProject = (JavaProject) JavaCore.create(projRsc);
                        javaProject.computeExpandedClasspath(combinedEntry, rootIDs, accumulatedEntries);
                    }
                }
            } else {
                rootIDs.add(rootID);
            }
        }
    }
}

From source file:org.eclipse.jdt.internal.core.JavaProject.java

License:Open Source License

/**
 * Returns the package fragment roots identified by the given entry. In case it refers to
 * a project, it will follow its classpath so as to find exported roots as well.
 * Only works with resolved entry/* w w w . j a v a  2  s  . c o  m*/
 * @param resolvedEntry IClasspathEntry
 * @param accumulatedRoots ObjectVector
 * @param rootIDs HashSet
 * @param referringEntry the CP entry (project) referring to this entry, or null if initial project
 * @param retrieveExportedRoots boolean
 * @throws JavaModelException
 */
public void computePackageFragmentRoots(IClasspathEntry resolvedEntry, ObjectVector accumulatedRoots,
        HashSet rootIDs, IClasspathEntry referringEntry, boolean retrieveExportedRoots,
        Map rootToResolvedEntries) throws JavaModelException {

    String rootID = ((ClasspathEntry) resolvedEntry).rootID();
    if (rootIDs.contains(rootID))
        return;

    IPath projectPath = this.project.getFullPath();
    IPath entryPath = resolvedEntry.getPath();
    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IPackageFragmentRoot root = null;

    switch (resolvedEntry.getEntryKind()) {

    // source folder
    case IClasspathEntry.CPE_SOURCE:

        if (projectPath.isPrefixOf(entryPath)) {
            Object target = JavaModel.getTarget(entryPath, true/*check existency*/);
            if (target == null)
                return;

            if (target instanceof IFolder || target instanceof IProject) {
                root = getPackageFragmentRoot((IResource) target);
            }
        }
        break;

    // internal/external JAR or folder
    case IClasspathEntry.CPE_LIBRARY:
        if (referringEntry != null && !resolvedEntry.isExported())
            return;
        Object target = JavaModel.getTarget(entryPath, true/*check existency*/);
        if (target == null)
            return;

        if (target instanceof IResource) {
            // internal target
            root = getPackageFragmentRoot((IResource) target, entryPath);
        } else if (target instanceof File) {
            // external target
            if (JavaModel.isFile(target)) {
                root = new JarPackageFragmentRoot(entryPath, this);
            } else if (((File) target).isDirectory()) {
                root = new ExternalPackageFragmentRoot(entryPath, this);
            }
        }
        break;

    // recurse into required project
    case IClasspathEntry.CPE_PROJECT:

        if (!retrieveExportedRoots)
            return;
        if (referringEntry != null && !resolvedEntry.isExported())
            return;

        IResource member = workspaceRoot.findMember(entryPath);
        if (member != null && member.getType() == IResource.PROJECT) {// double check if bound to project (23977)
            IProject requiredProjectRsc = (IProject) member;
            if (JavaProject.hasJavaNature(requiredProjectRsc)) { // special builder binary output
                rootIDs.add(rootID);
                JavaProject requiredProject = (JavaProject) JavaCore.create(requiredProjectRsc);
                requiredProject.computePackageFragmentRoots(requiredProject.getResolvedClasspath(),
                        accumulatedRoots, rootIDs,
                        rootToResolvedEntries == null ? resolvedEntry
                                : ((ClasspathEntry) resolvedEntry).combineWith((ClasspathEntry) referringEntry), // only combine if need to build the reverse map
                        retrieveExportedRoots, rootToResolvedEntries);
            }
            break;
        }
    }
    if (root != null) {
        accumulatedRoots.add(root);
        rootIDs.add(rootID);
        if (rootToResolvedEntries != null)
            rootToResolvedEntries.put(root,
                    ((ClasspathEntry) resolvedEntry).combineWith((ClasspathEntry) referringEntry));
    }
}