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

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

Introduction

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

Prototype

public static boolean equalsEquals(TypeBinding that, TypeBinding other) 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

private void selectFrom(Binding binding, CompilationUnitDeclaration parsedUnit, ICompilationUnit unit,
        boolean isDeclaration) {
    if (binding instanceof TypeVariableBinding) {
        TypeVariableBinding typeVariableBinding = (TypeVariableBinding) binding;
        Binding enclosingElement = typeVariableBinding.declaringElement;
        this.noProposal = false;

        if (enclosingElement instanceof SourceTypeBinding) {
            SourceTypeBinding enclosingType = (SourceTypeBinding) enclosingElement;
            if (isLocal(enclosingType) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalTypeParameter(typeVariableBinding);
            } else {
                this.requestor.acceptTypeParameter(enclosingType.qualifiedPackageName(),
                        enclosingType.qualifiedSourceName(), typeVariableBinding.sourceName(), false,
                        this.actualSelectionStart, this.actualSelectionEnd);
            }//from   w w w  .ja  v a 2 s . c  o  m
        } else if (enclosingElement instanceof MethodBinding) {
            MethodBinding enclosingMethod = (MethodBinding) enclosingElement;
            if (isLocal(enclosingMethod.declaringClass) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalMethodTypeParameter(typeVariableBinding);
            } else {
                this.requestor.acceptMethodTypeParameter(enclosingMethod.declaringClass.qualifiedPackageName(),
                        enclosingMethod.declaringClass.qualifiedSourceName(),
                        enclosingMethod.isConstructor() ? enclosingMethod.declaringClass.sourceName()
                                : enclosingMethod.selector,
                        enclosingMethod.sourceStart(), enclosingMethod.sourceEnd(),
                        typeVariableBinding.sourceName(), false, this.actualSelectionStart,
                        this.actualSelectionEnd);
            }
        }
        this.acceptedAnswer = true;
    } else if (binding instanceof ReferenceBinding) {
        ReferenceBinding typeBinding = (ReferenceBinding) binding;
        if (typeBinding instanceof ProblemReferenceBinding) {
            TypeBinding closestMatch = typeBinding.closestMatch();
            if (closestMatch instanceof ReferenceBinding) {
                typeBinding = (ReferenceBinding) closestMatch;
            } else {
                typeBinding = null;
            }
        }
        if (typeBinding == null)
            return;
        if (isLocal(typeBinding) && this.requestor instanceof SelectionRequestor) {
            this.noProposal = false;
            ((SelectionRequestor) this.requestor).acceptLocalType(typeBinding);
        } else {
            this.noProposal = false;

            this.requestor.acceptType(typeBinding.qualifiedPackageName(), typeBinding.qualifiedSourceName(),
                    typeBinding.modifiers, false, typeBinding.computeUniqueKey(), this.actualSelectionStart,
                    this.actualSelectionEnd);
        }
        this.acceptedAnswer = true;
    } else if (binding instanceof MethodBinding) {
        MethodBinding methodBinding = getCorrectMethodBinding((MethodBinding) binding);
        this.noProposal = false;

        boolean isValuesOrValueOf = false;
        if (binding instanceof SyntheticMethodBinding) {
            SyntheticMethodBinding syntheticMethodBinding = (SyntheticMethodBinding) binding;
            if (syntheticMethodBinding.purpose == SyntheticMethodBinding.EnumValues
                    || syntheticMethodBinding.purpose == SyntheticMethodBinding.EnumValueOf) {
                isValuesOrValueOf = true;
            }
        }

        if (!isValuesOrValueOf && !methodBinding.isSynthetic()) {
            TypeBinding[] parameterTypes = methodBinding.original().parameters;
            int length = parameterTypes.length;
            char[][] parameterPackageNames = new char[length][];
            char[][] parameterTypeNames = new char[length][];
            String[] parameterSignatures = new String[length];
            for (int i = 0; i < length; i++) {
                parameterPackageNames[i] = parameterTypes[i].qualifiedPackageName();
                parameterTypeNames[i] = parameterTypes[i].qualifiedSourceName();
                parameterSignatures[i] = new String(getSignature(parameterTypes[i])).replace('/', '.');
            }

            TypeVariableBinding[] typeVariables = methodBinding.original().typeVariables;
            length = typeVariables == null ? 0 : typeVariables.length;
            char[][] typeParameterNames = new char[length][];
            char[][][] typeParameterBoundNames = new char[length][][];
            for (int i = 0; i < length; i++) {
                TypeVariableBinding typeVariable = typeVariables[i];
                typeParameterNames[i] = typeVariable.sourceName;
                if (typeVariable.firstBound == null) {
                    typeParameterBoundNames[i] = new char[0][];
                } else if (TypeBinding.equalsEquals(typeVariable.firstBound, typeVariable.superclass)) {
                    int boundCount = 1
                            + (typeVariable.superInterfaces == null ? 0 : typeVariable.superInterfaces.length);
                    typeParameterBoundNames[i] = new char[boundCount][];
                    typeParameterBoundNames[i][0] = typeVariable.superclass.sourceName;
                    for (int j = 1; j < boundCount; j++) {
                        typeParameterBoundNames[i][j] = typeVariables[i].superInterfaces[j - 1].sourceName;
                    }
                } else {
                    int boundCount = typeVariable.superInterfaces == null ? 0
                            : typeVariable.superInterfaces.length;
                    typeParameterBoundNames[i] = new char[boundCount][];
                    for (int j = 0; j < boundCount; j++) {
                        typeParameterBoundNames[i][j] = typeVariables[i].superInterfaces[j].sourceName;
                    }
                }
            }

            ReferenceBinding declaringClass = methodBinding.declaringClass;
            if (isLocal(declaringClass) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalMethod(methodBinding);
            } else {
                this.requestor.acceptMethod(declaringClass.qualifiedPackageName(),
                        declaringClass.qualifiedSourceName(),
                        declaringClass.enclosingType() == null ? null
                                : new String(getSignature(declaringClass.enclosingType())),
                        methodBinding.isConstructor() ? declaringClass.sourceName() : methodBinding.selector,
                        parameterPackageNames, parameterTypeNames, parameterSignatures, typeParameterNames,
                        typeParameterBoundNames, methodBinding.isConstructor(), isDeclaration,
                        methodBinding.computeUniqueKey(), this.actualSelectionStart, this.actualSelectionEnd);
            }
        }
        this.acceptedAnswer = true;
    } else if (binding instanceof FieldBinding) {
        FieldBinding fieldBinding = (FieldBinding) binding;
        ReferenceBinding declaringClass = fieldBinding.declaringClass;
        if (declaringClass != null) { // arraylength
            this.noProposal = false;
            if (isLocal(declaringClass) && this.requestor instanceof SelectionRequestor) {
                ((SelectionRequestor) this.requestor).acceptLocalField(fieldBinding);
            } else {
                // if the binding is a problem field binding, we want to make sure
                // we can retrieve the closestMatch if the problem reason is NotVisible
                FieldBinding currentFieldBinding = fieldBinding;
                while (currentFieldBinding instanceof ProblemFieldBinding) {
                    ProblemFieldBinding problemFieldBinding = (ProblemFieldBinding) currentFieldBinding;
                    if (problemFieldBinding.problemId() == ProblemReasons.NotVisible) {
                        currentFieldBinding = problemFieldBinding.closestMatch;
                    } else {
                        currentFieldBinding = null;
                    }
                }
                char[] fieldName = null;
                char[] key = null;
                if (currentFieldBinding != null) {
                    fieldName = currentFieldBinding.name;
                    key = currentFieldBinding.computeUniqueKey();
                } else {
                    fieldName = fieldBinding.name;
                    key = fieldBinding.computeUniqueKey();
                }
                this.requestor.acceptField(declaringClass.qualifiedPackageName(),
                        declaringClass.qualifiedSourceName(), fieldName, false, key, this.actualSelectionStart,
                        this.actualSelectionEnd);
            }
            this.acceptedAnswer = true;
        }
    } else if (binding instanceof LocalVariableBinding) {
        if (this.requestor instanceof SelectionRequestor) {
            ((SelectionRequestor) this.requestor).acceptLocalVariable((LocalVariableBinding) binding, unit);
            this.acceptedAnswer = true;
        } else {
            // open on the type of the variable
            selectFrom(((LocalVariableBinding) binding).type, parsedUnit, false);
        }
    } else if (binding instanceof ArrayBinding) {
        selectFrom(((ArrayBinding) binding).leafComponentType, parsedUnit, false);
        // open on the type of the array
    } else if (binding instanceof PackageBinding) {
        PackageBinding packageBinding = (PackageBinding) binding;
        this.noProposal = false;
        this.requestor.acceptPackage(packageBinding.readableName());
        this.acceptedAnswer = true;
    } else if (binding instanceof BaseTypeBinding) {
        this.acceptedAnswer = true;
    }
}

From source file:org.eclipse.che.jdt.internal.core.search.matching.PatternLocator.java

License:Open Source License

protected void updateMatch(TypeBinding[] argumentsBinding, MatchLocator locator, char[][] patternArguments,
        boolean hasTypeParameters) {
    // Only possible if locator has an unit scope.
    if (locator.unitScope == null)
        return;// w  w  w  . j  av  a2s . c o m

    // First compare lengthes
    int patternTypeArgsLength = patternArguments == null ? 0 : patternArguments.length;
    int typeArgumentsLength = argumentsBinding == null ? 0 : argumentsBinding.length;

    // Initialize match rule
    int matchRule = this.match.getRule();
    if (this.match.isRaw()) {
        if (patternTypeArgsLength != 0) {
            matchRule &= ~SearchPattern.R_FULL_MATCH;
        }
    }
    if (hasTypeParameters) {
        matchRule = SearchPattern.R_ERASURE_MATCH;
    }

    // Compare arguments lengthes
    if (patternTypeArgsLength == typeArgumentsLength) {
        if (!this.match.isRaw() && hasTypeParameters) {
            // generic patterns are always not compatible match
            this.match.setRule(SearchPattern.R_ERASURE_MATCH);
            return;
        }
    } else {
        if (patternTypeArgsLength == 0) {
            if (!this.match.isRaw() || hasTypeParameters) {
                this.match.setRule(matchRule & ~SearchPattern.R_FULL_MATCH);
            }
        } else if (typeArgumentsLength == 0) {
            // raw binding is always compatible
            this.match.setRule(matchRule & ~SearchPattern.R_FULL_MATCH);
        } else {
            this.match.setRule(0); // impossible match
        }
        return;
    }
    if (argumentsBinding == null || patternArguments == null) {
        this.match.setRule(matchRule);
        return;
    }

    // Compare binding for each type argument only if pattern is not erasure only and at first level
    if (!hasTypeParameters && !this.match.isRaw() && (this.match.isEquivalent() || this.match.isExact())) {
        for (int i = 0; i < typeArgumentsLength; i++) {
            // Get parameterized type argument binding
            TypeBinding argumentBinding = argumentsBinding[i];
            if (argumentBinding instanceof CaptureBinding) {
                WildcardBinding capturedWildcard = ((CaptureBinding) argumentBinding).wildcard;
                if (capturedWildcard != null)
                    argumentBinding = capturedWildcard;
            }
            // Get binding for pattern argument
            char[] patternTypeArgument = patternArguments[i];
            char patternWildcard = patternTypeArgument[0];
            char[] patternTypeName = patternTypeArgument;
            int patternWildcardKind = -1;
            switch (patternWildcard) {
            case Signature.C_STAR:
                if (argumentBinding.isWildcard()) {
                    WildcardBinding wildcardBinding = (WildcardBinding) argumentBinding;
                    if (wildcardBinding.boundKind == Wildcard.UNBOUND)
                        continue;
                }
                matchRule &= ~SearchPattern.R_FULL_MATCH;
                continue; // unbound parameter always match
            case Signature.C_EXTENDS:
                patternWildcardKind = Wildcard.EXTENDS;
                patternTypeName = CharOperation.subarray(patternTypeArgument, 1, patternTypeArgument.length);
                break;
            case Signature.C_SUPER:
                patternWildcardKind = Wildcard.SUPER;
                patternTypeName = CharOperation.subarray(patternTypeArgument, 1, patternTypeArgument.length);
                break;
            default:
                break;
            }
            patternTypeName = Signature.toCharArray(patternTypeName);
            TypeBinding patternBinding = locator.getType(patternTypeArgument, patternTypeName);

            // If have no binding for pattern arg, then we won't be able to refine accuracy
            if (patternBinding == null) {
                if (argumentBinding.isWildcard()) {
                    WildcardBinding wildcardBinding = (WildcardBinding) argumentBinding;
                    if (wildcardBinding.boundKind == Wildcard.UNBOUND) {
                        matchRule &= ~SearchPattern.R_FULL_MATCH;
                    } else {
                        this.match.setRule(SearchPattern.R_ERASURE_MATCH);
                        return;
                    }
                }
                continue;
            }

            // Verify the pattern binding is compatible with match type argument binding
            switch (patternWildcard) {
            case Signature.C_STAR: // UNBOUND pattern
                // unbound always match => skip to next argument
                matchRule &= ~SearchPattern.R_FULL_MATCH;
                continue;
            case Signature.C_EXTENDS: // EXTENDS pattern
                if (argumentBinding.isWildcard()) { // argument is a wildcard
                    WildcardBinding wildcardBinding = (WildcardBinding) argumentBinding;
                    // It's ok if wildcards are identical
                    if (wildcardBinding.boundKind == patternWildcardKind
                            && TypeBinding.equalsEquals(wildcardBinding.bound, patternBinding)) {
                        continue;
                    }
                    // Look for wildcard compatibility
                    switch (wildcardBinding.boundKind) {
                    case Wildcard.EXTENDS:
                        if (wildcardBinding.bound == null
                                || wildcardBinding.bound.isCompatibleWith(patternBinding)) {
                            // valid when arg extends a subclass of pattern
                            matchRule &= ~SearchPattern.R_FULL_MATCH;
                            continue;
                        }
                        break;
                    case Wildcard.SUPER:
                        break;
                    case Wildcard.UNBOUND:
                        matchRule &= ~SearchPattern.R_FULL_MATCH;
                        continue;
                    }
                } else if (argumentBinding.isCompatibleWith(patternBinding)) {
                    // valid when arg is a subclass of pattern
                    matchRule &= ~SearchPattern.R_FULL_MATCH;
                    continue;
                }
                break;
            case Signature.C_SUPER: // SUPER pattern
                if (argumentBinding.isWildcard()) { // argument is a wildcard
                    WildcardBinding wildcardBinding = (WildcardBinding) argumentBinding;
                    // It's ok if wildcards are identical
                    if (wildcardBinding.boundKind == patternWildcardKind
                            && TypeBinding.equalsEquals(wildcardBinding.bound, patternBinding)) {
                        continue;
                    }
                    // Look for wildcard compatibility
                    switch (wildcardBinding.boundKind) {
                    case Wildcard.EXTENDS:
                        break;
                    case Wildcard.SUPER:
                        if (wildcardBinding.bound == null
                                || patternBinding.isCompatibleWith(wildcardBinding.bound)) {
                            // valid only when arg super a superclass of pattern
                            matchRule &= ~SearchPattern.R_FULL_MATCH;
                            continue;
                        }
                        break;
                    case Wildcard.UNBOUND:
                        matchRule &= ~SearchPattern.R_FULL_MATCH;
                        continue;
                    }
                } else if (patternBinding.isCompatibleWith(argumentBinding)) {
                    // valid only when arg is a superclass of pattern
                    matchRule &= ~SearchPattern.R_FULL_MATCH;
                    continue;
                }
                break;
            default:
                if (argumentBinding.isWildcard()) {
                    WildcardBinding wildcardBinding = (WildcardBinding) argumentBinding;
                    switch (wildcardBinding.boundKind) {
                    case Wildcard.EXTENDS:
                        if (wildcardBinding.bound == null
                                || patternBinding.isCompatibleWith(wildcardBinding.bound)) {
                            // valid only when arg extends a superclass of pattern
                            matchRule &= ~SearchPattern.R_FULL_MATCH;
                            continue;
                        }
                        break;
                    case Wildcard.SUPER:
                        if (wildcardBinding.bound == null
                                || wildcardBinding.bound.isCompatibleWith(patternBinding)) {
                            // valid only when arg super a subclass of pattern
                            matchRule &= ~SearchPattern.R_FULL_MATCH;
                            continue;
                        }
                        break;
                    case Wildcard.UNBOUND:
                        matchRule &= ~SearchPattern.R_FULL_MATCH;
                        continue;
                    }
                } else if (TypeBinding.equalsEquals(argumentBinding, patternBinding))
                    // valid only when arg is equals to pattern
                    continue;
                break;
            }

            // Argument does not match => erasure match will be the only possible one
            this.match.setRule(SearchPattern.R_ERASURE_MATCH);
            return;
        }
    }

    // Set match rule
    this.match.setRule(matchRule);
}

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

License:Open Source License

/**
 * Initialize the type to create from the "playedBy" clause.
 * @param scope non-null/*www  . ja  v a  2  s .co m*/
 */
private void createAst(BlockScope scope) {
    if (this.isAstCreated)
        return; // already done.

    this.isAstCreated = true; // even if creation fails, don't try again.

    ReferenceBinding enclType;
    AbstractMethodDeclaration enclMethodDecl;
    ReferenceBinding baseclass = null;

    enclType = scope.enclosingSourceType();
    enclMethodDecl = (AbstractMethodDeclaration) scope.methodScope().referenceContext;

    if (enclType.isDirectRole())
        baseclass = ((MemberTypeBinding) enclType).baseclass();
    if (baseclass == null || !enclMethodDecl.isConstructor()) {
        scope.problemReporter().baseConstructorCallInWrongMethod(this, scope.methodScope().referenceContext);
        return;
    }
    ConstructorDeclaration enclCtor = (ConstructorDeclaration) enclMethodDecl;
    if (this.isExpression) {
        if (!isArgOfOtherCtor(enclCtor, scope))
            scope.problemReporter().baseConstructorExpressionOutsideCtorCall(this);
    } else {
        if (enclCtor.statements[0] != this)
            scope.problemReporter().baseConstructorCallIsNotFirst(this);
    }

    AstGenerator gen = new AstGenerator(this.sourceStart, this.sourceEnd);
    Expression allocation;
    if (this.enclosingInstance != null) {
        this.enclosingInstance = new PotentialLowerExpression(this.enclosingInstance,
                baseclass.enclosingType());
        // FIXME(SH): check baseclass.enclosingType();
    }

    if (baseclass.isDirectRole()) {
        // instead of new B() create:
        //       receiver._OT$createB():
        Expression receiver;
        if (RoleTypeBinding.isRoleWithExplicitAnchor(baseclass)) {
            RoleTypeBinding baseRole = (RoleTypeBinding) baseclass;
            ITeamAnchor anchor = baseRole._teamAnchor;
            ReferenceBinding startClass = anchor.getFirstDeclaringClass();
            char[][] tokens = anchor.tokens();
            if (startClass != null) {
                // relevant start class, create as receiver:
                //     EnclType.this.field1.
                TypeReference startReference = gen.typeReference(startClass);
                startReference.setBaseclassDecapsulation(DecapsulationState.ALLOWED);
                receiver = gen.qualifiedThisReference(startReference);
                for (int i = 0; i < tokens.length; i++) {
                    receiver = gen.fieldReference(receiver, tokens[i]);
                }
            } else {
                // the best name path defines the receiver:
                receiver = gen.qualifiedNameReference(tokens);
            }
        } else {
            if (this.enclosingInstance != null) {
                receiver = this.enclosingInstance;
            } else {
                if (TypeBinding.equalsEquals(baseclass.enclosingType(), enclType.enclosingType()))
                    receiver = gen.thisReference(); // creating a role of the same team as base instance??
                else
                    receiver = gen.qualifiedThisReference(gen.typeReference(baseclass.enclosingType()));
            }
        }
        char[] selector = CharOperation.concat(CREATOR_PREFIX_NAME, baseclass.sourceName());

        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.arguments = this.arguments;
        allocSend.accessId = -1; // request that MessageSend.resolveType() assigns a fresh accessId if decapsulation is detected
        allocation = allocSend;
    } else {
        AllocationExpression alloc = newAllocation(baseclass, gen);
        alloc.type.setBaseclassDecapsulation(DecapsulationState.ALLOWED); // report individually
        alloc.arguments = this.arguments;
        alloc.sourceStart = this.sourceStart;
        alloc.sourceEnd = this.sourceEnd;
        alloc.statementEnd = this.statementEnd;
        allocation = alloc;
    }
    this.arguments = null; // don't use any more.

    ExplicitConstructorCall selfcall = enclCtor.constructorCall;
    if (selfcall.isImplicitSuper() && enclType.superclass().isDirectRole()
            && enclType.superclass().baseclass() != null) {
        // implement 2.4.2(c):
        // transform "super(); base(args);" => "super(new MyBase(args)); nop;"
        enclCtor.constructorCall = genLiftCtorCall(allocation);
        enclCtor.statements[0] = new AstGenerator(this.sourceStart, this.sourceEnd).emptyStatement();
        // pretend we are not calling base() because we already call the lifting-ctor.
    } else if (this.isExpression) {
        // similar to above:
        // translate "super(base(args), ...);" as "super(new MyBase(args), ...);"
        this.expression = allocation; // and ignore the assignment flavor of this node.
    } else {
        // needed by ASTConverter:
        this.expression = allocation;
        if (!enclType.roleModel.hasBaseclassProblem() && !scope.referenceType().ignoreFurtherInvestigation) {

            MethodModel.setCallsBaseCtor(enclCtor);

            // really creating base here, need to register this base object
            RoleModel boundRootRoleModel = enclType.roleModel.getBoundRootRole();
            if (boundRootRoleModel == null)
                throw new InternalCompilerError(
                        "Unexpected: role has neither baseclassProblem nor boundRootRole"); //$NON-NLS-1$
            Statement[] regStats = Lifting.genRoleRegistrationStatements(scope, boundRootRoleModel, baseclass,
                    enclCtor, gen);
            int len = enclCtor.statements.length;
            Statement[] newStats = new Statement[len + regStats.length];
            newStats[0] = this;
            System.arraycopy(regStats, 0, newStats, 1, regStats.length);
            System.arraycopy(enclCtor.statements, 1, newStats, regStats.length + 1, len - 1);
            enclCtor.setStatements(newStats);
        }
    }
}

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);
        }//from   w  ww  .j  av a 2  s .  c  om
    }
    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.ast.CallinMappingDeclaration.java

License:Open Source License

/**
 * Check all parameters in methodSpec against the resolved role method.
 * Also record which parameters (including result) need translation (lifting/lowering).
 *
 * Pre: not called if parameter mappings are present.
 * @param methodSpec//from  w  ww  . j av a  2  s .  c om
 */
protected boolean internalCheckParametersCompatibility(MethodSpec methodSpec, TypeBinding[] roleParams,
        TypeBinding[] baseParams) {
    if (baseParams.length < roleParams.length) {
        this.scope.problemReporter().tooFewArgumentsInMethodMapping(this.roleMethodSpec, methodSpec,
                false/*callout*/);
        this.binding.tagBits |= TagBits.HasMappingIncompatibility;
        return false;
    } else {
        // before modifying the parameters array copy it:
        System.arraycopy(this.roleMethodSpec.parameters, 0,
                this.roleMethodSpec.parameters = new TypeBinding[roleParams.length], 0, roleParams.length);
        for (int j = 0; j < roleParams.length; j++) {
            TypeBinding baseParam = baseParams[j];
            TypeBinding roleParam = roleParams[j];
            if (baseParam.dimensions() != roleParam.dimensions()) {
                this.scope.problemReporter().incompatibleMappedArgument(baseParam, roleParam,
                        this.roleMethodSpec, j, /*callout*/false);
                this.binding.tagBits |= TagBits.HasMappingIncompatibility;
                continue; // no real type checking needed.
            }
            TypeBinding baseLeaf = baseParam.leafComponentType();
            TypeBinding roleLeaf = roleParam.leafComponentType();
            ASTNode location = (methodSpec.hasSignature) ? (ASTNode) methodSpec.arguments[j] : methodSpec;
            boolean compatibilityViaBaseAnchor = false;
            boolean hasReportedError = false;
            boolean isTypeVariable = false;
            try { // capture continue exits

                // unbound type variable matches everything:
                if (roleParam.isTypeVariable()) {
                    TypeVariableBinding typeVariableBinding = (TypeVariableBinding) roleParam;
                    if (typeVariableBinding.firstBound == null)
                        continue;
                    // use bound for type checking below, yet need not check two-way compatibility:
                    isTypeVariable = true;
                    roleLeaf = typeVariableBinding.firstBound.leafComponentType();
                }

                int dimensions = roleParam.dimensions();
                if (baseLeaf.isCompatibleWith(roleLeaf)) {
                    this.roleMethodSpec.parameters[j] = roleParam;
                    continue;
                }
                if (RoleTypeCreator.isCompatibleViaBaseAnchor(this.scope, baseLeaf, roleLeaf,
                        TokenNameBINDIN)) {
                    this.roleMethodSpec.parameters[j] = roleParam;
                    compatibilityViaBaseAnchor = true;
                    continue;
                }

                TypeBinding roleToLiftTo = null;
                if (isReplaceCallin()) {
                    TypeBinding roleSideType = roleLeaf;
                    if (roleSideType.isRole()) {
                        ReferenceBinding roleRef = (ReferenceBinding) roleSideType;
                        roleRef = (ReferenceBinding) TeamModel
                                .strengthenRoleType(this.scope.enclosingReceiverType(), roleRef);
                        if (TypeBinding.equalsEquals(roleRef.baseclass(), baseLeaf)) {
                            if (dimensions > 0) {
                                if (roleRef instanceof DependentTypeBinding)
                                    roleToLiftTo = ((DependentTypeBinding) roleRef).getArrayType(dimensions);
                                else
                                    roleToLiftTo = this.scope.createArrayType(roleRef, dimensions); // FIXME(SH): is this OK?
                            } else {
                                roleToLiftTo = roleRef;
                            }
                        }
                    }
                } else {
                    // this uses OTJLD 2.3.3(a) adaptation which is not reversible, ie., not usable for replace:
                    roleToLiftTo = TeamModel.getRoleToLiftTo(this.scope, baseParam, roleParam, false, location);
                }
                if (roleToLiftTo != null) {
                    // success by translation
                    methodSpec.argNeedsTranslation[j] = true;
                    this.roleMethodSpec.argNeedsTranslation[j] = true;
                    this.roleMethodSpec.parameters[j] = roleToLiftTo; // this applies to all bindings

                    // still need to check for ambiguity/abstract role:
                    ReferenceBinding enclosingTeam = this.scope.enclosingSourceType().enclosingType();
                    int iProblem = enclosingTeam.getTeamModel()
                            .canLiftingFail((ReferenceBinding) roleToLiftTo.leafComponentType());
                    if (iProblem > 0)
                        addRoleLiftingProblem((ReferenceBinding) roleToLiftTo.leafComponentType(), iProblem);

                    continue;
                }
                // check auto(un)boxing:
                if (this.scope.isBoxingCompatibleWith(baseLeaf, roleLeaf))
                    continue;

                if (roleParam instanceof ReferenceBinding) {
                    ReferenceBinding roleRef = (ReferenceBinding) roleParam;
                    if (roleRef.isRole() && roleRef.baseclass() != null) {
                        this.scope.problemReporter().typeMismatchErrorPotentialLift(location, baseParam,
                                roleParam, roleRef.baseclass());
                        hasReportedError = true;
                        continue;
                    }
                }
                // no compatibility detected:
                this.scope.problemReporter().incompatibleMappedArgument(baseParam, roleParam,
                        this.roleMethodSpec, j, /*callout*/false);
                hasReportedError = true;
            } finally {
                if (hasReportedError)
                    this.binding.tagBits |= TagBits.HasMappingIncompatibility;
                // regardless of continue, check this last because it is the least precise message:
                if (!hasReportedError && baseLeaf.isCompatibleWith(roleLeaf)) {
                    if (isReplaceCallin() && !isTypeVariable) {
                        boolean twowayCompatible = compatibilityViaBaseAnchor
                                ? RoleTypeCreator.isCompatibleViaBaseAnchor(this.scope, baseLeaf, roleLeaf,
                                        TokenNameBINDOUT)
                                : roleLeaf.isCompatibleWith(baseLeaf);
                        if (!twowayCompatible) {
                            // requires two-way compatibility (see additional paragraph in 4.5(d))
                            this.scope.problemReporter().typesNotTwowayCompatibleInReplace(baseParam, roleParam,
                                    location, j);
                        }
                    }
                }
            }
        }
    }
    return true; // unused in the callin case
}

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

License:Open Source License

private boolean typeUsesTypeVariable(TypeBinding type, TypeBinding variable) {
    if (TypeBinding.equalsEquals(type.leafComponentType(), variable))
        return true;
    for (TypeVariableBinding t : type.typeVariables())
        if (typeUsesTypeVariable(t, variable))
            return true;
    if (type.isTypeVariable()) {
        if (typeUsesTypeVariable(((ReferenceBinding) type).superclass(), variable))
            return true;
        for (TypeBinding superIfc : ((ReferenceBinding) type).superInterfaces())
            if (typeUsesTypeVariable(superIfc, variable))
                return true;
    }//from w  w  w  . j a va2  s.c  o  m
    return false;
}

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

License:Open Source License

/** is inner contained (via reverse of enclosingType) in outer? */
private boolean contains(ReferenceBinding outer, ReferenceBinding inner) {
    ReferenceBinding current = inner.enclosingType();
    while (current != null) {
        if (TypeBinding.equalsEquals(current, outer))
            return true;
        current = current.enclosingType();
    }//from  w  ww . j  a  va 2s. c  o  m
    return false;
}

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

License:Open Source License

public static TypeBinding mapClass(ReferenceBinding srcTeamBinding, TypeBinding typeBinding,
        ReferenceBinding dstTeam) {/* www  .  j  a v  a  2 s.  co  m*/
    boolean isArrayBinding = typeBinding instanceof ArrayBinding;
    int dimension = 0;
    TypeBinding originalType = typeBinding;
    if (isArrayBinding) {
        ArrayBinding formerType = (ArrayBinding) typeBinding;
        typeBinding = formerType.leafComponentType();
        dimension = formerType.dimensions;

        if (typeBinding.isBaseType())
            return formerType; // no need to map array of basetype
    }
    ReferenceBinding refTypeBinding = (ReferenceBinding) typeBinding;
    // if Binding points at Role-Field of Superteamclass, then mapping must be done
    if (isMappableClass(refTypeBinding)) {
        refTypeBinding = (ReferenceBinding) refTypeBinding.erasure();
        ReferenceBinding refTeamBinding = getTeam(refTypeBinding);
        if (refTeamBinding != null) {
            if (srcTeamBinding != null) {
                srcTeamBinding = (ReferenceBinding) srcTeamBinding.erasure();
                TypeBinding newBinding = null;
                ReferenceBinding currentSrcTeam = srcTeamBinding;
                ReferenceBinding currentDstTeam = dstTeam;
                while (currentSrcTeam != null && currentDstTeam != null) {
                    if (TypeBinding.equalsEquals(refTeamBinding, currentSrcTeam)) {
                        // mapping the enclosing team which is nested in an outer team?
                        if (TypeBinding.equalsEquals(refTypeBinding, refTeamBinding) && refTypeBinding.isRole())
                            newBinding = currentDstTeam;
                        else
                            newBinding = searchRoleClass(refTypeBinding, currentDstTeam);
                        break;
                    }
                    // try dependent refinement of base classes:
                    ReferenceBinding srcBase = currentSrcTeam.baseclass();
                    if (srcBase != null && (srcBase.isTeam() || srcBase.isRole())) {
                        if (TypeBinding.equalsEquals(srcBase, refTypeBinding))
                            newBinding = currentDstTeam.baseclass();
                        else
                            newBinding = searchRoleClass(refTypeBinding, currentDstTeam.baseclass());
                        if (newBinding != null)
                            break;
                    }
                    // the common team to start searching might be an enclosing:
                    if (!currentSrcTeam.isRole())
                        break;
                    currentSrcTeam = currentSrcTeam.enclosingType();
                    currentDstTeam = currentDstTeam.enclosingType();
                }
                if (newBinding != null) {
                    if (isArrayBinding) {
                        // have no scope so can't use Scope.createArray(),
                        // which otherwise should be used throughout.
                        try {
                            newBinding = new ArrayBinding(newBinding, dimension, Config.getLookupEnvironment());
                        } catch (NotConfiguredException e) {
                            e.logWarning("Cannot create array binding"); //$NON-NLS-1$
                        }
                    }
                    return newBinding;
                }
            }
        }
    }
    return originalType;
}

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

License:Open Source License

/**
 * This method realizes the logic of the mapping for fields.
 * @param srcMethod        where to copy from
 * @param refFieldBinding  what to copy/remap
 * @param dstTeam          where to copy to
 * @return destination field//from  w w  w . j a  va  2 s.  com
 */
public static FieldBinding mapField(MethodBinding srcMethod, FieldBinding refFieldBinding,
        ReferenceBinding dstTeam) {
    // if Binding points at Role-Field of Superteamclass, then mapping must be done
    if (dstTeam != null) {
        if (isMappableField(refFieldBinding)) {
            if (refFieldBinding.isSynthetic()) {
                RoleModel role = ((ReferenceBinding) mapClass(srcMethod, refFieldBinding.declaringClass,
                        dstTeam)).roleModel;
                if (role != null) {
                    FieldBinding dstField = role.mapSyntheticField(refFieldBinding);
                    if (dstField != null)
                        return dstField;
                }
            }
            ReferenceBinding refTeamBinding = getTeam(refFieldBinding);
            if (refTeamBinding != null) {
                ReferenceBinding srcTeamBinding = getTeam(srcMethod);
                if (srcTeamBinding != null) {
                    if (TypeBinding.equalsEquals(refTeamBinding, srcTeamBinding)) {
                        FieldBinding newBinding = searchRoleField(refFieldBinding, dstTeam);
                        if (newBinding != null && TypeBinding.notEquals(newBinding.declaringClass, dstTeam)
                                && !TeamModel.isTeamContainingRole(dstTeam, newBinding.declaringClass)) {
                            // field is declared neither in dstTeam nor one of its roles.
                            // find the class, that corresponds to the field's declaring class:
                            ReferenceBinding updatedClass = (ReferenceBinding) mapClass(srcMethod,
                                    newBinding.declaringClass, dstTeam);
                            // update field binding to new declaring class?
                            if (TypeBinding.notEquals(newBinding.declaringClass, updatedClass))
                                newBinding = new FieldBinding(newBinding, updatedClass);
                        }
                        return newBinding;
                    }
                }
            }
        }
    }
    return refFieldBinding;
}

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

License:Open Source License

/**
 * Is given method a super-call to the constructor of an __OT__Confined role?
 */// w  w w. java  2  s .  com
private static boolean isConfinedSuperCtor(MethodBinding srcMethod, MethodBinding refMethodBinding) {
    // constructor?
    if (!refMethodBinding.isConstructor())
        return false;
    // of class __OT__Confined?
    if (!CharOperation.equals(refMethodBinding.declaringClass.compoundName,
            IOTConstants.ORG_OBJECTTEAMS_TEAM_OTCONFINED))
        return false;
    // is it the superclass of the current src class?
    if (TypeBinding.equalsEquals(refMethodBinding.declaringClass, srcMethod.declaringClass.superclass()))
        return true;
    // current src class may have no super class which is OK if it is Team.__OT__Confined
    return srcMethod.declaringClass.superclass() == null && CharOperation
            .equals(IOTConstants.ORG_OBJECTTEAMS_TEAM_OTCONFINED, refMethodBinding.declaringClass.compoundName);
}