Example usage for org.eclipse.jdt.internal.compiler.lookup TypeBinding enclosingType

List of usage examples for org.eclipse.jdt.internal.compiler.lookup TypeBinding enclosingType

Introduction

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

Prototype

public ReferenceBinding enclosingType() 

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 w w  .  j  av a 2 s .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.PatternLocator.java

License:Open Source License

protected char[] getQualifiedSourceName(TypeBinding binding) {
    TypeBinding type = binding instanceof ArrayBinding ? ((ArrayBinding) binding).leafComponentType : binding;
    if (type instanceof ReferenceBinding) {
        if (type.isLocalType()) {
            return CharOperation.concat(qualifiedSourceName(type.enclosingType()), new char[] { '.', '1', '.' },
                    binding.sourceName());
        } else if (type.isMemberType()) {
            return CharOperation.concat(qualifiedSourceName(type.enclosingType()), binding.sourceName(), '.');
        }/*from   w ww  .  j av  a  2s  .c o  m*/
    }
    return binding != null ? binding.qualifiedSourceName() : null;
}

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

License:Open Source License

public static TypeReference makeType(TypeBinding binding, ASTNode pos, boolean allowCompound) {
    int dims = binding.dimensions();
    binding = binding.leafComponentType();

    // Primitives

    char[] base = null;

    switch (binding.id) {
    case TypeIds.T_int:
        base = TypeConstants.INT;/*from   w w  w .  j  av a2  s  .c o  m*/
        break;
    case TypeIds.T_long:
        base = TypeConstants.LONG;
        break;
    case TypeIds.T_short:
        base = TypeConstants.SHORT;
        break;
    case TypeIds.T_byte:
        base = TypeConstants.BYTE;
        break;
    case TypeIds.T_double:
        base = TypeConstants.DOUBLE;
        break;
    case TypeIds.T_float:
        base = TypeConstants.FLOAT;
        break;
    case TypeIds.T_boolean:
        base = TypeConstants.BOOLEAN;
        break;
    case TypeIds.T_char:
        base = TypeConstants.CHAR;
        break;
    case TypeIds.T_void:
        base = TypeConstants.VOID;
        break;
    case TypeIds.T_null:
        return null;
    }

    if (base != null) {
        if (dims > 0) {
            TypeReference result = new ArrayTypeReference(base, dims, pos(pos));
            setGeneratedBy(result, pos);
            return result;
        }
        TypeReference result = new SingleTypeReference(base, pos(pos));
        setGeneratedBy(result, pos);
        return result;
    }

    if (binding.isAnonymousType()) {
        ReferenceBinding ref = (ReferenceBinding) binding;
        ReferenceBinding[] supers = ref.superInterfaces();
        if (supers == null || supers.length == 0)
            supers = new ReferenceBinding[] { ref.superclass() };
        if (supers[0] == null) {
            TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3));
            setGeneratedBy(result, pos);
            return result;
        }
        return makeType(supers[0], pos, false);
    }

    if (binding instanceof CaptureBinding) {
        return makeType(((CaptureBinding) binding).wildcard, pos, allowCompound);
    }

    if (binding.isUnboundWildcard()) {
        if (!allowCompound) {
            TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3));
            setGeneratedBy(result, pos);
            return result;
        } else {
            Wildcard out = new Wildcard(Wildcard.UNBOUND);
            setGeneratedBy(out, pos);
            out.sourceStart = pos.sourceStart;
            out.sourceEnd = pos.sourceEnd;
            return out;
        }
    }

    if (binding.isWildcard()) {
        WildcardBinding wildcard = (WildcardBinding) binding;
        if (wildcard.boundKind == Wildcard.EXTENDS) {
            if (!allowCompound) {
                return makeType(wildcard.bound, pos, false);
            } else {
                Wildcard out = new Wildcard(Wildcard.EXTENDS);
                setGeneratedBy(out, pos);
                out.bound = makeType(wildcard.bound, pos, false);
                out.sourceStart = pos.sourceStart;
                out.sourceEnd = pos.sourceEnd;
                return out;
            }
        } else if (allowCompound && wildcard.boundKind == Wildcard.SUPER) {
            Wildcard out = new Wildcard(Wildcard.SUPER);
            setGeneratedBy(out, pos);
            out.bound = makeType(wildcard.bound, pos, false);
            out.sourceStart = pos.sourceStart;
            out.sourceEnd = pos.sourceEnd;
            return out;
        } else {
            TypeReference result = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(pos, 3));
            setGeneratedBy(result, pos);
            return result;
        }
    }

    // Keep moving up via 'binding.enclosingType()' and gather generics from each binding. We stop after a local type, or a static type, or a top-level type.
    // Finally, add however many nullTypeArgument[] arrays as that are missing, inverse the list, toArray it, and use that as PTR's typeArgument argument.

    List<TypeReference[]> params = new ArrayList<TypeReference[]>();
    /* Calculate generics */ {
        TypeBinding b = binding;
        while (true) {
            boolean isFinalStop = b.isLocalType() || !b.isMemberType() || b.enclosingType() == null;

            TypeReference[] tyParams = null;
            if (b instanceof ParameterizedTypeBinding) {
                ParameterizedTypeBinding paramized = (ParameterizedTypeBinding) b;
                if (paramized.arguments != null) {
                    tyParams = new TypeReference[paramized.arguments.length];
                    for (int i = 0; i < tyParams.length; i++) {
                        tyParams[i] = makeType(paramized.arguments[i], pos, true);
                    }
                }
            }

            params.add(tyParams);
            if (isFinalStop)
                break;
            b = b.enclosingType();
        }
    }

    char[][] parts;

    if (binding.isTypeVariable()) {
        parts = new char[][] { binding.shortReadableName() };
    } else if (binding.isLocalType()) {
        parts = new char[][] { binding.sourceName() };
    } else {
        String[] pkg = new String(binding.qualifiedPackageName()).split("\\.");
        String[] name = new String(binding.qualifiedSourceName()).split("\\.");
        if (pkg.length == 1 && pkg[0].isEmpty())
            pkg = new String[0];
        parts = new char[pkg.length + name.length][];
        int ptr;
        for (ptr = 0; ptr < pkg.length; ptr++)
            parts[ptr] = pkg[ptr].toCharArray();
        for (; ptr < pkg.length + name.length; ptr++)
            parts[ptr] = name[ptr - pkg.length].toCharArray();
    }

    while (params.size() < parts.length)
        params.add(null);
    Collections.reverse(params);

    boolean isParamized = false;

    for (TypeReference[] tyParams : params) {
        if (tyParams != null) {
            isParamized = true;
            break;
        }
    }
    if (isParamized) {
        if (parts.length > 1) {
            TypeReference[][] typeArguments = params.toArray(new TypeReference[0][]);
            TypeReference result = new ParameterizedQualifiedTypeReference(parts, typeArguments, dims,
                    poss(pos, parts.length));
            setGeneratedBy(result, pos);
            return result;
        }
        TypeReference result = new ParameterizedSingleTypeReference(parts[0], params.get(0), dims, pos(pos));
        setGeneratedBy(result, pos);
        return result;
    }

    if (dims > 0) {
        if (parts.length > 1) {
            TypeReference result = new ArrayQualifiedTypeReference(parts, dims, poss(pos, parts.length));
            setGeneratedBy(result, pos);
            return result;
        }
        TypeReference result = new ArrayTypeReference(parts[0], dims, pos(pos));
        setGeneratedBy(result, pos);
        return result;
    }

    if (parts.length > 1) {
        TypeReference result = new QualifiedTypeReference(parts, poss(pos, parts.length));
        setGeneratedBy(result, pos);
        return result;
    }
    TypeReference result = new SingleTypeReference(parts[0], pos(pos));
    setGeneratedBy(result, pos);
    return result;
}

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

License:Open Source License

/**
 * Answer true if the receiver is visible to the receiverType and the invocationType.
 */// w  w  w.  ja  v a2 s. c o  m
public final boolean canBeSeenBy(ReferenceBinding receiverType, ReferenceBinding invocationType) {
    if (isPublic())
        return true;

    if (invocationType == this && invocationType == receiverType)
        return true;

    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 == this)
            return true;
        if (invocationType.fPackage == this.fPackage)
            return true;

        TypeBinding currentType = invocationType.erasure();
        TypeBinding declaringClass = enclosingType().erasure(); // protected types always have an enclosing one
        if (declaringClass == invocationType)
            return true;
        if (declaringClass == null)
            return false; // could be null if incorrect top-level protected type
        //int depth = 0;
        do {
            if (currentType.findSuperTypeOriginatingFrom(declaringClass) != null)
                return true;
            //depth++;
            currentType = currentType.enclosingType();
        } while (currentType != null);
        return false;
    }

    if (isPrivate()) {
        // answer true if the receiverType is the receiver or its enclosingType
        // AND the invocationType and the receiver have a common enclosingType
        receiverCheck: {
            if (!(receiverType == this || receiverType == enclosingType())) {
                // special tolerance for type variable direct bounds, but only if compliance <= 1.6, see: https://bugs.eclipse.org/bugs/show_bug.cgi?id=334622
                if (receiverType.isTypeVariable()) {
                    TypeVariableBinding typeVariable = (TypeVariableBinding) receiverType;
                    if (typeVariable.environment.globalOptions.complianceLevel <= ClassFileConstants.JDK1_6
                            && (typeVariable.isErasureBoundTo(erasure())
                                    || typeVariable.isErasureBoundTo(enclosingType().erasure())))
                        break receiverCheck;
                }
                return false;
            }
        }

        if (invocationType != this) {
            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();
            }
            if (outerInvocationType != outerDeclaringClass)
                return false;
        }
        return true;
    }

    // isDefault()
    if (invocationType.fPackage != this.fPackage)
        return false;

    ReferenceBinding currentType = receiverType;
    TypeBinding originalDeclaringClass = (enclosingType() == null ? this : enclosingType()).original();
    do {
        if (currentType.isCapture()) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=285002
            if (originalDeclaringClass == currentType.erasure().original())
                return true;
        } else {
            if (originalDeclaringClass == currentType.original())
                return true;
        }
        PackageBinding currentPackage = currentType.fPackage;
        // package could be null for wildcards/intersection types, ignore and recurse in superclass
        if (currentPackage != null && currentPackage != this.fPackage)
            return false;
    } while ((currentType = currentType.superclass()) != null);
    return false;
}

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 w  w  w. j av  a 2s . 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.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 om
 * In raw mode, all parameterized type denoting same original type are converted
 * to raw types. e.g.
 * class X <T> {
 *   X<T> foo;
 *   X<String> bar;
 * } when used in raw fashion, then type of both foo and bar is raw type X.
 *
 */
public static TypeBinding substitute(Substitution substitution, TypeBinding originalType) {
    if (originalType == null)
        return null;
    switch (originalType.kind()) {

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

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

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

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

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

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

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

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

License:Open Source License

private TypeBinding leastContainingInvocation(TypeBinding mec, Object invocationData, List lubStack) {
    if (invocationData == null)
        return mec; // no alternate invocation
    if (invocationData instanceof TypeBinding) { // only one invocation, simply return it (array only allocated if more than one)
        return (TypeBinding) invocationData;
    }/*  w ww.  j  av  a  2s.  co  m*/
    TypeBinding[] invocations = (TypeBinding[]) invocationData;

    // if mec is an array type, intersect invocation leaf component types, then promote back to array
    int dim = mec.dimensions();
    mec = mec.leafComponentType();

    int argLength = mec.typeVariables().length;
    if (argLength == 0)
        return mec; // should be caught by no invocation check

    // infer proper parameterized type from invocations
    TypeBinding[] bestArguments = new TypeBinding[argLength];
    for (int i = 0, length = invocations.length; i < length; i++) {
        TypeBinding invocation = invocations[i].leafComponentType();
        switch (invocation.kind()) {
        case Binding.GENERIC_TYPE:
            TypeVariableBinding[] invocationVariables = invocation.typeVariables();
            for (int j = 0; j < argLength; j++) {
                TypeBinding bestArgument = leastContainingTypeArgument(bestArguments[j], invocationVariables[j],
                        (ReferenceBinding) mec, j, lubStack);
                if (bestArgument == null)
                    return null;
                bestArguments[j] = bestArgument;
            }
            break;
        case Binding.PARAMETERIZED_TYPE:
            ParameterizedTypeBinding parameterizedType = (ParameterizedTypeBinding) invocation;
            for (int j = 0; j < argLength; j++) {
                TypeBinding bestArgument = leastContainingTypeArgument(bestArguments[j],
                        parameterizedType.arguments[j], (ReferenceBinding) mec, j, lubStack);
                if (bestArgument == null)
                    return null;
                bestArguments[j] = bestArgument;
            }
            break;
        case Binding.RAW_TYPE:
            return dim == 0 ? invocation : environment().createArrayType(invocation, dim); // raw type is taking precedence
        }
    }
    TypeBinding least = environment().createParameterizedType((ReferenceBinding) mec.erasure(), bestArguments,
            mec.enclosingType());
    return dim == 0 ? least : environment().createArrayType(least, dim);
}

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

License:Open Source License

public static Expression convertToDynAccess(BlockScope scope, AllocationExpression expression, int accessId) {
    TypeBinding baseclass = expression.resolvedType;
    AstGenerator gen = new AstGenerator(expression);
    Expression receiver = gen.typeReference(baseclass);
    char[] selector = CalloutImplementorDyn.OT_ACCESS_STATIC;
    int modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic;
    Expression[] arguments = expression.arguments;
    Expression enclosingInstance = null;
    if (expression instanceof QualifiedAllocationExpression) {
        enclosingInstance = ((QualifiedAllocationExpression) expression).enclosingInstance;
    } else if (baseclass.isMemberType()) {
        // extract the enclosing base instance from an outer playedBy:
        ReferenceBinding enclosingTeam = scope.enclosingReceiverType().enclosingType();
        if (enclosingTeam != null
                && TypeBinding.equalsEquals(baseclass.enclosingType(), enclosingTeam.baseclass)) {
            enclosingInstance = gen.fieldReference(gen.qualifiedThisReference(gen.typeReference(enclosingTeam)),
                    IOTConstants._OT_BASE);
            enclosingInstance.resolve(scope);
        }/* ww w . jav a  2  s.c  o m*/
    }
    if (enclosingInstance != null) {
        if (arguments == null) {
            arguments = new Expression[] { enclosingInstance };
        } else {
            int len = arguments.length;
            System.arraycopy(arguments, 0, arguments = new Expression[len + 1], 1, len);
            arguments[0] = enclosingInstance;
        }
    }
    MessageSend allocSend = new MessageSend() {
        @Override
        public boolean isDecapsulationAllowed(Scope scope2) {
            // this message send can decapsulate independent of scope
            return true;
        }

        @Override
        public DecapsulationState getBaseclassDecapsulation() {
            return DecapsulationState.ALLOWED;
        }
    };
    gen.setPositions(allocSend);
    allocSend.receiver = receiver;
    allocSend.selector = selector;
    allocSend.constant = Constant.NotAConstant;
    allocSend.actualReceiverType = baseclass;
    allocSend.accessId = accessId;
    allocSend.arguments = createResolvedAccessArguments(gen, accessId, arguments, scope);
    allocSend.binding = new MethodBinding(modifiers,
            new TypeBinding[] { TypeBinding.INT, TypeBinding.INT,
                    scope.createArrayType(scope.getJavaLangObject(), 1), scope.getOrgObjectteamsITeam() },
            Binding.NO_EXCEPTIONS, (ReferenceBinding) baseclass);
    allocSend.binding.returnType = scope.getJavaLangObject();
    allocSend.binding.selector = selector;
    return gen.resolvedCastExpression(allocSend, baseclass, CastExpression.RAW);
}

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

License:Open Source License

/** For role types ignore weakening and anchors. */
static boolean areTypesEqual(TypeBinding one, TypeBinding two) {
    if (TypeBinding.equalsEquals(one, two))
        return true;
    ReferenceBinding enclosingOne = one.enclosingType();
    if (enclosingOne == null)
        return false;
    ReferenceBinding enclosingTwo = two.enclosingType();
    if (enclosingTwo == null)
        return false;
    if (!areTypesEqual(enclosingOne, enclosingTwo))
        return false;
    return CharOperation.equals(one.sourceName(), two.sourceName());
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.mappings.CallinImplementor.java

License:Open Source License

/** Generate the statements for a callin wrapper method.
 *
 *///w w w  .  ja va  2  s . c om
boolean generateCallinStatements(MethodDeclaration callinWrapperDecl,
        CallinMappingDeclaration callinBindingDeclaration, RoleModel roleModel, MethodBinding roleMethodBinding,
        ReferenceBinding baseTypeBinding, MethodSpec baseMethodSpec, TypeBinding wrapperReturnType,
        boolean isReturnBoxed, AstGenerator gen) {
    if (callinBindingDeclaration.mappings == AbstractMethodMappingDeclaration.PENDING_MAPPINGS)
        return false; // cannot proceed, required info is not parsed.

    if (this._role.isRoleFile()) {
        this.synthGen = MethodModel.setupSourcePositionMapping(callinWrapperDecl,
                this._role.getTeamModel().getAst(), this._role, null);
        if (this.synthGen != null)
            gen = this.synthGen;
    }

    PredicateGenerator predGen = new PredicateGenerator(roleModel.getBinding(),
            callinBindingDeclaration.isReplaceCallin());

    char[] roleTypeName = roleModel.getInterfaceAst().name;

    //_OT$base_arg
    char[] otBaseArg = IOTConstants.BASE;

    //myRoleMethod
    char[] roleMethodName = roleMethodBinding.selector;

    TypeBinding[] roleParameters = roleMethodBinding.getSourceParameters();

    ArrayList<Statement> statements = new ArrayList<Statement>();

    // -------------- base predicate check -------
    char[] resultName = null;
    if (callinBindingDeclaration.callinModifier == TerminalTokens.TokenNameafter
            && baseMethodSpec.resolvedType() != TypeBinding.VOID) {
        resultName = IOTConstants.RESULT;
    }
    Statement predicateCheck = predGen.createBasePredicateCheck(callinBindingDeclaration, baseMethodSpec,
            resultName, gen);
    if (predicateCheck != null) {
        statements.add(predicateCheck);
    }

    // ------------- support for reflective function isExecutingCallin():
    // boolean oldIsExecutingCallin = _OT$setExecutingCallin();
    // try { ... main dispatching statements ... }
    // finally { resetFlag }
    MessageSend resetFlag = setExecutingCallin(roleModel, statements);

    // from here on all statements go into the try block - with "finally { resetFlag(); }"
    ArrayList<Statement> tryStatements = new ArrayList<Statement>();

    // -------------- call receiver & arguments --------------
    //_OT$role.myRoleMethod(_OT$param0, ...);
    // or:
    //MyRole.myRoleMethod(_OT$param0, ...);
    // or:
    //MyTeam.this.myMethod(_OT$param0, ...);
    Expression receiver = null;
    Expression[] messageSendArguments = makeWrapperCallArguments(callinBindingDeclaration, callinWrapperDecl,
            baseMethodSpec, null, resultName != null /*hasResultArg*/);
    if (messageSendArguments == null) {
        callinBindingDeclaration.tagAsHavingErrors();
        return false;
    }
    // pack unmapped arguments (positions are set by above makeWrapperCallArguments):
    packUnmappedArgs(baseMethodSpec, callinBindingDeclaration, callinWrapperDecl, tryStatements, gen);

    // for role-side predicate
    Expression[] predicateArgs = null;
    int offset = callinBindingDeclaration.isReplaceCallin() ? getMethodSignatureEnhancer().ENHANCING_ARG_LEN
            : 0;
    int plainLen = messageSendArguments.length - offset;
    boolean needRoleVar = false;
    if (roleMethodBinding.isStatic()) {
        receiver = gen.singleNameReference(roleMethodBinding.declaringClass.sourceName());
        // predicate args:
        if (offset > 0)
            System.arraycopy(messageSendArguments, offset, predicateArgs = new Expression[plainLen], 0,
                    plainLen); // retrench
        else
            predicateArgs = messageSendArguments; // nothing to retrench
        predicateArgs = maybeAddResultReference(callinBindingDeclaration, predicateArgs, resultName, gen);
    } else { // !roleMethodBinding.isStatic()
        if (!roleModel.getBinding().isCompatibleWith(roleMethodBinding.declaringClass)) {
            receiver = gen.qualifiedThisReference(TeamModel.strengthenEnclosing(
                    roleModel.getBinding().enclosingType(), roleMethodBinding.declaringClass));
        } else {
            receiver = gen.singleNameReference(ROLE_VAR_NAME);
            needRoleVar = true;

            // receiver for private method (doesn't exist in ifc-part) needs to be casted to the class.
            // Scope.findMethod() takes care of visibility if isMethodMappingWrapper() is detected.
            if (roleMethodBinding.isPrivate())
                receiver = gen.castExpression(receiver, gen.typeReference(roleModel.getClassPartBinding()),
                        CastExpression.NEED_CLASS);
            // Note on using NEED_CLASS above:
            // even if role is ParameterizedTypeBinding Scope.findMethod() must find a RoleTypeBinding
            // in order to enter the branch that checks isMethodMappingWrapper()
            // with CastExpression.RAW a RawTypeBinding might occur that is not recognized by Scope.findMethod()
            // see testA12_genericRoleFeature16f() which reports bogus visibility problem is RAW is used.
        }

        //MyRole _OT$role = _OT$liftToMyRole(_OT$base_arg);
        if (needRoleVar)
            tryStatements.add(
                    createLiftedRoleVar(callinBindingDeclaration, roleModel, baseTypeBinding, otBaseArg, gen));

        // store mapped arguments in local variables to use for predicate check
        // and wrapper call.
        // first create local variable for real arguments:
        assert roleParameters.length == plainLen;
        Expression[] newArgs = new Expression[plainLen];
        for (int i = offset; i < messageSendArguments.length; i++) {
            char[] localName = (OT_LOCAL + i).toCharArray();
            tryStatements.add(gen.localVariable(localName, roleParameters[i - offset],
                    new PotentialRoleReceiverExpression(messageSendArguments[i], ROLE_VAR_NAME,
                            gen.typeReference(roleModel.getClassPartBinding()))));
            newArgs[i - offset] = gen.singleNameReference(localName);
        }
        // predicate arguments (w/o enhancement but w/ result_opt):
        predicateArgs = maybeAddResultReference(callinBindingDeclaration, newArgs, resultName, gen);
        // prepend (generated) enhanced arguments
        System.arraycopy(newArgs, 0, newArgs = new Expression[messageSendArguments.length], offset, plainLen);
        for (int i = 0; i < offset; i++) {
            newArgs[i] = messageSendArguments[i]; // generated arg is not mapped, nor stored
        }
        messageSendArguments = newArgs; // from now on use local names instead of mapped expressions
    } // closes if(roleMethodBinding.isStatic())

    // role side predicate:
    predicateCheck = predGen.createPredicateCheck(callinBindingDeclaration, roleModel.getAst(), receiver,
            predicateArgs, messageSendArguments, gen);
    if (predicateCheck != null)
        // predicateCheck(_OT$role)
        tryStatements.add(predicateCheck);

    // ------------- the role message send:
    MessageSend roleMessageSend = gen.messageSend(receiver, roleMethodName, messageSendArguments);
    roleMessageSend.isPushedOutRoleMethodCall = true;

    // debugging should skip the return statement.
    AstGenerator stepOverGen = new AstGenerator(STEP_OVER_SOURCEPOSITION_START, STEP_OVER_SOURCEPOSITION_END);
    // ---------------- store or ignore the result:
    if (callinBindingDeclaration.isReplaceCallin()) {
        //   <WrapperReturn> _OT$result;
        //   try {
        //     _OT$result = _OT$role.myRoleMethod(_OT$param0);
        //   finally {
        //     _OT$setExecutingCallin(oldIsExecutingCallin);
        //   }

        //   $if isReturnBoxed
        //     if (_OT$result == null) throw new ResultNotProvidedException(..);
        //   $endif

        //   $if isResultMapped
        //     return <expressionMappedToResult>;
        //   $else
        //     return _OT$result;
        //   $endif

        Expression roleMessageSendExpression = roleMessageSend;

        if (roleMethodBinding.returnType.isArrayType()) {
            // if return from role method requires array-lowering, we must determine how to access the team (receiver of lowering-method):
            TypeBinding returnLeaf = roleMethodBinding.returnType.leafComponentType();
            findEnclosingTeam: if (returnLeaf.isRole()) {
                ReferenceBinding returnEnclosing = returnLeaf.enclosingType(); // the team type containing the returned role
                ReferenceBinding currentType = roleModel.getBinding();
                while ((currentType = currentType.enclosingType()) != null) // traverse all types accessible as this$<n>
                    if (TypeBinding.equalsEquals(currentType, returnEnclosing))
                        break findEnclosingTeam; // successful
                // not found, which means this$<n> is not a suitable receiver for array lowering, must use 'receiver' instead:
                roleMessageSendExpression = new PotentialLowerExpression(roleMessageSend, wrapperReturnType,
                        receiver);
            }
        }
        callinBindingDeclaration.resultVar = gen.localVariable(IOTConstants.OT_RESULT, wrapperReturnType, null);
        callinBindingDeclaration.resultVar.type.setBaseclassDecapsulation(DecapsulationState.REPORTED);
        tryStatements.add(callinBindingDeclaration.resultVar);
        tryStatements.add(
                gen.assignment(gen.singleNameReference(IOTConstants.OT_RESULT), roleMessageSendExpression));

        // ResultNotProvidedException?
        if (isReturnBoxed && !callinBindingDeclaration.isResultMapped) {
            tryStatements.add(genResultNotProvidedCheck(this._role.getTeamModel().getBinding().sourceName(),
                    roleTypeName, roleMethodBinding, baseTypeBinding, baseMethodSpec, gen));
        }
        // ------------- possibly convert using result mapping
        if (callinBindingDeclaration.mappings != null && callinBindingDeclaration.isResultMapped) {
            tryStatements.add(stepOverGen.returnStatement(new PotentialRoleReceiverExpression(
                    callinBindingDeclaration.getResultExpression(baseMethodSpec, isReturnBoxed, stepOverGen),
                    ROLE_VAR_NAME, gen.typeReference(roleModel.getClassPartBinding()))));
        } else {
            tryStatements
                    .add(stepOverGen.returnStatement(stepOverGen.singleNameReference(IOTConstants.OT_RESULT)));
        }

        TryStatement tryFinally = gen.tryFinally(tryStatements.toArray(new Statement[tryStatements.size()]),
                new Statement[] { resetFlag });
        // for debugging:
        //         tryFinally.catchArguments = new Argument[] {
        //            gen.argument("e1".toCharArray(), gen.singleTypeReference("RuntimeException".toCharArray())),
        //            gen.argument("e2".toCharArray(), gen.singleTypeReference("Error".toCharArray()))
        //         };
        //         tryFinally.catchBlocks = new Block[] {
        //            gen.block(new Statement[] {
        //                  gen.messageSend(
        //                        gen.singleNameReference("e1".toCharArray()),
        //                        "printStackTrace".toCharArray(),
        //                        null),
        //                  gen.throwStatement(gen.singleNameReference("e1".toCharArray()))
        //            }),
        //            gen.block(new Statement[] {
        //                  gen.messageSend(
        //                        gen.singleNameReference("e2".toCharArray()),
        //                        "printStackTrace".toCharArray(),
        //                        null),
        //                  gen.throwStatement(gen.singleNameReference("e2".toCharArray()))
        //            })
        //         };
        statements.add(tryFinally);

    } else {
        // try {
        //    _OT$role.myRoleMethod(_OT$param0);
        // finally {
        //     _OT$setExecutingCallin(oldIsExecutingCallin);
        // }
        tryStatements.add(roleMessageSend);
        statements.add(gen.tryFinally(tryStatements.toArray(new Statement[tryStatements.size()]),
                new Statement[] { resetFlag }));
        statements.add(stepOverGen.returnStatement(null)); // empty return to ensure step-over in the end
    }

    callinWrapperDecl.setStatements(statements.toArray(new Statement[statements.size()]));

    // parameter mappings are detected during makeWrapperCallArguments
    // ----------- byte code attribute -------------
    if (callinBindingDeclaration.positions != null) {
        MethodModel model = MethodModel.getModel(callinWrapperDecl);
        model.addAttribute(new CallinParamMappingsAttribute(callinBindingDeclaration));
    }

    return true;
}