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

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

Introduction

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

Prototype

int TYPE

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

Click Source Link

Usage

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

License:Open Source License

protected void matchReportReference(ASTNode reference, IJavaElement element, IJavaElement localElement,
        IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator)
        throws CoreException {
    long[] positions = null;
    int last = -1;
    if (reference instanceof ImportReference) {
        ImportReference importRef = (ImportReference) reference;
        positions = importRef.sourcePositions;
        last = (importRef.bits & ASTNode.OnDemand) != 0 ? positions.length : positions.length - 1;
    } else {// w ww .  j a v  a  2s . c  o  m
        TypeBinding typeBinding = null;
        if (reference instanceof QualifiedNameReference) {
            QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
            positions = qNameRef.sourcePositions;
            switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
            case Binding.FIELD: // reading a field
                typeBinding = qNameRef.actualReceiverType;
                break;
            case Binding.TYPE: //=============only type ==============
                if (qNameRef.binding instanceof TypeBinding)
                    typeBinding = (TypeBinding) qNameRef.binding;
                break;
            case Binding.VARIABLE: //============unbound cases===========
            case Binding.TYPE | Binding.VARIABLE:
                Binding binding = qNameRef.binding;
                if (binding instanceof TypeBinding) {
                    typeBinding = (TypeBinding) binding;
                } else if (binding instanceof ProblemFieldBinding) {
                    typeBinding = qNameRef.actualReceiverType;
                    last = qNameRef.tokens.length
                            - (qNameRef.otherBindings == null ? 2 : qNameRef.otherBindings.length + 2);
                } else if (binding instanceof ProblemBinding) {
                    ProblemBinding pbBinding = (ProblemBinding) binding;
                    typeBinding = pbBinding.searchType;
                    last = CharOperation.occurencesOf('.', pbBinding.name);
                }
                break;
            }
        } else if (reference instanceof QualifiedTypeReference) {
            QualifiedTypeReference qTypeRef = (QualifiedTypeReference) reference;
            positions = qTypeRef.sourcePositions;
            typeBinding = qTypeRef.resolvedType;
        } else if (reference instanceof JavadocSingleTypeReference) {
            JavadocSingleTypeReference jsTypeRef = (JavadocSingleTypeReference) reference;
            positions = new long[1];
            positions[0] = (((long) jsTypeRef.sourceStart) << 32) + jsTypeRef.sourceEnd;
            typeBinding = jsTypeRef.resolvedType;
        }
        if (positions == null)
            return;
        if (typeBinding instanceof ArrayBinding)
            typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
        if (typeBinding instanceof ProblemReferenceBinding)
            typeBinding = ((ProblemReferenceBinding) typeBinding).closestMatch();
        if (typeBinding instanceof ReferenceBinding) {
            PackageBinding pkgBinding = ((ReferenceBinding) typeBinding).fPackage;
            if (pkgBinding != null)
                last = pkgBinding.compoundName.length;
        }
        // Do not report qualified references which are only enclosing type
        // (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=91078)
        ReferenceBinding enclosingType = typeBinding == null ? null : typeBinding.enclosingType();
        if (enclosingType != null) {
            int length = positions.length;
            while (enclosingType != null && length > 0) {
                length--;
                enclosingType = enclosingType.enclosingType();
            }
            if (length <= 1)
                return;
        }
    }
    if (last == -1) {
        last = this.pattern.segments.length;
    }
    if (last == 0)
        return;
    if (last > positions.length)
        last = positions.length;
    int sourceStart = (int) (positions[0] >>> 32);
    int sourceEnd = ((int) positions[last - 1]);
    PackageReferenceMatch packageReferenceMatch = locator.newPackageReferenceMatch(element, accuracy,
            sourceStart, sourceEnd - sourceStart + 1, reference);
    packageReferenceMatch.setLocalElement(localElement);
    this.match = packageReferenceMatch;
    locator.report(this.match);
}

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

License:Open Source License

protected int resolveLevel(QualifiedNameReference qNameRef) {
    TypeBinding typeBinding = null;//from   ww w  .j a v  a2s  .c  o  m
    switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
    case Binding.FIELD: // reading a field
        if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 3 : qNameRef.otherBindings.length + 3))
            return IMPOSSIBLE_MATCH; // must be at least p1.A.x
        typeBinding = qNameRef.actualReceiverType;
        break;
    case Binding.LOCAL: // reading a local variable
        return IMPOSSIBLE_MATCH; // no package match in it
    case Binding.TYPE: //=============only type ==============
        if (qNameRef.binding instanceof TypeBinding)
            typeBinding = (TypeBinding) qNameRef.binding;
        break;
    /*
     * Handling of unbound qualified name references. The match may reside in the resolved fragment,
     * which is recorded inside the problem binding, along with the portion of the name until it became a problem.
     */
    case Binding.VARIABLE: //============unbound cases===========
    case Binding.TYPE | Binding.VARIABLE:
        Binding binding = qNameRef.binding;
        if (binding instanceof ProblemReferenceBinding) {
            typeBinding = (TypeBinding) binding;
        } else if (binding instanceof ProblemFieldBinding) {
            if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 3
                    : qNameRef.otherBindings.length + 3))
                return IMPOSSIBLE_MATCH; // must be at least p1.A.x
            typeBinding = qNameRef.actualReceiverType;
        } else if (binding instanceof ProblemBinding) {
            ProblemBinding pbBinding = (ProblemBinding) binding;
            if (CharOperation.occurencesOf('.', pbBinding.name) <= 0) // index of last bound token is one before the pb token
                return INACCURATE_MATCH;
            typeBinding = pbBinding.searchType;
        }
        break;
    }
    return resolveLevel(typeBinding);
}

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

License:Open Source License

protected void matchReportReference(QualifiedNameReference qNameRef, IJavaElement element,
        Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException {
    Binding binding = qNameRef.binding;
    TypeBinding typeBinding = null;//from w ww.j  a va2s. c  o  m
    int lastIndex = qNameRef.tokens.length - 1;
    switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
    case Binding.FIELD: // reading a field
        typeBinding = qNameRef.actualReceiverType;
        lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
        break;
    case Binding.TYPE: //=============only type ==============
        if (binding instanceof TypeBinding)
            typeBinding = (TypeBinding) binding;
        break;
    case Binding.VARIABLE: //============unbound cases===========
    case Binding.TYPE | Binding.VARIABLE:
        if (binding instanceof ProblemReferenceBinding) {
            typeBinding = (TypeBinding) binding;
        } else if (binding instanceof ProblemFieldBinding) {
            typeBinding = qNameRef.actualReceiverType;
            lastIndex -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
        } else if (binding instanceof ProblemBinding) {
            typeBinding = ((ProblemBinding) binding).searchType;
        }
        break;
    }
    if (typeBinding instanceof ProblemReferenceBinding) {
        ProblemReferenceBinding pbBinding = (ProblemReferenceBinding) typeBinding;
        typeBinding = pbBinding.closestMatch();
        lastIndex = pbBinding.compoundName.length - 1;
    }

    // Create search match to report
    if (this.match == null) {
        this.match = locator.newTypeReferenceMatch(element, elementBinding, accuracy, qNameRef);
    }

    // try to match all enclosing types for which the token matches as well.
    if (typeBinding instanceof ReferenceBinding) {
        ReferenceBinding refBinding = (ReferenceBinding) typeBinding;
        while (refBinding != null && lastIndex >= 0) {
            if (resolveLevelForType(refBinding) == ACCURATE_MATCH) {
                if (locator.encloses(element)) {
                    long[] positions = qNameRef.sourcePositions;
                    // index now depends on pattern type signature
                    int index = lastIndex;
                    if (this.pattern.qualification != null) {
                        index = lastIndex - this.pattern.segmentsSize;
                    }
                    if (index < 0)
                        index = 0;
                    int start = (int) ((positions[index]) >>> 32);
                    int end = (int) positions[lastIndex];
                    this.match.setOffset(start);
                    this.match.setLength(end - start + 1);

                    //  Look if there's a need to special report for parameterized type
                    matchReportReference(qNameRef, lastIndex, refBinding, locator);
                }
                return;
            }
            lastIndex--;
            refBinding = refBinding.enclosingType();
        }
    }
    locator.reportAccurateTypeReference(this.match, qNameRef, this.pattern.simpleName);
}

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

License:Open Source License

protected void reportDeclaration(ASTNode reference, IJavaElement element, MatchLocator locator,
        SimpleSet knownTypes) throws CoreException {
    int maxType = -1;
    TypeBinding typeBinding = null;/*w ww  .j a v a2 s  .  c o m*/
    if (reference instanceof TypeReference) {
        typeBinding = ((TypeReference) reference).resolvedType;
        maxType = Integer.MAX_VALUE;
    } else if (reference instanceof QualifiedNameReference) {
        QualifiedNameReference qNameRef = (QualifiedNameReference) reference;
        Binding binding = qNameRef.binding;
        maxType = qNameRef.tokens.length - 1;
        switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
        case Binding.FIELD: // reading a field
            typeBinding = qNameRef.actualReceiverType;
            maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
            break;
        case Binding.TYPE: //=============only type ==============
            if (binding instanceof TypeBinding)
                typeBinding = (TypeBinding) binding;
            break;
        case Binding.VARIABLE: //============unbound cases===========
        case Binding.TYPE | Binding.VARIABLE:
            if (binding instanceof ProblemFieldBinding) {
                typeBinding = qNameRef.actualReceiverType;
                maxType -= qNameRef.otherBindings == null ? 1 : qNameRef.otherBindings.length + 1;
            } else if (binding instanceof ProblemBinding) {
                ProblemBinding pbBinding = (ProblemBinding) binding;
                typeBinding = pbBinding.searchType; // second chance with recorded type so far
                char[] partialQualifiedName = pbBinding.name;
                maxType = CharOperation.occurencesOf('.', partialQualifiedName) - 1; // index of last bound token is one before the pb token
                if (typeBinding == null || maxType < 0)
                    return;
            }
            break;
        }
    } else if (reference instanceof SingleNameReference) {
        typeBinding = (TypeBinding) ((SingleNameReference) reference).binding;
        maxType = 1;
    }

    if (typeBinding instanceof ArrayBinding)
        typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
    if (typeBinding == null || typeBinding instanceof BaseTypeBinding)
        return;
    if (typeBinding instanceof ProblemReferenceBinding) {
        TypeBinding original = typeBinding.closestMatch();
        if (original == null)
            return; // original may not be set (bug 71279)
        typeBinding = original;
    }
    typeBinding = typeBinding.erasure();
    reportDeclaration((ReferenceBinding) typeBinding, maxType, locator, knownTypes);
}

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

License:Open Source License

protected int resolveLevel(NameReference nameRef) {
    Binding binding = nameRef.binding;

    if (nameRef instanceof SingleNameReference) {
        if (binding instanceof ProblemReferenceBinding)
            binding = ((ProblemReferenceBinding) binding).closestMatch();
        if (binding instanceof ReferenceBinding)
            return resolveLevelForType((ReferenceBinding) binding);
        return binding == null || binding instanceof ProblemBinding ? INACCURATE_MATCH : IMPOSSIBLE_MATCH;
    }//w  w  w.j a va  2 s  .c  o  m

    TypeBinding typeBinding = null;
    QualifiedNameReference qNameRef = (QualifiedNameReference) nameRef;
    switch (qNameRef.bits & ASTNode.RestrictiveFlagMASK) {
    case Binding.FIELD: // reading a field
        if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 2 : qNameRef.otherBindings.length + 2))
            return IMPOSSIBLE_MATCH; // must be at least A.x
        typeBinding = nameRef.actualReceiverType;
        break;
    case Binding.LOCAL: // reading a local variable
        return IMPOSSIBLE_MATCH; // no type match in it
    case Binding.TYPE: //=============only type ==============
        if (binding instanceof TypeBinding)
            typeBinding = (TypeBinding) binding;
        break;
    /*
     * Handling of unbound qualified name references. The match may reside in the resolved fragment,
     * which is recorded inside the problem binding, along with the portion of the name until it became a problem.
     */
    case Binding.VARIABLE: //============unbound cases===========
    case Binding.TYPE | Binding.VARIABLE:
        if (binding instanceof ProblemReferenceBinding) {
            typeBinding = (TypeBinding) binding;
        } else if (binding instanceof ProblemFieldBinding) {
            if (qNameRef.tokens.length < (qNameRef.otherBindings == null ? 2
                    : qNameRef.otherBindings.length + 2))
                return IMPOSSIBLE_MATCH; // must be at least A.x
            typeBinding = nameRef.actualReceiverType;
        } else if (binding instanceof ProblemBinding) {
            ProblemBinding pbBinding = (ProblemBinding) binding;
            if (CharOperation.occurencesOf('.', pbBinding.name) <= 0) // index of last bound token is one before the pb token
                return INACCURATE_MATCH;
            typeBinding = pbBinding.searchType;
        }
        break;
    }
    return resolveLevel(typeBinding);
}

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

License:Open Source License

/**
 * In eclipse 3.7+, the CastExpression constructor was changed from a really weird version to
 * a less weird one. Unfortunately that means we need to use reflection as we want to be compatible
 * with eclipse versions before 3.7 and 3.7+.
 * //from w  w w.ja va 2s .  co m
 * @param ref The {@code foo} in {@code (String)foo}.
 * @param castTo The {@code String} in {@code (String)foo}.
 */
public static CastExpression makeCastExpression(Expression ref, TypeReference castTo, ASTNode source) {
    CastExpression result;
    try {
        if (castExpressionConstructorIsTypeRefBased) {
            result = castExpressionConstructor.newInstance(ref, castTo);
        } else {
            Expression castToConverted = castTo;

            if (castTo.getClass() == SingleTypeReference.class && !isPrimitive(castTo)) {
                SingleTypeReference str = (SingleTypeReference) castTo;
                //Why a SingleNameReference instead of a SingleTypeReference you ask? I don't know. It seems dumb. Ask the ecj guys.
                castToConverted = new SingleNameReference(str.token, 0);
                castToConverted.bits = (castToConverted.bits & ~Binding.VARIABLE) | Binding.TYPE;
                castToConverted.sourceStart = str.sourceStart;
                castToConverted.sourceEnd = str.sourceEnd;
                setGeneratedBy(castToConverted, source);
            } else if (castTo.getClass() == QualifiedTypeReference.class) {
                QualifiedTypeReference qtr = (QualifiedTypeReference) castTo;
                //Same here, but for the more complex types, they stay types.
                castToConverted = new QualifiedNameReference(qtr.tokens, copy(qtr.sourcePositions),
                        qtr.sourceStart, qtr.sourceEnd);
                castToConverted.bits = (castToConverted.bits & ~Binding.VARIABLE) | Binding.TYPE;
                setGeneratedBy(castToConverted, source);
            }

            result = castExpressionConstructor.newInstance(ref, castToConverted);
        }
    } catch (InvocationTargetException e) {
        throw Lombok.sneakyThrow(e.getCause());
    } catch (IllegalAccessException e) {
        throw Lombok.sneakyThrow(e);
    } catch (InstantiationException e) {
        throw Lombok.sneakyThrow(e);
    }

    result.sourceStart = source.sourceStart;
    result.sourceEnd = source.sourceEnd;
    result.statementEnd = source.sourceEnd;

    setGeneratedBy(result, source);
    return result;
}

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

License:Open Source License

boolean areTypesEqual(TypeBinding one, TypeBinding two) {
    if (one == two)
        return true;
    // https://bugs.eclipse.org/bugs/show_bug.cgi?id=329584
    switch (one.kind()) {
    case Binding.TYPE:
        switch (two.kind()) {
        case Binding.PARAMETERIZED_TYPE:
        case Binding.RAW_TYPE:
            if (one == two.erasure())
                return true;
        }/*  ww  w  .  ja v a 2s  .  c  om*/
        break;
    case Binding.RAW_TYPE:
    case Binding.PARAMETERIZED_TYPE:
        switch (two.kind()) {
        case Binding.TYPE:
            if (one.erasure() == two)
                return true;
        }
    }

    // need to consider X<?> and X<? extends Object> as the same 'type'
    if (one.isParameterizedType() && two.isParameterizedType())
        return one.isEquivalentTo(two) && two.isEquivalentTo(one);

    // Can skip this since we resolved each method before comparing it, see computeSubstituteMethod()
    //   if (one instanceof UnresolvedReferenceBinding)
    //      return ((UnresolvedReferenceBinding) one).resolvedType == two;
    //   if (two instanceof UnresolvedReferenceBinding)
    //      return ((UnresolvedReferenceBinding) two).resolvedType == one;
    return false; // all other type bindings are identical
}

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

License:Open Source License

/**
 * Answer true if the receiver type can be assigned to the argument type (right)
 *//*from w w  w  . jav  a  2s  .  c o  m*/
private boolean isCompatibleWith0(TypeBinding otherType) {
    if (otherType == this)
        return true;
    if (otherType.id == TypeIds.T_JavaLangObject)
        return true;
    // equivalence may allow compatibility with array type through wildcard
    // bound
    if (isEquivalentTo(otherType))
        return true;
    switch (otherType.kind()) {
    case Binding.WILDCARD_TYPE:
    case Binding.INTERSECTION_TYPE:
        return false; // should have passed equivalence check above if
                      // wildcard
    case Binding.TYPE_PARAMETER:
        // check compatibility with capture of ? super X
        if (otherType.isCapture()) {
            CaptureBinding otherCapture = (CaptureBinding) otherType;
            TypeBinding otherLowerBound;
            if ((otherLowerBound = otherCapture.lowerBound) != null) {
                if (otherLowerBound.isArrayType())
                    return false;
                return isCompatibleWith(otherLowerBound);
            }
        }
        //$FALL-THROUGH$
    case Binding.GENERIC_TYPE:
    case Binding.TYPE:
    case Binding.PARAMETERIZED_TYPE:
    case Binding.RAW_TYPE:
        switch (kind()) {
        case Binding.GENERIC_TYPE:
        case Binding.PARAMETERIZED_TYPE:
        case Binding.RAW_TYPE:
            if (erasure() == otherType.erasure())
                return false; // should have passed equivalence check
                              // above if same erasure
        }
        ReferenceBinding otherReferenceType = (ReferenceBinding) otherType;
        if (otherReferenceType.isInterface()) // could be annotation type
            return implementsInterface(otherReferenceType, true);
        if (isInterface()) // Explicit conversion from an interface
                           // to a class is not allowed
            return false;
        return otherReferenceType.isSuperclassOf(this);
    default:
        return false;
    }
}

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   ww w .  ja v a 2s  .c  o m
 * 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

public Binding getBinding(char[] name, int mask, InvocationSite invocationSite, boolean needResolve) {
    CompilationUnitScope unitScope = compilationUnitScope();
    LookupEnvironment env = unitScope.environment;
    try {//from www  .  j  a  v a 2s .  c o m
        env.missingClassFileLocation = invocationSite;
        Binding binding = null;
        FieldBinding problemField = null;
        if ((mask & Binding.VARIABLE) != 0) {
            boolean insideStaticContext = false;
            boolean insideConstructorCall = false;
            boolean insideTypeAnnotation = false;

            FieldBinding foundField = null;
            // can be a problem field which is answered if a valid field is not found
            ProblemFieldBinding foundInsideProblem = null;
            // inside Constructor call or inside static context
            Scope scope = this;
            int depth = 0;
            int foundDepth = 0;
            ReferenceBinding foundActualReceiverType = null;
            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;

                    //$FALL-THROUGH$ could duplicate the code below to save a cast - questionable optimization
                case BLOCK_SCOPE:
                    LocalVariableBinding variableBinding = scope.findVariable(name);
                    // looks in this scope only
                    if (variableBinding != null) {
                        if (foundField != null && foundField.isValidBinding())
                            return new ProblemFieldBinding(foundField, // closest match
                                    foundField.declaringClass, name,
                                    ProblemReasons.InheritedNameHidesEnclosingName);
                        if (depth > 0)
                            invocationSite.setDepth(depth);
                        return variableBinding;
                    }
                    break;
                case CLASS_SCOPE:
                    ClassScope classScope = (ClassScope) scope;
                    ReferenceBinding receiverType = classScope.enclosingReceiverType();
                    if (!insideTypeAnnotation) {
                        FieldBinding fieldBinding = classScope.findField(receiverType, name, invocationSite,
                                needResolve);
                        // Use next line instead if willing to enable protected access accross inner types
                        // FieldBinding fieldBinding = findField(enclosingType, name, invocationSite);

                        if (fieldBinding != null) { // skip it if we did not find anything
                            if (fieldBinding.problemId() == ProblemReasons.Ambiguous) {
                                if (foundField == null || foundField.problemId() == ProblemReasons.NotVisible)
                                    // supercedes any potential InheritedNameHidesEnclosingName problem
                                    return fieldBinding;
                                // make the user qualify the field, likely wants the first inherited field (javac generates an ambiguous error instead)
                                return new ProblemFieldBinding(foundField, // closest match
                                        foundField.declaringClass, name,
                                        ProblemReasons.InheritedNameHidesEnclosingName);
                            }

                            ProblemFieldBinding insideProblem = null;
                            if (fieldBinding.isValidBinding()) {
                                if (!fieldBinding.isStatic()) {
                                    if (insideConstructorCall) {
                                        insideProblem = new ProblemFieldBinding(fieldBinding, // closest match
                                                fieldBinding.declaringClass, name,
                                                ProblemReasons.NonStaticReferenceInConstructorInvocation);
                                    } else if (insideStaticContext) {
                                        insideProblem = new ProblemFieldBinding(fieldBinding, // closest match
                                                fieldBinding.declaringClass, name,
                                                ProblemReasons.NonStaticReferenceInStaticContext);
                                    }
                                }
                                if (receiverType == fieldBinding.declaringClass
                                        || compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) {
                                    // found a valid field in the 'immediate' scope (i.e. not inherited)
                                    // OR in 1.4 mode (inherited shadows enclosing)
                                    if (foundField == null) {
                                        if (depth > 0) {
                                            invocationSite.setDepth(depth);
                                            invocationSite.setActualReceiverType(receiverType);
                                        }
                                        // return the fieldBinding if it is not declared in a superclass of the scope's binding (that is, inherited)
                                        return insideProblem == null ? fieldBinding : insideProblem;
                                    }
                                    if (foundField.isValidBinding())
                                        // if a valid field was found, complain when another is found in an 'immediate' enclosing type (that is, not inherited)
                                        // but only if "valid field" was inherited in the first place.
                                        if (foundField.declaringClass != fieldBinding.declaringClass
                                                && foundField.declaringClass != foundActualReceiverType) // https://bugs.eclipse.org/bugs/show_bug.cgi?id=316956
                                            // i.e. have we found the same field - do not trust field identity yet
                                            return new ProblemFieldBinding(foundField, // closest match
                                                    foundField.declaringClass, name,
                                                    ProblemReasons.InheritedNameHidesEnclosingName);
                                }
                            }

                            if (foundField == null || (foundField.problemId() == ProblemReasons.NotVisible
                                    && fieldBinding.problemId() != ProblemReasons.NotVisible)) {
                                // only remember the fieldBinding if its the first one found or the previous one was not visible & fieldBinding is...
                                foundDepth = depth;
                                foundActualReceiverType = receiverType;
                                foundInsideProblem = insideProblem;
                                foundField = fieldBinding;
                            }
                        }
                    }
                    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 (foundInsideProblem != null)
                return foundInsideProblem;
            if (foundField != null) {
                if (foundField.isValidBinding()) {
                    if (foundDepth > 0) {
                        invocationSite.setDepth(foundDepth);
                        invocationSite.setActualReceiverType(foundActualReceiverType);
                    }
                    return foundField;
                }
                problemField = foundField;
                foundField = null;
            }

            if (compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5) {
                // at this point the scope is a compilation unit scope & need to check for imported static fields
                unitScope.faultInImports(); // ensure static imports are resolved
                ImportBinding[] imports = unitScope.imports;
                if (imports != null) {
                    // check single static imports
                    for (int i = 0, length = imports.length; i < length; i++) {
                        ImportBinding importBinding = imports[i];
                        if (importBinding.isStatic() && !importBinding.onDemand) {
                            if (CharOperation.equals(
                                    importBinding.compoundName[importBinding.compoundName.length - 1], name)) {
                                if (unitScope.resolveSingleImport(importBinding,
                                        Binding.TYPE | Binding.FIELD | Binding.METHOD) != null
                                        && importBinding.resolvedImport instanceof FieldBinding) {
                                    foundField = (FieldBinding) importBinding.resolvedImport;
                                    ImportReference importReference = importBinding.reference;
                                    if (importReference != null && needResolve) {
                                        importReference.bits |= ASTNode.Used;
                                    }
                                    invocationSite.setActualReceiverType(foundField.declaringClass);
                                    if (foundField.isValidBinding()) {
                                        return foundField;
                                    }
                                    if (problemField == null)
                                        problemField = foundField;
                                }
                            }
                        }
                    }
                    // check on demand imports
                    boolean foundInImport = false;
                    for (int i = 0, length = imports.length; i < length; i++) {
                        ImportBinding importBinding = imports[i];
                        if (importBinding.isStatic() && importBinding.onDemand) {
                            Binding resolvedImport = importBinding.resolvedImport;
                            if (resolvedImport instanceof ReferenceBinding) {
                                FieldBinding temp = findField((ReferenceBinding) resolvedImport, name,
                                        invocationSite, needResolve);
                                if (temp != null) {
                                    if (!temp.isValidBinding()) {
                                        if (problemField == null)
                                            problemField = temp;
                                    } else if (temp.isStatic()) {
                                        if (foundField == temp)
                                            continue;
                                        ImportReference importReference = importBinding.reference;
                                        if (importReference != null && needResolve) {
                                            importReference.bits |= ASTNode.Used;
                                        }
                                        if (foundInImport)
                                            // Answer error binding -- import on demand conflict; name found in two import on demand packages.
                                            return new ProblemFieldBinding(foundField, // closest match
                                                    foundField.declaringClass, name, ProblemReasons.Ambiguous);
                                        foundField = temp;
                                        foundInImport = true;
                                    }
                                }
                            }
                        }
                    }
                    if (foundField != null) {
                        invocationSite.setActualReceiverType(foundField.declaringClass);
                        return foundField;
                    }
                }
            }
        }

        // We did not find a local or instance variable.
        if ((mask & Binding.TYPE) != 0) {
            if ((binding = getBaseType(name)) != null)
                return binding;
            binding = getTypeOrPackage(name,
                    (mask & Binding.PACKAGE) == 0 ? Binding.TYPE : Binding.TYPE | Binding.PACKAGE, needResolve);
            if (binding.isValidBinding() || mask == Binding.TYPE)
                return binding;
            // answer the problem type binding if we are only looking for a type
        } else if ((mask & Binding.PACKAGE) != 0) {
            unitScope.recordSimpleReference(name);
            if ((binding = env.getTopLevelPackage(name)) != null)
                return binding;
        }
        if (problemField != null)
            return problemField;
        if (binding != null && binding.problemId() != ProblemReasons.NotFound)
            return binding; // answer the better problem binding
        return new ProblemBinding(name, enclosingSourceType(), ProblemReasons.NotFound);
    } catch (AbortCompilation e) {
        e.updateContext(invocationSite, referenceCompilationUnit().compilationResult);
        throw e;
    } finally {
        env.missingClassFileLocation = null;
    }
}