Example usage for org.eclipse.jdt.internal.compiler.lookup Binding ARRAY_TYPE

List of usage examples for org.eclipse.jdt.internal.compiler.lookup Binding ARRAY_TYPE

Introduction

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

Prototype

int ARRAY_TYPE

To view the source code for org.eclipse.jdt.internal.compiler.lookup Binding ARRAY_TYPE.

Click Source Link

Usage

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

License:Open Source License

/**
 * Returns a type where either all variables or specific ones got discarded.
 * e.g. List<E> (discarding <E extends Enum<E>) will return:  List<? extends Enum<?>>
 *///from  w w w .  j  a  v  a2  s. com
public static TypeBinding convertEliminatingTypeVariables(TypeBinding originalType,
        ReferenceBinding genericType, int rank, Set eliminatedVariables) {
    if ((originalType.tagBits & TagBits.HasTypeVariable) != 0) {
        switch (originalType.kind()) {
        case Binding.ARRAY_TYPE:
            ArrayBinding originalArrayType = (ArrayBinding) originalType;
            TypeBinding originalLeafComponentType = originalArrayType.leafComponentType;
            TypeBinding substitute = convertEliminatingTypeVariables(originalLeafComponentType, genericType,
                    rank, eliminatedVariables); // substitute could itself be array type
            if (substitute != originalLeafComponentType) {
                return originalArrayType.environment.createArrayType(substitute.leafComponentType(),
                        substitute.dimensions() + originalArrayType.dimensions());
            }
            break;
        case Binding.PARAMETERIZED_TYPE:
            ParameterizedTypeBinding paramType = (ParameterizedTypeBinding) originalType;
            ReferenceBinding originalEnclosing = paramType.enclosingType();
            ReferenceBinding substitutedEnclosing = originalEnclosing;
            if (originalEnclosing != null) {
                substitutedEnclosing = (ReferenceBinding) convertEliminatingTypeVariables(originalEnclosing,
                        genericType, rank, eliminatedVariables);
            }
            TypeBinding[] originalArguments = paramType.arguments;
            TypeBinding[] substitutedArguments = originalArguments;
            for (int i = 0, length = originalArguments == null ? 0
                    : originalArguments.length; i < length; i++) {
                TypeBinding originalArgument = originalArguments[i];
                TypeBinding substitutedArgument = convertEliminatingTypeVariables(originalArgument,
                        paramType.genericType(), i, eliminatedVariables);
                if (substitutedArgument != originalArgument) {
                    if (substitutedArguments == originalArguments) {
                        System.arraycopy(originalArguments, 0, substitutedArguments = new TypeBinding[length],
                                0, i);
                    }
                    substitutedArguments[i] = substitutedArgument;
                } else if (substitutedArguments != originalArguments) {
                    substitutedArguments[i] = originalArgument;
                }
            }
            if (originalEnclosing != substitutedEnclosing || originalArguments != substitutedArguments) {
                return paramType.environment.createParameterizedType(paramType.genericType(),
                        substitutedArguments, substitutedEnclosing);
            }
            break;
        case Binding.TYPE_PARAMETER:
            if (genericType == null) {
                break;
            }
            TypeVariableBinding originalVariable = (TypeVariableBinding) originalType;
            if (eliminatedVariables != null && eliminatedVariables.contains(originalType)) {
                return originalVariable.environment.createWildcard(genericType, rank, null, null,
                        Wildcard.UNBOUND);
            }
            TypeBinding originalUpperBound = originalVariable.upperBound();
            if (eliminatedVariables == null) {
                eliminatedVariables = new HashSet(2);
            }
            eliminatedVariables.add(originalVariable);
            TypeBinding substitutedUpperBound = convertEliminatingTypeVariables(originalUpperBound, genericType,
                    rank, eliminatedVariables);
            eliminatedVariables.remove(originalVariable);
            return originalVariable.environment.createWildcard(genericType, rank, substitutedUpperBound, null,
                    Wildcard.EXTENDS);
        case Binding.RAW_TYPE:
            break;
        case Binding.GENERIC_TYPE:
            ReferenceBinding currentType = (ReferenceBinding) originalType;
            originalEnclosing = currentType.enclosingType();
            substitutedEnclosing = originalEnclosing;
            if (originalEnclosing != null) {
                substitutedEnclosing = (ReferenceBinding) convertEliminatingTypeVariables(originalEnclosing,
                        genericType, rank, eliminatedVariables);
            }
            originalArguments = currentType.typeVariables();
            substitutedArguments = originalArguments;
            for (int i = 0, length = originalArguments == null ? 0
                    : originalArguments.length; i < length; i++) {
                TypeBinding originalArgument = originalArguments[i];
                TypeBinding substitutedArgument = convertEliminatingTypeVariables(originalArgument, currentType,
                        i, eliminatedVariables);
                if (substitutedArgument != originalArgument) {
                    if (substitutedArguments == originalArguments) {
                        System.arraycopy(originalArguments, 0, substitutedArguments = new TypeBinding[length],
                                0, i);
                    }
                    substitutedArguments[i] = substitutedArgument;
                } else if (substitutedArguments != originalArguments) {
                    substitutedArguments[i] = originalArgument;
                }
            }
            if (originalEnclosing != substitutedEnclosing || originalArguments != substitutedArguments) {
                return ((TypeVariableBinding) originalArguments[0]).environment
                        .createParameterizedType(genericType, substitutedArguments, substitutedEnclosing);
            }
            break;
        case Binding.WILDCARD_TYPE:
            WildcardBinding wildcard = (WildcardBinding) originalType;
            TypeBinding originalBound = wildcard.bound;
            TypeBinding substitutedBound = originalBound;
            if (originalBound != null) {
                substitutedBound = convertEliminatingTypeVariables(originalBound, genericType, rank,
                        eliminatedVariables);
                if (substitutedBound != originalBound) {
                    return wildcard.environment.createWildcard(wildcard.genericType, wildcard.rank,
                            substitutedBound, null, wildcard.boundKind);
                }
            }
            break;
        case Binding.INTERSECTION_TYPE:
            WildcardBinding intersection = (WildcardBinding) originalType;
            originalBound = intersection.bound;
            substitutedBound = originalBound;
            if (originalBound != null) {
                substitutedBound = convertEliminatingTypeVariables(originalBound, genericType, rank,
                        eliminatedVariables);
            }
            TypeBinding[] originalOtherBounds = intersection.otherBounds;
            TypeBinding[] substitutedOtherBounds = originalOtherBounds;
            for (int i = 0, length = originalOtherBounds == null ? 0
                    : originalOtherBounds.length; i < length; i++) {
                TypeBinding originalOtherBound = originalOtherBounds[i];
                TypeBinding substitutedOtherBound = convertEliminatingTypeVariables(originalOtherBound,
                        genericType, rank, eliminatedVariables);
                if (substitutedOtherBound != originalOtherBound) {
                    if (substitutedOtherBounds == originalOtherBounds) {
                        System.arraycopy(originalOtherBounds, 0,
                                substitutedOtherBounds = new TypeBinding[length], 0, i);
                    }
                    substitutedOtherBounds[i] = substitutedOtherBound;
                } else if (substitutedOtherBounds != originalOtherBounds) {
                    substitutedOtherBounds[i] = originalOtherBound;
                }
            }
            if (substitutedBound != originalBound || substitutedOtherBounds != originalOtherBounds) {
                return intersection.environment.createWildcard(intersection.genericType, intersection.rank,
                        substitutedBound, substitutedOtherBounds, intersection.boundKind);
            }
            break;
        }
    }
    return originalType;
}

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

License:Open Source License

/**
 * Returns a type, where original type was substituted using the receiver
 * parameterized type.//from w w  w. ja v a  2  s.c  om
 * In raw mode, all parameterized type denoting same original type are converted
 * to raw types. e.g.
 * class X <T> {
 *   X<T> foo;
 *   X<String> bar;
 * } when used in raw fashion, then type of both foo and bar is raw type X.
 *
 */
public static TypeBinding substitute(Substitution substitution, TypeBinding originalType) {
    if (originalType == null)
        return null;
    switch (originalType.kind()) {

    case Binding.TYPE_PARAMETER:
        return substitution.substitute((TypeVariableBinding) originalType);

    case Binding.PARAMETERIZED_TYPE:
        ParameterizedTypeBinding originalParameterizedType = (ParameterizedTypeBinding) originalType;
        ReferenceBinding originalEnclosing = originalType.enclosingType();
        ReferenceBinding substitutedEnclosing = originalEnclosing;
        if (originalEnclosing != null) {
            substitutedEnclosing = (ReferenceBinding) substitute(substitution, originalEnclosing);
        }
        TypeBinding[] originalArguments = originalParameterizedType.arguments;
        TypeBinding[] substitutedArguments = originalArguments;
        if (originalArguments != null) {
            if (substitution.isRawSubstitution()) {
                return originalParameterizedType.environment
                        .createRawType(originalParameterizedType.genericType(), substitutedEnclosing);
            }
            substitutedArguments = substitute(substitution, originalArguments);
        }
        if (substitutedArguments != originalArguments || substitutedEnclosing != originalEnclosing) {
            return originalParameterizedType.environment.createParameterizedType(
                    originalParameterizedType.genericType(), substitutedArguments, substitutedEnclosing);
        }
        break;

    case Binding.ARRAY_TYPE:
        ArrayBinding originalArrayType = (ArrayBinding) originalType;
        TypeBinding originalLeafComponentType = originalArrayType.leafComponentType;
        TypeBinding substitute = substitute(substitution, originalLeafComponentType); // substitute could itself be array type
        if (substitute != originalLeafComponentType) {
            return originalArrayType.environment.createArrayType(substitute.leafComponentType(),
                    substitute.dimensions() + originalType.dimensions());
        }
        break;

    case Binding.WILDCARD_TYPE:
    case Binding.INTERSECTION_TYPE:
        WildcardBinding wildcard = (WildcardBinding) originalType;
        if (wildcard.boundKind != Wildcard.UNBOUND) {
            TypeBinding originalBound = wildcard.bound;
            TypeBinding substitutedBound = substitute(substitution, originalBound);
            TypeBinding[] originalOtherBounds = wildcard.otherBounds;
            TypeBinding[] substitutedOtherBounds = substitute(substitution, originalOtherBounds);
            if (substitutedBound != originalBound || originalOtherBounds != substitutedOtherBounds) {
                if (originalOtherBounds != null) {
                    /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=347145: the constituent intersecting types have changed
                       in the last round of substitution. Reevaluate the composite intersection type, as there is a possibility
                       of the intersection collapsing into one of the constituents, the other being fully subsumed.
                    */
                    TypeBinding[] bounds = new TypeBinding[1 + substitutedOtherBounds.length];
                    bounds[0] = substitutedBound;
                    System.arraycopy(substitutedOtherBounds, 0, bounds, 1, substitutedOtherBounds.length);
                    TypeBinding[] glb = Scope.greaterLowerBound(bounds); // re-evaluate
                    if (glb != null && glb != bounds) {
                        substitutedBound = glb[0];
                        if (glb.length == 1) {
                            substitutedOtherBounds = null;
                        } else {
                            System.arraycopy(glb, 1, substitutedOtherBounds = new TypeBinding[glb.length - 1],
                                    0, glb.length - 1);
                        }
                    }
                }
                return wildcard.environment.createWildcard(wildcard.genericType, wildcard.rank,
                        substitutedBound, substitutedOtherBounds, wildcard.boundKind);
            }
        }
        break;

    case Binding.TYPE:
        if (!originalType.isMemberType())
            break;
        ReferenceBinding originalReferenceType = (ReferenceBinding) originalType;
        originalEnclosing = originalType.enclosingType();
        substitutedEnclosing = originalEnclosing;
        if (originalEnclosing != null) {
            substitutedEnclosing = (ReferenceBinding) substitute(substitution, originalEnclosing);
        }

        // treat as if parameterized with its type variables (non generic type gets 'null' arguments)
        if (substitutedEnclosing != originalEnclosing) {
            return substitution.isRawSubstitution()
                    ? substitution.environment().createRawType(originalReferenceType, substitutedEnclosing)
                    : substitution.environment().createParameterizedType(originalReferenceType, null,
                            substitutedEnclosing);
        }
        break;
    case Binding.GENERIC_TYPE:
        originalReferenceType = (ReferenceBinding) originalType;
        originalEnclosing = originalType.enclosingType();
        substitutedEnclosing = originalEnclosing;
        if (originalEnclosing != null) {
            substitutedEnclosing = (ReferenceBinding) substitute(substitution, originalEnclosing);
        }

        if (substitution.isRawSubstitution()) {
            return substitution.environment().createRawType(originalReferenceType, substitutedEnclosing);
        }
        // treat as if parameterized with its type variables (non generic type gets 'null' arguments)
        originalArguments = originalReferenceType.typeVariables();
        substitutedArguments = substitute(substitution, originalArguments);
        return substitution.environment().createParameterizedType(originalReferenceType, substitutedArguments,
                substitutedEnclosing);
    }
    return originalType;
}

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

License:Open Source License

/**
 * Connect type variable supertypes, and returns true if no problem was detected
 * @param typeParameters//from   w ww.j  a  v a2s .  c  om
 * @param checkForErasedCandidateCollisions
 */
protected boolean connectTypeVariables(TypeParameter[] typeParameters,
        boolean checkForErasedCandidateCollisions) {
    /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=305259 - We used to not bother with connecting
       type variables if source level is < 1.5. This creates problems in the reconciler if a 1.4
       project references the generified API of a 1.5 project. The "current" project's source
       level cannot decide this question for some other project. Now, if we see type parameters
       at all, we assume that the concerned java element has some legitimate business with them.
     */
    if (typeParameters == null || typeParameters.length == 0)
        return true;
    Map invocations = new HashMap(2);
    boolean noProblems = true;
    // preinitializing each type variable
    for (int i = 0, paramLength = typeParameters.length; i < paramLength; i++) {
        TypeParameter typeParameter = typeParameters[i];
        TypeVariableBinding typeVariable = typeParameter.binding;
        if (typeVariable == null)
            return false;

        typeVariable.superclass = getJavaLangObject();
        typeVariable.superInterfaces = Binding.NO_SUPERINTERFACES;
        // set firstBound to the binding of the first explicit bound in parameter declaration
        typeVariable.firstBound = null; // first bound used to compute erasure
    }
    nextVariable: for (int i = 0, paramLength = typeParameters.length; i < paramLength; i++) {
        TypeParameter typeParameter = typeParameters[i];
        TypeVariableBinding typeVariable = typeParameter.binding;
        TypeReference typeRef = typeParameter.type;
        if (typeRef == null)
            continue nextVariable;
        boolean isFirstBoundTypeVariable = false;
        TypeBinding superType = this.kind == METHOD_SCOPE
                ? typeRef.resolveType((BlockScope) this, false/*no bound check*/)
                : typeRef.resolveType((ClassScope) this);
        if (superType == null) {
            typeVariable.tagBits |= TagBits.HierarchyHasProblems;
        } else {
            typeRef.resolvedType = superType; // hold onto the problem type
            firstBound: {
                switch (superType.kind()) {
                case Binding.ARRAY_TYPE:
                    problemReporter().boundCannotBeArray(typeRef, superType);
                    typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                    break firstBound; // do not keep first bound
                case Binding.TYPE_PARAMETER:
                    isFirstBoundTypeVariable = true;
                    TypeVariableBinding varSuperType = (TypeVariableBinding) superType;
                    if (varSuperType.rank >= typeVariable.rank
                            && varSuperType.declaringElement == typeVariable.declaringElement) {
                        if (compilerOptions().complianceLevel <= ClassFileConstants.JDK1_6) {
                            problemReporter().forwardTypeVariableReference(typeParameter, varSuperType);
                            typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                            break firstBound; // do not keep first bound
                        }
                    }
                    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=335751
                    if (compilerOptions().complianceLevel > ClassFileConstants.JDK1_6) {
                        if (typeVariable.rank >= varSuperType.rank
                                && varSuperType.declaringElement == typeVariable.declaringElement) {
                            SimpleSet set = new SimpleSet(typeParameters.length);
                            set.add(typeVariable);
                            ReferenceBinding superBinding = varSuperType;
                            while (superBinding instanceof TypeVariableBinding) {
                                if (set.includes(superBinding)) {
                                    problemReporter().hierarchyCircularity(typeVariable, varSuperType, typeRef);
                                    typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                                    break firstBound; // do not keep first bound
                                } else {
                                    set.add(superBinding);
                                    superBinding = ((TypeVariableBinding) superBinding).superclass;
                                }
                            }
                        }
                    }
                    break;
                default:
                    if (((ReferenceBinding) superType).isFinal()) {
                        problemReporter().finalVariableBound(typeVariable, typeRef);
                    }
                    break;
                }
                ReferenceBinding superRefType = (ReferenceBinding) superType;
                if (!superType.isInterface()) {
                    typeVariable.superclass = superRefType;
                } else {
                    typeVariable.superInterfaces = new ReferenceBinding[] { superRefType };
                }
                typeVariable.tagBits |= superType.tagBits & TagBits.ContainsNestedTypeReferences;
                typeVariable.firstBound = superRefType; // first bound used to compute erasure
            }
        }
        TypeReference[] boundRefs = typeParameter.bounds;
        if (boundRefs != null) {
            nextBound: for (int j = 0, boundLength = boundRefs.length; j < boundLength; j++) {
                typeRef = boundRefs[j];
                superType = this.kind == METHOD_SCOPE ? typeRef.resolveType((BlockScope) this, false)
                        : typeRef.resolveType((ClassScope) this);
                if (superType == null) {
                    typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                    continue nextBound;
                } else {
                    typeVariable.tagBits |= superType.tagBits & TagBits.ContainsNestedTypeReferences;
                    boolean didAlreadyComplain = !typeRef.resolvedType.isValidBinding();
                    if (isFirstBoundTypeVariable && j == 0) {
                        problemReporter().noAdditionalBoundAfterTypeVariable(typeRef);
                        typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                        didAlreadyComplain = true;
                        //continue nextBound; - keep these bounds to minimize secondary errors
                    } else if (superType.isArrayType()) {
                        if (!didAlreadyComplain) {
                            problemReporter().boundCannotBeArray(typeRef, superType);
                            typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                        }
                        continue nextBound;
                    } else {
                        if (!superType.isInterface()) {
                            if (!didAlreadyComplain) {
                                problemReporter().boundMustBeAnInterface(typeRef, superType);
                                typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                            }
                            continue nextBound;
                        }
                    }
                    // check against superclass
                    if (checkForErasedCandidateCollisions
                            && typeVariable.firstBound == typeVariable.superclass) {
                        if (hasErasedCandidatesCollisions(superType, typeVariable.superclass, invocations,
                                typeVariable, typeRef)) {
                            continue nextBound;
                        }
                    }
                    // check against superinterfaces
                    ReferenceBinding superRefType = (ReferenceBinding) superType;
                    for (int index = typeVariable.superInterfaces.length; --index >= 0;) {
                        ReferenceBinding previousInterface = typeVariable.superInterfaces[index];
                        if (previousInterface == superRefType) {
                            problemReporter().duplicateBounds(typeRef, superType);
                            typeVariable.tagBits |= TagBits.HierarchyHasProblems;
                            continue nextBound;
                        }
                        if (checkForErasedCandidateCollisions) {
                            if (hasErasedCandidatesCollisions(superType, previousInterface, invocations,
                                    typeVariable, typeRef)) {
                                continue nextBound;
                            }
                        }
                    }
                    int size = typeVariable.superInterfaces.length;
                    System.arraycopy(typeVariable.superInterfaces, 0,
                            typeVariable.superInterfaces = new ReferenceBinding[size + 1], 0, size);
                    typeVariable.superInterfaces[size] = superRefType;
                }
            }
        }
        noProblems &= (typeVariable.tagBits & TagBits.HierarchyHasProblems) == 0;
    }
    return noProblems;
}

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

License:Open Source License

public FieldBinding findField(TypeBinding receiverType, char[] fieldName, InvocationSite invocationSite,
        boolean needResolve, boolean invisibleFieldsOk) {

    CompilationUnitScope unitScope = compilationUnitScope();
    unitScope.recordTypeReference(receiverType);

    checkArrayField: {//from  w  ww .j  av  a 2 s .  c  om
        TypeBinding leafType;
        switch (receiverType.kind()) {
        case Binding.BASE_TYPE:
            return null;
        case Binding.WILDCARD_TYPE:
        case Binding.INTERSECTION_TYPE:
        case Binding.TYPE_PARAMETER: // capture
            TypeBinding receiverErasure = receiverType.erasure();
            if (!receiverErasure.isArrayType())
                break checkArrayField;
            leafType = receiverErasure.leafComponentType();
            break;
        case Binding.ARRAY_TYPE:
            leafType = receiverType.leafComponentType();
            break;
        default:
            break checkArrayField;
        }
        if (leafType instanceof ReferenceBinding)
            if (!((ReferenceBinding) leafType).canBeSeenBy(this))
                return new ProblemFieldBinding((ReferenceBinding) leafType, fieldName,
                        ProblemReasons.ReceiverTypeNotVisible);
        if (CharOperation.equals(fieldName, TypeConstants.LENGTH)) {
            if ((leafType.tagBits & TagBits.HasMissingType) != 0) {
                return new ProblemFieldBinding(ArrayBinding.ArrayLength, null, fieldName,
                        ProblemReasons.NotFound);
            }
            return ArrayBinding.ArrayLength;
        }
        return null;
    }

    ReferenceBinding currentType = (ReferenceBinding) receiverType;
    if (!currentType.canBeSeenBy(this))
        return new ProblemFieldBinding(currentType, fieldName, ProblemReasons.ReceiverTypeNotVisible);

    currentType.initializeForStaticImports();
    FieldBinding field = currentType.getField(fieldName, needResolve);
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=316456
    boolean insideTypeAnnotations = this instanceof MethodScope && ((MethodScope) this).insideTypeAnnotation;
    if (field != null) {
        if (invisibleFieldsOk) {
            return field;
        }
        if (invocationSite == null || insideTypeAnnotations ? field.canBeSeenBy(getCurrentPackage())
                : field.canBeSeenBy(currentType, invocationSite, this))
            return field;
        return new ProblemFieldBinding(field /* closest match*/, field.declaringClass, fieldName,
                ProblemReasons.NotVisible);
    }
    // collect all superinterfaces of receiverType until the field is found in a supertype
    ReferenceBinding[] interfacesToVisit = null;
    int nextPosition = 0;
    FieldBinding visibleField = null;
    boolean keepLooking = true;
    FieldBinding notVisibleField = null;
    // we could hold onto the not visible field for extra error reporting
    while (keepLooking) {
        ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
        if (itsInterfaces != null && itsInterfaces != Binding.NO_SUPERINTERFACES) {
            if (interfacesToVisit == null) {
                interfacesToVisit = itsInterfaces;
                nextPosition = interfacesToVisit.length;
            } else {
                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;
                }
            }
        }
        if ((currentType = currentType.superclass()) == null)
            break;

        unitScope.recordTypeReference(currentType);
        currentType.initializeForStaticImports();
        currentType = (ReferenceBinding) currentType.capture(this,
                invocationSite == null ? 0 : invocationSite.sourceEnd());
        if ((field = currentType.getField(fieldName, needResolve)) != null) {
            if (invisibleFieldsOk) {
                return field;
            }
            keepLooking = false;
            if (field.canBeSeenBy(receiverType, invocationSite, this)) {
                if (visibleField == null)
                    visibleField = field;
                else
                    return new ProblemFieldBinding(visibleField /* closest match*/, visibleField.declaringClass,
                            fieldName, ProblemReasons.Ambiguous);
            } else {
                if (notVisibleField == null)
                    notVisibleField = field;
            }
        }
    }

    // walk all visible interfaces to find ambiguous references
    if (interfacesToVisit != null) {
        ProblemFieldBinding ambiguous = null;
        done: for (int i = 0; i < nextPosition; i++) {
            ReferenceBinding anInterface = interfacesToVisit[i];
            unitScope.recordTypeReference(anInterface);
            // no need to capture rcv interface, since member field is going to be static anyway
            if ((field = anInterface.getField(fieldName, true /*resolve*/)) != null) {
                if (invisibleFieldsOk) {
                    return field;
                }
                if (visibleField == null) {
                    visibleField = field;
                } else {
                    ambiguous = new ProblemFieldBinding(visibleField /* closest match*/,
                            visibleField.declaringClass, fieldName, ProblemReasons.Ambiguous);
                    break done;
                }
            } else {
                ReferenceBinding[] itsInterfaces = anInterface.superInterfaces();
                if (itsInterfaces != 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;
                    }
                }
            }
        }
        if (ambiguous != null)
            return ambiguous;
    }

    if (visibleField != null)
        return visibleField;
    if (notVisibleField != null) {
        return new ProblemFieldBinding(notVisibleField, currentType, fieldName, ProblemReasons.NotVisible);
    }
    return null;
}

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

License:Open Source License

public MethodBinding getMethod(TypeBinding receiverType, char[] selector, TypeBinding[] argumentTypes,
        InvocationSite invocationSite) {
    CompilationUnitScope unitScope = compilationUnitScope();
    LookupEnvironment env = unitScope.environment;
    try {/*from   w w w  .  j  a  v  a  2 s . com*/
        env.missingClassFileLocation = invocationSite;
        switch (receiverType.kind()) {
        case Binding.BASE_TYPE:
            return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
        case Binding.ARRAY_TYPE:
            unitScope.recordTypeReference(receiverType);
            return findMethodForArray((ArrayBinding) receiverType, selector, argumentTypes, invocationSite);
        }
        unitScope.recordTypeReference(receiverType);

        ReferenceBinding currentType = (ReferenceBinding) receiverType;
        if (!currentType.canBeSeenBy(this))
            return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.ReceiverTypeNotVisible);

        // retrieve an exact visible match (if possible)
        MethodBinding methodBinding = findExactMethod(currentType, selector, argumentTypes, invocationSite);
        if (methodBinding != null)
            return methodBinding;

        methodBinding = findMethod(currentType, selector, argumentTypes, invocationSite);
        // GROOVY start: give it one more chance as the ast transform may have introduced it
        // is this the right approach?  Requires ast transforms running before this is done
        if (methodBinding == null) {
            methodBinding = oneLastLook(currentType, selector, argumentTypes, invocationSite);
        }
        // GROOVY end
        if (methodBinding == null)
            return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
        if (!methodBinding.isValidBinding())
            return methodBinding;

        // 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;
    } catch (AbortCompilation e) {
        e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
        throw e;
    } finally {
        env.missingClassFileLocation = null;
    }
}

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

License:Open Source License

/**
 * Returns the most specific set of types compatible with all given types.
 * (i.e. most specific common super types)
 * If no types is given, will return an empty array. If not compatible
 * reference type is found, returns null. In other cases, will return an array
 * of minimal erased types, where some nulls may appear (and must simply be
 * ignored).//  w  ww  .  ja  v  a  2 s. c  om
 */
protected TypeBinding[] minimalErasedCandidates(TypeBinding[] types, Map allInvocations) {
    int length = types.length;
    int indexOfFirst = -1, actualLength = 0;
    for (int i = 0; i < length; i++) {
        TypeBinding type = types[i];
        if (type == null)
            continue;
        if (type.isBaseType())
            return null;
        if (indexOfFirst < 0)
            indexOfFirst = i;
        actualLength++;
    }
    switch (actualLength) {
    case 0:
        return Binding.NO_TYPES;
    case 1:
        return types;
    }
    TypeBinding firstType = types[indexOfFirst];
    if (firstType.isBaseType())
        return null;

    // record all supertypes of type
    // intersect with all supertypes of otherType
    ArrayList typesToVisit = new ArrayList(5);

    int dim = firstType.dimensions();
    TypeBinding leafType = firstType.leafComponentType();
    // do not allow type variables/intersection types to match with erasures for free
    TypeBinding firstErasure;
    switch (leafType.kind()) {
    case Binding.PARAMETERIZED_TYPE:
    case Binding.RAW_TYPE:
    case Binding.ARRAY_TYPE:
        firstErasure = firstType.erasure();
        break;
    default:
        firstErasure = firstType;
        break;
    }
    if (firstErasure != firstType) {
        allInvocations.put(firstErasure, firstType);
    }
    typesToVisit.add(firstType);
    int max = 1;
    ReferenceBinding currentType;
    for (int i = 0; i < max; i++) {
        TypeBinding typeToVisit = (TypeBinding) typesToVisit.get(i);
        dim = typeToVisit.dimensions();
        if (dim > 0) {
            leafType = typeToVisit.leafComponentType();
            switch (leafType.id) {
            case TypeIds.T_JavaLangObject:
                if (dim > 1) { // Object[][] supertype is Object[]
                    TypeBinding elementType = ((ArrayBinding) typeToVisit).elementsType();
                    if (!typesToVisit.contains(elementType)) {
                        typesToVisit.add(elementType);
                        max++;
                    }
                    continue;
                }
                //$FALL-THROUGH$
            case TypeIds.T_byte:
            case TypeIds.T_short:
            case TypeIds.T_char:
            case TypeIds.T_boolean:
            case TypeIds.T_int:
            case TypeIds.T_long:
            case TypeIds.T_float:
            case TypeIds.T_double:
                TypeBinding superType = getJavaIoSerializable();
                if (!typesToVisit.contains(superType)) {
                    typesToVisit.add(superType);
                    max++;
                }
                superType = getJavaLangCloneable();
                if (!typesToVisit.contains(superType)) {
                    typesToVisit.add(superType);
                    max++;
                }
                superType = getJavaLangObject();
                if (!typesToVisit.contains(superType)) {
                    typesToVisit.add(superType);
                    max++;
                }
                continue;

            default:
            }
            typeToVisit = leafType;
        }
        currentType = (ReferenceBinding) typeToVisit;
        if (currentType.isCapture()) {
            TypeBinding firstBound = ((CaptureBinding) currentType).firstBound;
            if (firstBound != null && firstBound.isArrayType()) {
                TypeBinding superType = dim == 0 ? firstBound
                        : (TypeBinding) environment().createArrayType(firstBound, dim); // recreate array if needed
                if (!typesToVisit.contains(superType)) {
                    typesToVisit.add(superType);
                    max++;
                    TypeBinding superTypeErasure = (firstBound.isTypeVariable()
                            || firstBound.isWildcard() /*&& !itsInterface.isCapture()*/) ? superType
                                    : superType.erasure();
                    if (superTypeErasure != superType) {
                        allInvocations.put(superTypeErasure, superType);
                    }
                }
                continue;
            }
        }
        // inject super interfaces prior to superclass
        ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
        if (itsInterfaces != null) { // can be null during code assist operations that use LookupEnvironment.completeTypeBindings(parsedUnit, buildFieldsAndMethods)
            for (int j = 0, count = itsInterfaces.length; j < count; j++) {
                TypeBinding itsInterface = itsInterfaces[j];
                TypeBinding superType = dim == 0 ? itsInterface
                        : (TypeBinding) environment().createArrayType(itsInterface, dim); // recreate array if needed
                if (!typesToVisit.contains(superType)) {
                    typesToVisit.add(superType);
                    max++;
                    TypeBinding superTypeErasure = (itsInterface.isTypeVariable()
                            || itsInterface.isWildcard() /*&& !itsInterface.isCapture()*/) ? superType
                                    : superType.erasure();
                    if (superTypeErasure != superType) {
                        allInvocations.put(superTypeErasure, superType);
                    }
                }
            }
        }
        TypeBinding itsSuperclass = currentType.superclass();
        if (itsSuperclass != null) {
            TypeBinding superType = dim == 0 ? itsSuperclass
                    : (TypeBinding) environment().createArrayType(itsSuperclass, dim); // recreate array if needed
            if (!typesToVisit.contains(superType)) {
                typesToVisit.add(superType);
                max++;
                TypeBinding superTypeErasure = (itsSuperclass.isTypeVariable()
                        || itsSuperclass.isWildcard() /*&& !itsSuperclass.isCapture()*/) ? superType
                                : superType.erasure();
                if (superTypeErasure != superType) {
                    allInvocations.put(superTypeErasure, superType);
                }
            }
        }
    }
    int superLength = typesToVisit.size();
    TypeBinding[] erasedSuperTypes = new TypeBinding[superLength];
    int rank = 0;
    for (Iterator iter = typesToVisit.iterator(); iter.hasNext();) {
        TypeBinding type = (TypeBinding) iter.next();
        leafType = type.leafComponentType();
        erasedSuperTypes[rank++] = (leafType.isTypeVariable()
                || leafType.isWildcard() /*&& !leafType.isCapture()*/) ? type : type.erasure();
    }
    // intersecting first type supertypes with other types' ones, nullifying non matching supertypes
    int remaining = superLength;
    nextOtherType: for (int i = indexOfFirst + 1; i < length; i++) {
        TypeBinding otherType = types[i];
        if (otherType == null)
            continue nextOtherType;
        if (otherType.isArrayType()) {
            nextSuperType: for (int j = 0; j < superLength; j++) {
                TypeBinding erasedSuperType = erasedSuperTypes[j];
                if (erasedSuperType == null || erasedSuperType == otherType)
                    continue nextSuperType;
                TypeBinding match;
                if ((match = otherType.findSuperTypeOriginatingFrom(erasedSuperType)) == null) {
                    erasedSuperTypes[j] = null;
                    if (--remaining == 0)
                        return null;
                    continue nextSuperType;
                }
                // record invocation
                Object invocationData = allInvocations.get(erasedSuperType);
                if (invocationData == null) {
                    allInvocations.put(erasedSuperType, match); // no array for singleton
                } else if (invocationData instanceof TypeBinding) {
                    if (match != invocationData) {
                        // using an array to record invocations in order (188103)
                        TypeBinding[] someInvocations = { (TypeBinding) invocationData, match, };
                        allInvocations.put(erasedSuperType, someInvocations);
                    }
                } else { // using an array to record invocations in order (188103)
                    TypeBinding[] someInvocations = (TypeBinding[]) invocationData;
                    checkExisting: {
                        int invocLength = someInvocations.length;
                        for (int k = 0; k < invocLength; k++) {
                            if (someInvocations[k] == match)
                                break checkExisting;
                        }
                        System.arraycopy(someInvocations, 0, someInvocations = new TypeBinding[invocLength + 1],
                                0, invocLength);
                        allInvocations.put(erasedSuperType, someInvocations);
                        someInvocations[invocLength] = match;
                    }
                }
            }
            continue nextOtherType;
        }
        nextSuperType: for (int j = 0; j < superLength; j++) {
            TypeBinding erasedSuperType = erasedSuperTypes[j];
            if (erasedSuperType == null)
                continue nextSuperType;
            TypeBinding match;
            if (erasedSuperType == otherType
                    || erasedSuperType.id == TypeIds.T_JavaLangObject && otherType.isInterface()) {
                match = erasedSuperType;
            } else {
                if (erasedSuperType.isArrayType()) {
                    match = null;
                } else {
                    match = otherType.findSuperTypeOriginatingFrom(erasedSuperType);
                }
                if (match == null) { // incompatible super type
                    erasedSuperTypes[j] = null;
                    if (--remaining == 0)
                        return null;
                    continue nextSuperType;
                }
            }
            // record invocation
            Object invocationData = allInvocations.get(erasedSuperType);
            if (invocationData == null) {
                allInvocations.put(erasedSuperType, match); // no array for singleton
            } else if (invocationData instanceof TypeBinding) {
                if (match != invocationData) {
                    // using an array to record invocations in order (188103)
                    TypeBinding[] someInvocations = { (TypeBinding) invocationData, match, };
                    allInvocations.put(erasedSuperType, someInvocations);
                }
            } else { // using an array to record invocations in order (188103)
                TypeBinding[] someInvocations = (TypeBinding[]) invocationData;
                checkExisting: {
                    int invocLength = someInvocations.length;
                    for (int k = 0; k < invocLength; k++) {
                        if (someInvocations[k] == match)
                            break checkExisting;
                    }
                    System.arraycopy(someInvocations, 0, someInvocations = new TypeBinding[invocLength + 1], 0,
                            invocLength);
                    allInvocations.put(erasedSuperType, someInvocations);
                    someInvocations[invocLength] = match;
                }
            }
        }
    }
    // eliminate non minimal super types
    if (remaining > 1) {
        nextType: for (int i = 0; i < superLength; i++) {
            TypeBinding erasedSuperType = erasedSuperTypes[i];
            if (erasedSuperType == null)
                continue nextType;
            nextOtherType: for (int j = 0; j < superLength; j++) {
                if (i == j)
                    continue nextOtherType;
                TypeBinding otherType = erasedSuperTypes[j];
                if (otherType == null)
                    continue nextOtherType;
                if (erasedSuperType instanceof ReferenceBinding) {
                    if (otherType.id == TypeIds.T_JavaLangObject && erasedSuperType.isInterface())
                        continue nextOtherType; // keep Object for an interface
                    if (erasedSuperType.findSuperTypeOriginatingFrom(otherType) != null) {
                        erasedSuperTypes[j] = null; // discard non minimal supertype
                        remaining--;
                    }
                } else if (erasedSuperType.isArrayType()) {
                    if (otherType.isArrayType() // keep Object[...] for an interface array (same dimensions)
                            && otherType.leafComponentType().id == TypeIds.T_JavaLangObject
                            && otherType.dimensions() == erasedSuperType.dimensions()
                            && erasedSuperType.leafComponentType().isInterface())
                        continue nextOtherType;
                    if (erasedSuperType.findSuperTypeOriginatingFrom(otherType) != null) {
                        erasedSuperTypes[j] = null; // discard non minimal supertype
                        remaining--;
                    }
                }
            }
        }
    }
    return erasedSuperTypes;
}

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

License:Open Source License

public MethodBinding getStaticFactory(ReferenceBinding allocationType, ReferenceBinding originalEnclosingType,
        TypeBinding[] argumentTypes, final InvocationSite allocationSite) {
    TypeVariableBinding[] classTypeVariables = allocationType.typeVariables();
    int classTypeVariablesArity = classTypeVariables.length;
    MethodBinding[] methods = allocationType.getMethods(TypeConstants.INIT, argumentTypes.length);
    MethodBinding[] staticFactories = new MethodBinding[methods.length];
    int sfi = 0;/* w  w w.ja va2  s .c  o  m*/
    for (int i = 0, length = methods.length; i < length; i++) {
        MethodBinding method = methods[i];
        int paramLength = method.parameters.length;
        boolean isVarArgs = method.isVarargs();
        if (argumentTypes.length != paramLength)
            if (!isVarArgs || argumentTypes.length < paramLength - 1)
                continue; // incompatible
        TypeVariableBinding[] methodTypeVariables = method.typeVariables();
        int methodTypeVariablesArity = methodTypeVariables.length;

        MethodBinding staticFactory = new MethodBinding(method.modifiers | ClassFileConstants.AccStatic,
                TypeConstants.SYNTHETIC_STATIC_FACTORY, null, null, null, method.declaringClass);
        staticFactory.typeVariables = new TypeVariableBinding[classTypeVariablesArity
                + methodTypeVariablesArity];
        final SimpleLookupTable map = new SimpleLookupTable(classTypeVariablesArity + methodTypeVariablesArity);
        // Rename each type variable T of the type to T'
        final LookupEnvironment environment = environment();
        for (int j = 0; j < classTypeVariablesArity; j++) {
            map.put(classTypeVariables[j],
                    staticFactory.typeVariables[j] = new TypeVariableBinding(
                            CharOperation.concat(classTypeVariables[j].sourceName, "'".toCharArray()), //$NON-NLS-1$
                            staticFactory, j, environment));
        }
        // Rename each type variable U of method U to U''.
        for (int j = classTypeVariablesArity, max = classTypeVariablesArity
                + methodTypeVariablesArity; j < max; j++) {
            map.put(methodTypeVariables[j - classTypeVariablesArity],
                    (staticFactory.typeVariables[j] = new TypeVariableBinding(
                            CharOperation.concat(methodTypeVariables[j - classTypeVariablesArity].sourceName,
                                    "''".toCharArray()), //$NON-NLS-1$
                            staticFactory, j, environment)));
        }
        ReferenceBinding enclosingType = originalEnclosingType;
        while (enclosingType != null) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=345968
            if (enclosingType.kind() == Binding.PARAMETERIZED_TYPE) {
                final ParameterizedTypeBinding parameterizedType = (ParameterizedTypeBinding) enclosingType;
                final ReferenceBinding genericType = parameterizedType.genericType();
                TypeVariableBinding[] enclosingClassTypeVariables = genericType.typeVariables();
                int enclosingClassTypeVariablesArity = enclosingClassTypeVariables.length;
                for (int j = 0; j < enclosingClassTypeVariablesArity; j++) {
                    map.put(enclosingClassTypeVariables[j], parameterizedType.arguments[j]);
                }
            }
            enclosingType = enclosingType.enclosingType();
        }
        final Scope scope = this;
        Substitution substitution = new Substitution() {
            public LookupEnvironment environment() {
                return scope.environment();
            }

            public boolean isRawSubstitution() {
                return false;
            }

            public TypeBinding substitute(TypeVariableBinding typeVariable) {
                TypeBinding retVal = (TypeBinding) map.get(typeVariable);
                return retVal != null ? retVal : typeVariable;
            }
        };

        // initialize new variable bounds
        for (int j = 0, max = classTypeVariablesArity + methodTypeVariablesArity; j < max; j++) {
            TypeVariableBinding originalVariable = j < classTypeVariablesArity ? classTypeVariables[j]
                    : methodTypeVariables[j - classTypeVariablesArity];
            TypeBinding substitutedType = (TypeBinding) map.get(originalVariable);
            if (substitutedType instanceof TypeVariableBinding) {
                TypeVariableBinding substitutedVariable = (TypeVariableBinding) substitutedType;
                TypeBinding substitutedSuperclass = Scope.substitute(substitution, originalVariable.superclass);
                ReferenceBinding[] substitutedInterfaces = Scope.substitute(substitution,
                        originalVariable.superInterfaces);
                if (originalVariable.firstBound != null) {
                    substitutedVariable.firstBound = originalVariable.firstBound == originalVariable.superclass
                            ? substitutedSuperclass // could be array type or interface
                            : substitutedInterfaces[0];
                }
                switch (substitutedSuperclass.kind()) {
                case Binding.ARRAY_TYPE:
                    substitutedVariable.superclass = environment.getResolvedType(TypeConstants.JAVA_LANG_OBJECT,
                            null);
                    substitutedVariable.superInterfaces = substitutedInterfaces;
                    break;
                default:
                    if (substitutedSuperclass.isInterface()) {
                        substitutedVariable.superclass = environment
                                .getResolvedType(TypeConstants.JAVA_LANG_OBJECT, null);
                        int interfaceCount = substitutedInterfaces.length;
                        System.arraycopy(substitutedInterfaces, 0,
                                substitutedInterfaces = new ReferenceBinding[interfaceCount + 1], 1,
                                interfaceCount);
                        substitutedInterfaces[0] = (ReferenceBinding) substitutedSuperclass;
                        substitutedVariable.superInterfaces = substitutedInterfaces;
                    } else {
                        substitutedVariable.superclass = (ReferenceBinding) substitutedSuperclass; // typeVar was extending other typeVar which got substituted with interface
                        substitutedVariable.superInterfaces = substitutedInterfaces;
                    }
                }
            }
        }
        TypeVariableBinding[] returnTypeParameters = new TypeVariableBinding[classTypeVariablesArity];
        for (int j = 0; j < classTypeVariablesArity; j++) {
            returnTypeParameters[j] = (TypeVariableBinding) map.get(classTypeVariables[j]);
        }
        staticFactory.returnType = environment.createParameterizedType(allocationType, returnTypeParameters,
                allocationType.enclosingType());
        staticFactory.parameters = Scope.substitute(substitution, method.parameters);
        staticFactory.thrownExceptions = Scope.substitute(substitution, method.thrownExceptions);
        if (staticFactory.thrownExceptions == null) {
            staticFactory.thrownExceptions = Binding.NO_EXCEPTIONS;
        }
        staticFactories[sfi++] = new ParameterizedMethodBinding(
                (ParameterizedTypeBinding) environment.convertToParameterizedType(staticFactory.declaringClass),
                staticFactory);
    }
    if (sfi == 0)
        return null;
    if (sfi != methods.length) {
        System.arraycopy(staticFactories, 0, staticFactories = new MethodBinding[sfi], 0, sfi);
    }
    MethodBinding[] compatible = new MethodBinding[sfi];
    int compatibleIndex = 0;
    for (int i = 0; i < sfi; i++) {
        MethodBinding compatibleMethod = computeCompatibleMethod(staticFactories[i], argumentTypes,
                allocationSite);
        if (compatibleMethod != null) {
            if (compatibleMethod.isValidBinding())
                compatible[compatibleIndex++] = compatibleMethod;
        }
    }

    if (compatibleIndex == 0) {
        return null;
    }
    MethodBinding[] visible = new MethodBinding[compatibleIndex];
    int visibleIndex = 0;
    for (int i = 0; i < compatibleIndex; i++) {
        MethodBinding method = compatible[i];
        if (method.canBeSeenBy(allocationSite, this))
            visible[visibleIndex++] = method;
    }
    if (visibleIndex == 0) {
        return null;
    }
    return visibleIndex == 1 ? visible[0]
            : mostSpecificMethodBinding(visible, visibleIndex, argumentTypes, allocationSite, allocationType);
}