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

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

Introduction

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

Prototype

public FieldBinding getField(char[] fieldName, boolean needResolve) 

Source Link

Usage

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 a  va 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.objectteams.otdt.internal.codeassist.SelectionOnFieldAccessSpec.java

License:Open Source License

@Override
public void resolveFinished() {
    // cf. SelectionOnMethodSpec:
    FieldBinding binding = this.resolvedField;
    // tolerate some error cases
    if (binding == null || !(binding.isValidBinding() || binding.problemId() == ProblemReasons.NotVisible
            || binding.problemId() == ProblemReasons.InheritedNameHidesEnclosingName
            || binding.problemId() == ProblemReasons.NonStaticReferenceInConstructorInvocation
            || binding.problemId() == ProblemReasons.NonStaticReferenceInStaticContext)) {
        throw new SelectionNodeFound();
    } else {/*from w  w  w.ja va 2s  .c o m*/
        //field is part of a role
        if (binding.declaringClass.isRole()) {
            // field is copy inherited: use the original binding:
            if (binding.copyInheritanceSrc != null)
                throw new SelectionNodeFound(binding.copyInheritanceSrc);

            //have to generate a new binding here!
            ReferenceBinding roleClass = binding.declaringClass.roleModel.getClassPartBinding();
            FieldBinding newBinding = roleClass.getField(binding.name, true);
            throw new SelectionNodeFound(newBinding);
        }
    }
    throw new SelectionNodeFound(this.resolvedField);
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.ast.CallinMappingDeclaration.java

License:Open Source License

/** Check whether the baseSpec has a result compatible via replace. */
public void checkResultForReplace(MethodSpec baseSpec) {
    boolean typeIdentityRequired = true; // default unless return is type variable
    // covariant return requires a fresh type parameter for the role's return type:
    if (baseSpec.covariantReturn && this.roleMethodSpec.returnType != null) {
        TypeBinding resolvedRoleReturn = this.roleMethodSpec.returnType.resolvedType;
        if (resolvedRoleReturn != null) {
            if (!resolvedRoleReturn.isTypeVariable()) {
                this.scope.problemReporter()
                        .covariantReturnRequiresTypeParameter(this.roleMethodSpec.returnType);
                this.binding.tagBits |= TagBits.HasMappingIncompatibility;
            } else {
                // is the type parameter "fresh"?
                for (Argument arg : this.roleMethodSpec.arguments) {
                    if (typeUsesTypeVariable(arg.type.resolvedType.leafComponentType(), resolvedRoleReturn)) {
                        this.scope.problemReporter().duplicateUseOfTypeVariableInCallin(
                                this.roleMethodSpec.returnType, resolvedRoleReturn);
                        this.binding.tagBits |= TagBits.HasMappingIncompatibility;
                        break;
                    }// ww  w . j  av a 2  s  .c  om
                }
            }
        }
    }
    TypeVariableBinding returnVariable = MethodModel
            .checkedGetReturnTypeVariable(this.roleMethodSpec.resolvedMethod);
    if (returnVariable != null) {
        // unbounded type variable always matches:
        if (returnVariable.firstBound == null)
            return;
        // in case of type variable only one-way compatibility is needed even for replace:
        typeIdentityRequired = false;
    }

    // now go for the actual type checking:
    TypeBinding baseReturn = baseSpec.resolvedMethod.returnType;
    TypeBinding roleReturn = MethodModel.getReturnType(this.roleMethodSpec.resolvedMethod);
    TypeBinding roleReturnLeaf = roleReturn != null ? roleReturn.leafComponentType() : null;
    if (roleReturnLeaf instanceof ReferenceBinding && ((ReferenceBinding) roleReturnLeaf).isRole()) {
        // strengthen:
        roleReturnLeaf = TeamModel.strengthenRoleType(this.scope.enclosingSourceType(), roleReturnLeaf);
        if (roleReturnLeaf == null) { // FIXME(SH): testcase and better handling
            String roleReturnName = roleReturn != null ? new String(roleReturn.readableName())
                    : "null return type"; //$NON-NLS-1$
            throw new InternalCompilerError("role strengthening for " + roleReturnName + " -> null"); //$NON-NLS-1$ //$NON-NLS-2$
        }

        // bound roles use their topmost bound super:
        if (((ReferenceBinding) roleReturnLeaf).baseclass() != null)
            roleReturnLeaf = RoleModel.getTopmostBoundRole(this.scope, (ReferenceBinding) roleReturnLeaf);

        // need the RTB:
        if (!(roleReturnLeaf instanceof DependentTypeBinding))
            roleReturnLeaf = RoleTypeCreator.maybeWrapUnqualifiedRoleType(roleReturnLeaf,
                    this.scope.enclosingSourceType());

        // array?
        int dims = roleReturn != null ? roleReturn.dimensions() : 0;
        if (dims == 0) {
            roleReturn = roleReturnLeaf;
            this.realRoleReturn = roleReturnLeaf;
        } else {
            roleReturn = ((DependentTypeBinding) roleReturnLeaf).getArrayType(dims);
            this.realRoleReturn = ((DependentTypeBinding) roleReturnLeaf).getArrayType(dims);
        }
    }
    if (baseReturn == null || baseReturn == TypeBinding.VOID) {
        // OTJLD 4.4(b): "A callin method bound with replace
        //                to a base method returning void
        //                must not declare a non-void result."
        if (!(roleReturn == null || roleReturn == TypeBinding.VOID)) {
            this.scope.problemReporter().callinIllegalRoleReturnReturn(baseSpec, this.roleMethodSpec);
            this.binding.tagBits |= TagBits.HasMappingIncompatibility;
        }
    } else {
        if (roleReturn == null || roleReturn == TypeBinding.VOID) {
            this.baseMethodNeedingResultFromBasecall = baseSpec;
            // will be reported in checkBaseResult().
            return;
        }

        TypeBinding baseLeaf = baseReturn.leafComponentType();
        if (baseLeaf instanceof DependentTypeBinding) {
            // instantiate relative to Role._OT$base:
            ReferenceBinding enclosingRole = this.scope.enclosingSourceType();
            FieldBinding baseField = enclosingRole.getField(IOTConstants._OT_BASE, true);
            if (baseField != null && baseField.isValidBinding())
                baseReturn = baseField.getRoleTypeBinding((ReferenceBinding) baseLeaf, baseReturn.dimensions());
        }

        // check auto(un)boxing:
        if (this.scope.isBoxingCompatibleWith(roleReturn, baseReturn))
            return;

        Config oldConfig = Config.createOrResetConfig(this);
        try {
            if (!roleReturn.isCompatibleWith(baseReturn)) {
                if (typeIdentityRequired) {
                    this.scope.problemReporter().callinIncompatibleReturnType(baseSpec, this.roleMethodSpec);
                    this.binding.tagBits |= TagBits.HasMappingIncompatibility;
                    return;
                }
                // else we still needed the lowering test
            }
            // callin replace requires two way compatibility:
            baseSpec.returnNeedsTranslation = Config.getLoweringRequired();

        } finally {
            Config.removeOrRestore(oldConfig, this);
        }
        // from now on don't bother with arrays any more (dimensions have been checked):
        roleReturn = roleReturn.leafComponentType();
        baseReturn = baseReturn.leafComponentType();
        TypeBinding translatedReturn = baseSpec.returnNeedsTranslation
                ? ((ReferenceBinding) roleReturn).baseclass()
                : roleReturn;
        if (translatedReturn.isTypeVariable()) {
            TypeBinding firstBound = ((TypeVariableBinding) translatedReturn).firstBound;
            if (firstBound != null)
                translatedReturn = firstBound;
        }
        if (!baseReturn.isCompatibleWith(translatedReturn)) {
            this.scope.problemReporter().callinIncompatibleReturnTypeBaseCall(baseSpec, this.roleMethodSpec);
            this.binding.tagBits |= TagBits.HasMappingIncompatibility;
        }
    }
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.ast.QualifiedBaseReference.java

License:Open Source License

@Override
public TypeBinding resolveType(BlockScope scope) {
    TypeBinding superResult = super.resolveType(scope);
    if (superResult == null || !superResult.isValidBinding())
        return null;
    ReferenceBinding currentType = this.currentCompatibleType;
    while (currentType != null && currentType.isValidBinding() && currentType.isRole()) {
        this.baseField = currentType.getField(IOTConstants._OT_BASE, true);
        if (this.baseField != null) {
            if (this.baseField.isValidBinding())
                return this.resolvedType = this.baseField.type;
        }/*from ww w. ja v a  2  s  .  c o m*/
        currentType = currentType.superclass(); // base field may be inherited
    }
    if (this.baseField == null)
        this.baseField = new ProblemFieldBinding((ReferenceBinding) this.resolvedType, IOTConstants.BASE,
                ProblemReasons.NotFound);
    scope.problemReporter().unboundQualifiedBase((ReferenceBinding) this.qualification.resolvedType, this);
    return null;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.bytecode.ConstantPoolObjectReader.java

License:Open Source License

public FieldBinding findFieldByName(ReferenceBinding clazz, char[] name) {
    char[] prefix = TypeConstants.SYNTHETIC_ENCLOSING_INSTANCE_PREFIX;
    if (CharOperation.prefixEquals(prefix, name)) {
        TypeBinding original = clazz.original();
        if (original instanceof NestedTypeBinding) {
            if (original.isMemberType() || original.isLocalType()) {
                NestedTypeBinding ntb = (NestedTypeBinding) original;
                SyntheticArgumentBinding[] sab = ntb.syntheticEnclosingInstances();
                for (int i = 0; i < sab.length; i++) {
                    if (CharOperation.equals(name, sab[i].name))
                        return sab[i].matchingField;
                }//from   ww  w. j  a v  a 2 s .c o m
            }
        }
        // no name adjustment or synthetics needed at the reading (source) side.
    }
    // either regular field or synthetic in a BinaryTypeBinding:
    return clazz.getField(name, true);
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.bytecode.ConstantPoolObjectReader.java

License:Open Source License

public static FieldBinding findFieldByBinding(ReferenceBinding clazz, FieldBinding refField) {
    char[] thisPrefix = TypeConstants.SYNTHETIC_ENCLOSING_INSTANCE_PREFIX;
    char[] classPrefix = TypeConstants.SYNTHETIC_CLASS;
    char[] name = refField.name;
    if (CharOperation.prefixEquals(thisPrefix, name)) {
        int distance = refField.declaringClass.depth() - ((ReferenceBinding) refField.type).depth();
        if (clazz instanceof NestedTypeBinding) {
            {/*from w  ww .  jav  a2s  .  co  m*/
                NestedTypeBinding mtb = (NestedTypeBinding) clazz;
                ReferenceBinding dstFieldType = clazz;
                while (distance-- > 0) {
                    dstFieldType = dstFieldType.enclosingType();
                }
                return mtb.addSyntheticFieldForInnerclass(dstFieldType);
            }
        } else { // BinaryTypeBinding
            int depth = clazz.depth() - distance;
            name = CharOperation.concat(thisPrefix, String.valueOf(depth).toCharArray());
        }
    } else if (CharOperation.prefixEquals(classPrefix, name)) {
        // assume the synthetic field is present, just create a new binding.
        return new FieldBinding(refField.name, refField.type, 0, clazz, null);
    }
    // directly find field in clazz or superclass(es)
    ReferenceBinding current = clazz;
    while (current != null) {
        FieldBinding f = current.getField(name, true);
        if (f != null)
            return f;
        current = current.superclass();
    }
    return null;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.bytecode.SingleValueAttribute.java

License:Open Source License

/**
 * Evaluate class level attribute(s).//  w  w w .j a  v  a 2  s . co m
 */
public void evaluate(Binding binding, LookupEnvironment environment, char[][][] missingTypeNames) {
    if (CharOperation.equals(this._name, PLAYEDBY_NAME)) {
        checkBindingMismatch(binding, ExtraCompilerModifiers.AccRole);
        ReferenceBinding roleType = (ReferenceBinding) binding;
        if (CharOperation.indexOf(ANCHOR_DELIM, this._value, true) > -1) {
            // decode anchored type:
            char[] typeName = singleRoleName(this._value);
            char[][] anchorPath = anchorPath(this._value);
            ReferenceBinding staticPart = null;
            int i;
            for (i = 0; i < anchorPath.length - 1; i++) {
                ReferenceBinding envType = environment.askForType(CharOperation.subarray(anchorPath, 0, i + 1));
                if (envType != null)
                    staticPart = envType;
                else if (staticPart != null)
                    break; // seen enough
            }
            if (staticPart == null)
                return; // no success!
            ReferenceBinding currentType = staticPart;
            ITeamAnchor anchor = null; // accumulate anchor path here
            while (i < anchorPath.length) {
                if (currentType instanceof BinaryTypeBinding
                        && ((BinaryTypeBinding) currentType).version == 0) {
                    // necessary type on the path is not fully initialized (version is about the last field to be assigned in cachePartsFrom()).
                    roleType.roleModel.addAttribute(this);
                    return; // defer evaluation
                }
                FieldBinding f = currentType.getField(anchorPath[i], true);
                if (f == null || !(f.type instanceof ReferenceBinding))
                    return; // not a valid anchor path.
                currentType = (ReferenceBinding) f.type;
                if (anchor == null)
                    anchor = f;
                else
                    anchor = f.setPathPrefix(anchor);
                i++;
            }
            if (anchor == null)
                return; // no success!
            ReferenceBinding baseType = anchor.getMemberTypeOfType(typeName);
            if (baseType == null)
                return; // no success!
            roleType.baseclass = (ReferenceBinding) anchor.getRoleTypeBinding(baseType, null/*typeArguments*/,
                    0); // FIXME(SH) retrieve type arguments from attribute (need to store first ;-)
        } else {
            roleType.baseclass = getResolvedType(environment, toConstantPoolName(this._value),
                    missingTypeNames);
        }
        roleType.baseclass.setIsBoundBase(roleType);
    }
}

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

License:Open Source License

/** Given that this is the model of a fake strong base field, return the original field from the super role. */
public FieldBinding getOriginalFromFake() {
    ReferenceBinding superRole = this.actualDeclaringClass;
    FieldBinding fieldBinding = superRole.getField(this._binding.name, true);
    if (fieldBinding == null)
        throw new InternalCompilerError(
                "Expected base field not found in super Role " + new String(superRole.readableName())); //$NON-NLS-1$
    return fieldBinding;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.statemachine.copyinheritance.TypeLevel.java

License:Open Source License

/**
 * Starting from the tsuper role's base class check whether implicit playedBy refinement
 * is involved. If so, create a weakened type to reflect the dual type of the base field.
 *//*  w  ww .  jav  a  2s.c o m*/
private static ReferenceBinding checkAdjustImplicitlyRefinedBase(ReferenceBinding baseclass,
        TypeDeclaration destRoleDecl, SourceTypeBinding destRole) {
    // only if base class is a base-anchored role:
    if (RoleTypeBinding.isRoleWithExplicitAnchor(baseclass)
            && ((RoleTypeBinding) baseclass)._teamAnchor.isBaseAnchor()) {
        // only if the current enclosing has an explicit playedBy (TODO(SH): multi-level!)
        if (destRoleDecl.enclosingType != null && destRoleDecl.enclosingType.baseclass != null) {
            // navigate manually to the strong base type:
            ReferenceBinding destEnclosing = destRole.enclosingType();
            ReferenceBinding outerBase = destEnclosing.baseclass();
            if (!outerBase.isCompatibleWith(baseclass.enclosingType()))
                return baseclass;
            ReferenceBinding innerBase = outerBase.getMemberType(baseclass.sourceName());
            ITeamAnchor outerBaseField = destEnclosing.getField(IOTConstants._OT_BASE, true);
            assert outerBaseField != null;
            // combine both types:
            TypeBinding[] typeArguments = baseclass.isParameterizedType()
                    ? ((ParameterizedTypeBinding) baseclass).arguments
                    : null;
            TypeBinding innerBaseRoleType = outerBaseField.getDependentTypeBinding(innerBase, -1, typeArguments,
                    0);
            return ((RoleTypeBinding) innerBaseRoleType).weakenFrom(baseclass);
        }
    }
    return baseclass;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.statemachine.transformer.StandardElementGenerator.java

License:Open Source License

private static void checkCreateFakedStrongBaseField(ReferenceBinding superRole, ReferenceBinding roleClass,
        ReferenceBinding baseTypeBinding) {
    if (TypeBinding.equalsEquals(superRole.baseclass, baseTypeBinding))
        return; // not strengthening
    ReferenceBinding nextSuper = superRole.superclass();
    while (nextSuper.isRole() && nextSuper.roleModel.isBound()) {
        superRole = nextSuper;/*  w w  w .j  ava2 s .  co m*/
        nextSuper = nextSuper.superclass();
    }
    // create faked base field with exact type information:
    FieldBinding fakeStrongBaseField = new FieldBinding(_OT_BASE, baseTypeBinding,
            AccPublic | AccFinal | AccSynthetic, roleClass, Constant.NotAConstant);
    fakeStrongBaseField.tagBits |= TagBits.IsFakedField;
    SourceTypeBinding roleSourceClass = (SourceTypeBinding) roleClass;
    FieldModel model = FieldModel.getModel(fakeStrongBaseField);
    model.actualDeclaringClass = superRole;
    FieldBinding superBaseField = superRole.getField(IOTConstants._OT_BASE, false);
    if (superBaseField != null)
        fakeStrongBaseField.shareBestName(superBaseField);
    roleSourceClass.addField(fakeStrongBaseField);
}