Example usage for org.eclipse.jdt.internal.compiler.lookup Scope enclosingSourceType

List of usage examples for org.eclipse.jdt.internal.compiler.lookup Scope enclosingSourceType

Introduction

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

Prototype

public final SourceTypeBinding enclosingSourceType() 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.util.HandleFactory.java

License:Open Source License

/**
 * Create handle by adding child to parent obtained by recursing into parent scopes.
 *///w ww.  ja v  a2s .  c  om
private IJavaElement createElement(Scope scope, int elementPosition, ICompilationUnit unit,
        HashSet existingElements, HashMap knownScopes) {
    IJavaElement newElement = (IJavaElement) knownScopes.get(scope);
    if (newElement != null)
        return newElement;

    switch (scope.kind) {
    case Scope.COMPILATION_UNIT_SCOPE:
        newElement = unit;
        break;
    case Scope.CLASS_SCOPE:
        IJavaElement parentElement = createElement(scope.parent, elementPosition, unit, existingElements,
                knownScopes);
        switch (parentElement.getElementType()) {
        case IJavaElement.COMPILATION_UNIT:
            newElement = ((ICompilationUnit) parentElement)
                    .getType(new String(scope.enclosingSourceType().sourceName));
            break;
        case IJavaElement.TYPE:
            newElement = ((IType) parentElement).getType(new String(scope.enclosingSourceType().sourceName));
            break;
        case IJavaElement.FIELD:
        case IJavaElement.INITIALIZER:
        case IJavaElement.METHOD:
            IMember member = (IMember) parentElement;
            if (member.isBinary()) {
                return null;
            } else {
                newElement = member.getType(new String(scope.enclosingSourceType().sourceName), 1);
                // increment occurrence count if collision is detected
                if (newElement != null) {
                    while (!existingElements.add(newElement))
                        ((SourceRefElement) newElement).occurrenceCount++;
                }
            }
            break;
        }
        if (newElement != null) {
            knownScopes.put(scope, newElement);
        }
        break;
    case Scope.METHOD_SCOPE:
        IType parentType = (IType) createElement(scope.parent, elementPosition, unit, existingElements,
                knownScopes);
        MethodScope methodScope = (MethodScope) scope;
        if (methodScope.isInsideInitializer()) {
            // inside field or initializer, must find proper one
            TypeDeclaration type = methodScope.referenceType();
            int occurenceCount = 1;
            int length = type.fields == null ? 0 : type.fields.length;
            for (int i = 0; i < length; i++) {
                FieldDeclaration field = type.fields[i];
                if (field.declarationSourceStart <= elementPosition
                        && elementPosition <= field.declarationSourceEnd) {
                    switch (field.getKind()) {
                    case AbstractVariableDeclaration.FIELD:
                    case AbstractVariableDeclaration.ENUM_CONSTANT:
                        newElement = parentType.getField(new String(field.name));
                        break;
                    case AbstractVariableDeclaration.INITIALIZER:
                        newElement = parentType.getInitializer(occurenceCount);
                        break;
                    }
                    break;
                } else if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
                    occurenceCount++;
                }
            }
        } else {
            // method element
            AbstractMethodDeclaration method = methodScope.referenceMethod();
            newElement = parentType.getMethod(new String(method.selector),
                    Util.typeParameterSignatures(method));
            if (newElement != null) {
                knownScopes.put(scope, newElement);
            }
        }
        break;
    case Scope.BLOCK_SCOPE:
        // standard block, no element per se
        newElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
        break;
    }
    return newElement;
}

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

License:Open Source License

/**
 * Create handle by adding child to parent obtained by recursing into parent scopes.
 *///ww w .  jav  a 2  s  .  co  m
public IJavaElement createElement(Scope scope, int elementPosition, ICompilationUnit unit,
        HashSet existingElements, HashMap knownScopes) {
    IJavaElement newElement = (IJavaElement) knownScopes.get(scope);
    if (newElement != null)
        return newElement;

    switch (scope.kind) {
    case Scope.COMPILATION_UNIT_SCOPE:
        newElement = unit;
        break;
    case Scope.CLASS_SCOPE:
        IJavaElement parentElement = createElement(scope.parent, elementPosition, unit, existingElements,
                knownScopes);
        switch (parentElement.getElementType()) {
        case IJavaElement.COMPILATION_UNIT:
            newElement = ((ICompilationUnit) parentElement)
                    .getType(new String(scope.enclosingSourceType().sourceName));
            break;
        case IJavaElement.TYPE:
            newElement = ((IType) parentElement).getType(new String(scope.enclosingSourceType().sourceName));
            break;
        case IJavaElement.FIELD:
        case IJavaElement.INITIALIZER:
        case IJavaElement.METHOD:
            IMember member = (IMember) parentElement;
            if (member.isBinary()) {
                return null;
            } else {
                newElement = member.getType(new String(scope.enclosingSourceType().sourceName), 1);
                // increment occurrence count if collision is detected
                if (newElement != null) {
                    while (!existingElements.add(newElement))
                        ((SourceRefElement) newElement).occurrenceCount++;
                }
            }
            break;
        }
        if (newElement != null) {
            knownScopes.put(scope, newElement);
        }
        break;
    case Scope.METHOD_SCOPE:
        if (scope.isLambdaScope()) {
            parentElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
            LambdaExpression expression = (LambdaExpression) scope.originalReferenceContext();
            if (expression.resolvedType != null && expression.resolvedType.isValidBinding()
                    && !(expression.descriptor instanceof ProblemMethodBinding)) { // chain in lambda element only if resolved properly.
                //newElement = new org.eclipse.jdt.internal.core.SourceLambdaExpression((JavaElement) parentElement, expression)
                // .getMethod();

                newElement = LambdaFactory.createLambdaExpression((JavaElement) parentElement, expression)
                        .getMethod();
                knownScopes.put(scope, newElement);
                return newElement;
            }
            return parentElement;
        }
        IType parentType = (IType) createElement(scope.parent, elementPosition, unit, existingElements,
                knownScopes);
        MethodScope methodScope = (MethodScope) scope;
        if (methodScope.isInsideInitializer()) {
            // inside field or initializer, must find proper one
            TypeDeclaration type = methodScope.referenceType();
            int occurenceCount = 1;
            int length = type.fields == null ? 0 : type.fields.length;
            for (int i = 0; i < length; i++) {
                FieldDeclaration field = type.fields[i];
                if (field.declarationSourceStart <= elementPosition
                        && elementPosition <= field.declarationSourceEnd) {
                    switch (field.getKind()) {
                    case AbstractVariableDeclaration.FIELD:
                    case AbstractVariableDeclaration.ENUM_CONSTANT:
                        newElement = parentType.getField(new String(field.name));
                        break;
                    case AbstractVariableDeclaration.INITIALIZER:
                        newElement = parentType.getInitializer(occurenceCount);
                        break;
                    }
                    break;
                } else if (field.getKind() == AbstractVariableDeclaration.INITIALIZER) {
                    occurenceCount++;
                }
            }
        } else {
            // method element
            AbstractMethodDeclaration method = methodScope.referenceMethod();
            newElement = parentType.getMethod(new String(method.selector),
                    Util.typeParameterSignatures(method));
            if (newElement != null) {
                knownScopes.put(scope, newElement);
            }
        }
        break;
    case Scope.BLOCK_SCOPE:
        // standard block, no element per se
        newElement = createElement(scope.parent, elementPosition, unit, existingElements, knownScopes);
        break;
    }
    return newElement;
}

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

License:Open Source License

/**
 * Answer true if the receiver is visible to the type provided by the scope.
 *//*from   www  .  j av  a 2 s .  c  o m*/
public final boolean canBeSeenBy(Scope scope) {
    // GROOVY start
    if (scope.compilationUnitScope() != null && scope.compilationUnitScope().canSeeEverything()) {
        return true;
    }
    // GROOVY end
    if (isPublic())
        return true;

    SourceTypeBinding invocationType = scope.enclosingSourceType();
    if (invocationType == this)
        return true;

    if (invocationType == null) // static import call
        return !isPrivate() && scope.getCurrentPackage() == this.fPackage;

    if (isProtected()) {
        // answer true if the invocationType is the declaringClass or they are in the same package
        // OR the invocationType is a subclass of the declaringClass
        //    AND the invocationType is the invocationType or its subclass
        //    OR the type is a static method accessed directly through a type
        //    OR previous assertions are true for one of the enclosing type
        if (invocationType.fPackage == this.fPackage)
            return true;

        TypeBinding declaringClass = enclosingType(); // protected types always have an enclosing one
        if (declaringClass == null)
            return false; // could be null if incorrect top-level protected type
        declaringClass = declaringClass.erasure();// erasure cannot be null
        TypeBinding currentType = invocationType.erasure();
        // int depth = 0;
        do {
            if (declaringClass == invocationType)
                return true;
            if (currentType.findSuperTypeOriginatingFrom(declaringClass) != null)
                return true;
            // depth++;
            currentType = currentType.enclosingType();
        } while (currentType != null);
        return false;
    }
    if (isPrivate()) {
        // answer true if the receiver and the invocationType have a common enclosingType
        // already know they are not the identical type
        ReferenceBinding outerInvocationType = invocationType;
        ReferenceBinding temp = outerInvocationType.enclosingType();
        while (temp != null) {
            outerInvocationType = temp;
            temp = temp.enclosingType();
        }

        ReferenceBinding outerDeclaringClass = (ReferenceBinding) erasure();
        temp = outerDeclaringClass.enclosingType();
        while (temp != null) {
            outerDeclaringClass = temp;
            temp = temp.enclosingType();
        }
        return outerInvocationType == outerDeclaringClass;
    }

    // isDefault()
    return invocationType.fPackage == this.fPackage;
}

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

License:Open Source License

@Override
void checkDecapsulation(ReferenceBinding baseClass, Scope scope) {
    if (this.implementationStrategy != ImplementationStrategy.DIRECT) {
        this.accessId = createAccessAttribute(scope.enclosingSourceType().roleModel);
        scope.problemReporter().decapsulation(this, baseClass, scope, isSetter());
    }//from   w w  w. j a  va 2s .co  m
}

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

License:Open Source License

void checkDecapsulation(ReferenceBinding baseClass, Scope scope) {
    if (!this.resolvedMethod.canBeSeenBy(baseClass, this, scope)) {
        WeavingScheme weavingScheme = scope.compilerOptions().weavingScheme;
        this.implementationStrategy = weavingScheme == WeavingScheme.OTDRE ? ImplementationStrategy.DYN_ACCESS
                : ImplementationStrategy.DECAPS_WRAPPER;
        this.accessId = createAccessAttribute(scope.enclosingSourceType().roleModel);
        scope.problemReporter().decapsulation(this, baseClass, scope);
    } else {/*from   w  w w. ja  va  2s  .  c om*/
        this.implementationStrategy = ImplementationStrategy.DIRECT;
    }
}

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

License:Open Source License

private boolean isRoleOfSuperTeam(ReferenceBinding roleClass, Scope scope) {
    ReferenceBinding site = scope.enclosingSourceType();
    if (!site.isRole())
        return false;
    return site.enclosingType().superclass().isCompatibleWith(roleClass.enclosingType());
}

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

License:Open Source License

private static LocalDeclaration createLiftingStatement(Scope scope, Argument argument) {
    LiftingTypeReference ltr = (LiftingTypeReference) argument.type;
    int start = argument.type.sourceStart;
    int end = argument.type.sourceEnd;
    AstGenerator gen = new AstGenerator(start, end);

    // names:/*  w w w.  ja v a2  s. c om*/
    char[] oldName = argument.name;
    char[] newName = CharOperation.concat(OT_DOLLAR_NAME, oldName);
    argument.updateName(newName);

    // MyRole obj = _OT$liftToMyRole(_OT$obj); (via PotentialLiftExpression)
    TypeBinding roleType = scope.getType(ltr.roleToken);
    ReferenceBinding roleRef = (ReferenceBinding) roleType;
    //    using a PotentialLiftExpression allows us to defer type resolution.
    Expression liftCall = null;

    // spare the details during completion - see comment regarding local.declaration.initialization inside
    // InternalExtendedCompletionContext.searchVisibleVariablesAndMethods(Scope, ObjectVector, ObjectVector, ObjectVector, boolean)
    if (!Config.isUsingAssistParser()) {
        if (roleRef.isValidBinding() && roleRef.isRole()
                && (roleRef.tagBits & TagBits.HierarchyHasProblems) == 0
                && !RoleModel.hasTagBit(roleRef, RoleModel.BaseclassHasProblems)) {
            Expression receiverTeam = ThisReference.implicitThis();
            ReferenceBinding teamBinding = roleRef.enclosingType();
            if (TypeBinding.notEquals(teamBinding, scope.enclosingSourceType()))
                receiverTeam = gen.qualifiedThisReference(teamBinding);
            if (roleRef.baseclass() == null) {
                // static adjustment (OTJLD 2.3.2(a)):
                ReferenceBinding baseType = null;
                if (scope.classScope() instanceof OTClassScope) {
                    // try base scope first:
                    CompilationUnitScope baseScope = ((OTClassScope) scope.classScope())
                            .getBaseImportScope(scope);
                    if (baseScope != null) {
                        baseType = (ReferenceBinding) baseScope.getType(ltr.baseTokens, ltr.baseTokens.length);
                        baseScope.originalScope = null;
                    }
                }
                if (baseType == null || !baseType.isValidBinding())
                    // fall back to normal scope:
                    baseType = (ReferenceBinding) scope.getType(ltr.baseTokens, ltr.baseTokens.length);
                roleRef = (ReferenceBinding) TeamModel.getRoleToLiftTo(scope, baseType, roleRef, true, ltr);
                if (baseType.isTypeVariable() && roleRef == null)
                    roleRef = (ReferenceBinding) roleType; // fall back to the declared type
            }
            if (roleRef != null) {
                if (ltr.baseReference.dimensions() > 0)
                    roleType = scope.createArrayType(roleRef, ltr.baseReference.dimensions());
                liftCall = new PotentialLiftExpression(receiverTeam, gen.singleNameReference(newName),
                        ltr.roleReference);
            }
            // errors are reported by LiftingTypeReference.resolveType().
        }
    }
    //    assemble the variable decl:
    LocalDeclaration declaration = gen.localVariable(oldName, AstClone.copyTypeReference(ltr.roleReference),
            liftCall);

    // store local declaration in lifting type,
    // which may need to cancel some generated AST after resolve.
    // (cf. LiftingTypeReference.invalidate())
    ltr.fakedArgument = declaration;

    return declaration;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.lookup.AnchorMapping.java

License:Open Source License

private TypeBinding instantiateParameter(final Scope scope, final TypeBinding parameter, final int i,
        final MethodBinding currentMethod, final boolean isMethodEnhanced) {
    return RoleTypeCreator.deepSubstitute(parameter, scope.environment(), new IDependentTypeSubstitution() {
        @SuppressWarnings("synthetic-access")
        public TypeBinding substitute(DependentTypeBinding paramDependentType, TypeBinding[] typeArguments,
                int dimensions) {
            int srcIdx = isMethodEnhanced ? (i - AnchorMapping.this._methodSignatureEnhancer.ENHANCING_ARG_LEN)
                    : i;/*from   www  .  ja  v a  2s  . c  o m*/
            ITeamAnchor anchor = null;
            if (AnchorMapping.this._arguments != null)
                anchor = translateAnchor(scope, AnchorMapping.this._arguments[srcIdx], paramDependentType,
                        currentMethod);

            // missing a required anchor?
            if (anchor == null && paramDependentType.hasAnchorWithinThisMethodsSignature(currentMethod))
                return new ProblemReferenceBinding(paramDependentType.sourceName(), paramDependentType,
                        ProblemReasons.AnchorNotFound);

            if (anchor == null && AnchorMapping.this._receiver != null) {
                if (DependentTypeBinding.isDependentTypeOf(AnchorMapping.this._receiver.resolvedType,
                        paramDependentType._teamAnchor)) {
                    DependentTypeBinding depReceiver = (DependentTypeBinding) AnchorMapping.this._receiver.resolvedType;
                    return depReceiver._teamAnchor.getRoleTypeBinding(paramDependentType, typeArguments,
                            dimensions);
                }
                ITeamAnchor newAnchor = TeamAnchor.getTeamAnchor(AnchorMapping.this._receiver);
                if (newAnchor != null && newAnchor.isValidBinding()
                        && newAnchor != paramDependentType._teamAnchor) {
                    if (paramDependentType._teamAnchor.isPrefixLegal(scope.enclosingSourceType(), newAnchor)) {
                        newAnchor = paramDependentType._teamAnchor.setPathPrefix(newAnchor);
                        return newAnchor.getRoleTypeBinding(paramDependentType, typeArguments, dimensions);
                    }
                }
                if (DependentTypeBinding.isDependentTypeVariable(currentMethod.parameters[i])) {
                    TypeVariableBinding typeVariable = (TypeVariableBinding) ((DependentTypeBinding) currentMethod.parameters[i]).type;
                    ITeamAnchor[] anchors = typeVariable.anchors;
                    if (anchors != null && anchors[0] instanceof LocalVariableBinding) { // FIXME(SH): more positions?
                        int pos = ((LocalVariableBinding) anchors[0]).resolvedPosition;
                        if (pos < AnchorMapping.this._arguments.length)
                            anchor = translateAnchor(scope, AnchorMapping.this._arguments[pos],
                                    (DependentTypeBinding) currentMethod.parameters[i], currentMethod);
                    }
                }
            }
            if ((anchor = validAnchor(anchor)) != null) {
                // downgrading allowed:
                return anchor.getRoleTypeBinding(paramDependentType, typeArguments, dimensions);
            }
            return paramDependentType;
        }
    });
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.lookup.AnchorMapping.java

License:Open Source License

private ITeamAnchor translateAnchor(Scope scope, ASTNode typedNode, DependentTypeBinding paramDependentType,
        MethodBinding currentMethod) {/*from  w  ww .  j  a  v a2  s. co  m*/
    ProblemReporter problemReporter = scope != null ? scope.problemReporter() : null;
    ITeamAnchor anchor = null;
    if (paramDependentType.hasAnchorWithinThisMethodsSignature(currentMethod) && this._arguments != null) {
        // anchored to an argument:
        Statement anchorExpr = this._arguments[paramDependentType._argumentPosition];
        ReferenceBinding roleType = paramDependentType.getRealType();
        if (anchorExpr instanceof Expression)
            anchor = RoleTypeCreator.getAnchorVariableBinding(null, // site
                    (Expression) anchorExpr, // anchor
                    roleType, // roleType
                    problemReporter, //
                    typedNode); // typedNode
        else // when resolving a method spec, we interpret an Argument as an anchor expression 
            anchor = ((Argument) anchorExpr).binding;

    } else if (paramDependentType._teamAnchor instanceof TThisBinding) {
        // anchored to TThis (must be a real role):
        DependentTypeBinding paramRoleType = (DependentTypeBinding) (paramDependentType instanceof WeakenedTypeBinding
                ? paramDependentType.type
                : paramDependentType);
        ReferenceBinding tthisType = paramRoleType.enclosingType();
        ReferenceBinding site = scope != null ? scope.enclosingSourceType() : null;
        ReferenceBinding roleRef = paramRoleType.getRealType();
        // try to get anchor from _receiver:
        if (this._receiver != null && TypeAnalyzer.isVariableRef(this._receiver)) {
            boolean reportError = TeamModel.isTeamContainingRole(
                    (ReferenceBinding) this._receiver.resolvedType.leafComponentType(), roleRef);
            anchor = RoleTypeCreator.getAnchorVariableBinding(site, this._receiver, paramRoleType,
                    reportError ? problemReporter : null, null);
        }
        anchor = validAnchor(anchor);
        if (anchor == null)
            anchor = validAnchor(TThisBinding.getTThisForRole(roleRef, site));
        if (anchor != null) {
            if (!anchor.isTypeCompatibleWith(tthisType))
                anchor = null; // cancel if incompatible.
        }
    }
    return anchor;
}

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

License:Open Source License

/**
 * performs role type strengthening, preforms static adjustment (OTJLD 2.3.3(a).
 * Respects arrays and checks compatibility.
 * @param scope client context, guaranteed to be a team or a role
 * @param provided/*  w w  w .  j  a v a  2s  .  c  om*/
 * @param required
 * @param doAdjust should the adjusted role be returned (as opposed to just the strengthened)?
 * @param location where to report errors against
 * @return an exact role or null
 */
public static TypeBinding getRoleToLiftTo(Scope scope, TypeBinding provided, TypeBinding required,
        boolean doAdjust, ASTNode location) {
    ReferenceBinding requiredRef = null;
    if (required.isArrayType() && (required.leafComponentType() instanceof ReferenceBinding)) {
        requiredRef = (ReferenceBinding) required.leafComponentType();
    } else if (required instanceof ReferenceBinding) {
        requiredRef = (ReferenceBinding) required;
    }
    if (requiredRef != null && requiredRef.isRole()) {
        requiredRef = (ReferenceBinding) strengthenRoleType(scope.enclosingSourceType(), requiredRef);
        ReferenceBinding foundRole = null;
        if (requiredRef.baseclass() == null) {
            foundRole = adjustRoleToLiftTo(scope, provided, requiredRef, location);
            if (foundRole != null && !doAdjust)
                foundRole = requiredRef; // successful but revert to unadjusted
        } else {
            if (!provided.leafComponentType().isBaseType()) {
                ReferenceBinding providedLeaf = (ReferenceBinding) provided.leafComponentType();
                providedLeaf = RoleTypeCreator.maybeInstantiateFromPlayedBy(scope, providedLeaf);
                if (providedLeaf.isCompatibleWith(requiredRef.baseclass())
                        && required.dimensions() == provided.dimensions()) {
                    foundRole = requiredRef;
                }
            }
            // FIXME(SH): unneeded?
            //            // just check definite binding ambiguity:
            //            adjustRoleToLiftTo(scope, provided, requiredRef, location);
        }
        if (foundRole != null) {
            // success by translation
            if (required.dimensions() == 0)
                return foundRole;
            else
                return scope.createArrayType(foundRole, required.dimensions());
        }
    }
    return null;
}