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:org.eclipse.objectteams.otdt.internal.core.compiler.lookup.TeamAnchor.java

License:Open Source License

public boolean hasSameTypeAs(ITeamAnchor other) {
    return TypeBinding.equalsEquals(leafReferenceType(), ((TeamAnchor) other).leafReferenceType());
}

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

License:Open Source License

public static boolean requireWeakening(DependentTypeBinding strongType, ReferenceBinding weakType) {
    if (TypeBinding.equalsEquals(strongType, weakType))
        return false;
    if (strongType instanceof WeakenedTypeBinding)
        return TypeBinding.equalsEquals(((WeakenedTypeBinding) strongType).weakenedType, weakType);
    return false;
}

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.
 *
 *///from  ww w.  j  av a 2  s . com
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;
}

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

License:Open Source License

/**
 * Implements inherited abstract method.
 *
 * Note that as a side effect, this method modifies methodMapping.mappings!
 *
 * @param methodMapping      lookup method spec and parameter mapping here
 * @param wrapperDeclaration use args of this method if no mapping is involved
 * @param implParameters     parameters of the implemented method to invoke (possibly enhanced)
 * @param idx                argument position on the target side
 * @param hasResultArgument  as a 'result' argument been prepended to the wrapper args?
 * @param sourceMethodSpec   this signature defines the provided args
 * @return the expression to pass to the implemented method.
 *///  w  ww  .jav a  2s .  c  om
Expression getArgument(AbstractMethodMappingDeclaration methodMapping, MethodDeclaration wrapperDeclaration,
        TypeBinding[] implParameters, int idx, boolean hasResultArgument, final MethodSpec sourceMethodSpec) {
    final MethodSpec implementationMethodSpec = methodMapping.getImplementationMethodSpec();

    Expression mappedArgExpr = null;
    int pos = -1;
    char[] targetArgName = null;

    int generatedArgsLen = methodMapping.isReplaceCallin() ? getMethodSignatureEnhancer().ENHANCING_ARG_LEN : 0;
    final int srcIdx = idx - generatedArgsLen; // index into source-code signatures.
    int wrapperPrefixLen = hasResultArgument ? 2 : 1; // skip prepended base_arg, and possibly result arg

    if (methodMapping.mappings == null // have no parameter mapping
            || methodMapping.mappings.length == 0 || idx < generatedArgsLen) // don't map generated args.
    {
        targetArgName = idx + wrapperPrefixLen < wrapperDeclaration.arguments.length
                ? wrapperDeclaration.arguments[idx + wrapperPrefixLen].name
                : CharOperation.concat(IOTConstants.OT_DOLLAR_NAME, "missingArg".toCharArray()); //$NON-NLS-1$
        MethodSpec rmSpec = methodMapping.roleMethodSpec;
        mappedArgExpr = genSimpleArgExpr(targetArgName, rmSpec);
        if (idx >= generatedArgsLen)
            mappedArgExpr.resolve(wrapperDeclaration.scope); // resolved type needed in liftCall().
    } else {
        targetArgName = implementationMethodSpec.arguments[srcIdx].name;
        // retrieve info collected during analyzeParameterMappings:
        Pair<Expression, Integer> mapper = methodMapping.mappingExpressions[srcIdx];
        mappedArgExpr = mapper.first;
        if (mapper.second != null)
            pos = mapper.second.intValue();
    }
    if (mappedArgExpr != null) {
        SourceTypeBinding roleType = methodMapping.scope.enclosingSourceType();

        if (idx >= implParameters.length) // CLOVER: never true in jacks suite
            return mappedArgExpr; // arg is invisible to receiver, don't lift
        TypeBinding expectedType = implParameters[idx];

        // arg might have been weakened:
        if (expectedType.isRole()
                && TypeBinding.notEquals(expectedType.enclosingType(), roleType.enclosingType()))
            expectedType = TeamModel.strengthenRoleType(roleType, expectedType);

        AstGenerator gen = new AstGenerator(mappedArgExpr.sourceStart, mappedArgExpr.sourceEnd);
        Expression receiver = null;
        TypeBinding expectedLeaf = expectedType.leafComponentType();
        if (RoleTypeBinding.isRoleWithoutExplicitAnchor(expectedLeaf) && TypeBinding
                .equalsEquals(roleType.getRealClass(), ((ReferenceBinding) expectedLeaf).enclosingType())) {
            // expectedType is a role of the current role(=team),
            // use the role as the receiver for the lift call:
            receiver = gen.singleNameReference(ROLE_VAR_NAME);
        }
        if (sourceMethodSpec.hasSignature) {
            if (sourceMethodSpec.argNeedsTranslation(srcIdx)) {
                mappedArgExpr.tagReportedBaseclassDecapsulation();
                return Lifting.liftCall(methodMapping.scope,
                        receiver != null ? receiver : gen.qualifiedThisReference(expectedLeaf.enclosingType()),
                        mappedArgExpr, sourceMethodSpec.resolvedParameters()[srcIdx], expectedType,
                        methodMapping.isReplaceCallin()/*needLowering*/);
            }
            if (methodMapping.mappings == null)
                // we have signatures and no parameter mapping.
                // if no need for translation has been recorded, it IS not needed.
                return mappedArgExpr;
        }
        // don't know yet whether lifting is actually needed (=>potentially)
        Expression liftExpr = gen.potentialLift(receiver, mappedArgExpr, expectedType,
                methodMapping.isReplaceCallin()); // reversible?

        // if param mappings are present, connect the PLE to the method spec for propagating translation flag
        // (CallinMethodMappingsAttribute needs to know whether lifting is actually needed.)
        if (methodMapping.mappings != null && liftExpr instanceof PotentialLiftExpression) {
            final int srcPos = pos;
            ((PotentialLiftExpression) liftExpr).onLiftingRequired(new Runnable() {
                public void run() {
                    if (srcPos != -1)
                        sourceMethodSpec.argNeedsTranslation[srcPos] = true;
                    implementationMethodSpec.argNeedsTranslation[srcIdx] = true;
                }
            });
        }

        return liftExpr;
    }
    wrapperDeclaration.scope.problemReporter().unmappedParameter(targetArgName, implementationMethodSpec,
            methodMapping.isCallout());
    return null;
}

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

License:Open Source License

Expression getArgument(CallinMappingDeclaration methodMapping, MethodDeclaration wrapperDeclaration,
        TypeBinding[] implParameters, int idx, final MethodSpec sourceMethodSpec) {
    final MethodSpec implementationMethodSpec = methodMapping.getImplementationMethodSpec();

    Expression mappedArgExpr = null;
    int pos = -1;
    char[] targetArgName = null;

    int generatedArgsLen = methodMapping.isReplaceCallin()
            ? MethodSignatureEnhancer.getEnhancingArgLen(WeavingScheme.OTDRE)
            : 0;//from w  w  w . j  ava  2 s. c  o m
    final int srcIdx = idx - generatedArgsLen; // index into source-code signatures.

    targetArgName = implementationMethodSpec.arguments[srcIdx].name;
    // retrieve info collected during analyzeParameterMappings:
    Pair<Expression, Integer> mapper = methodMapping.mappingExpressions[srcIdx];
    mappedArgExpr = mapper.first;
    if (mapper.second != null)
        pos = mapper.second.intValue();

    if (mappedArgExpr != null) {
        if (methodMapping.baseMethodSpecs.length > 1) // multi-mappings need to copy mapped argument expressions:
            mappedArgExpr = copyExpression(mappedArgExpr, methodMapping.scope,
                    methodMapping.compilationResult.getCompilationUnit());

        SourceTypeBinding roleType = methodMapping.scope.enclosingSourceType();

        if (idx >= implParameters.length) // CLOVER: never true in jacks suite
            return mappedArgExpr; // arg is invisible to receiver, don't lift
        TypeBinding expectedType = implParameters[idx];

        // arg might have been weakened:
        if (expectedType.isRole()
                && TypeBinding.notEquals(expectedType.enclosingType(), roleType.enclosingType()))
            expectedType = TeamModel.strengthenRoleType(roleType, expectedType);

        AstGenerator gen = new AstGenerator(mappedArgExpr.sourceStart, mappedArgExpr.sourceEnd);
        Expression receiver = null;
        if (RoleTypeBinding.isRoleWithoutExplicitAnchor(expectedType) && TypeBinding
                .equalsEquals(roleType.getRealClass(), ((ReferenceBinding) expectedType).enclosingType())) {
            // expectedType is a role of the current role(=team),
            // use the role as the receiver for the lift call:
            receiver = gen.singleNameReference(ROLE_VAR_NAME);
        }
        if (sourceMethodSpec.hasSignature) {
            if (sourceMethodSpec.argNeedsTranslation(srcIdx)) {
                mappedArgExpr.tagReportedBaseclassDecapsulation();
                return Lifting.liftCall(methodMapping.scope,
                        receiver != null ? receiver : ThisReference.implicitThis(), mappedArgExpr,
                        sourceMethodSpec.resolvedParameters()[srcIdx], expectedType,
                        methodMapping.isReplaceCallin()/*needLowering*/);
            }
            if (methodMapping.mappings == null)
                // we have signatures and no parameter mapping.
                // if no need for translation has been recorded, it IS not needed.
                return mappedArgExpr;
        }
        // don't know yet whether lifting is actually needed (=>potentially)
        Expression liftExpr = gen.potentialLift(receiver, mappedArgExpr, expectedType,
                methodMapping.isReplaceCallin()); // reversible?

        // if param mappings are present, connect the PLE to the method spec for propagating translation flag
        // (CallinMethodMappingsAttribute needs to know whether lifting is actually needed.)
        if (methodMapping.mappings != null && pos != -1 && liftExpr instanceof PotentialLiftExpression) {
            final int srcPos = pos;
            ((PotentialLiftExpression) liftExpr).onLiftingRequired(new Runnable() {
                public void run() {
                    sourceMethodSpec.argNeedsTranslation[srcPos] = true;
                    implementationMethodSpec.argNeedsTranslation[srcIdx] = true;
                }
            });
        }

        return liftExpr;
    }
    wrapperDeclaration.scope.problemReporter().unmappedParameter(targetArgName, implementationMethodSpec,
            methodMapping.isCallout());
    return null;
}

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

License:Open Source License

private void generateDispatchMethod(char[] methodName, final boolean isReplace, final boolean isAfter,
        final List<CallinMappingDeclaration> callinDecls, final TeamModel aTeam) {
    // FIXME(SH): once we know that Team has empty implementations (and checked cases involving team inheritance)
    // we probably want to avoid generating empty methods here.
    final TypeDeclaration teamDecl = aTeam.getAst();
    if (teamDecl == null)
        return;/* ww w  .j  ava 2 s . c  o m*/

    final AstGenerator gen = new AstGenerator(teamDecl);
    gen.replaceableEnclosingClass = teamDecl.binding;

    // public void _OT$callBefore   (IBoundBase2 base,                      int boundMethodId, int callinId,    Object[] args)
    // public void _OT$callAfter   (IBoundBase2 base,                      int boundMethodId, int callinId,    Object[] args, Object result)
    // public void _OT$callReplace   (IBoundBase2 base, Team[] teams, int index,    int boundMethodId, int[] callinIds, Object[] args)
    int length = 4;
    if (isReplace)
        length = 6;
    else if (isAfter)
        length = 5;
    Argument[] arguments = new Argument[length];
    int a = 0;
    arguments[a++] = gen.argument(_BASE$, gen.qualifiedTypeReference(IOTConstants.ORG_OBJECTTEAMS_IBOUNDBASE2));
    if (isReplace)
        arguments[a++] = gen.argument(TEAMS,
                gen.qualifiedArrayTypeReference(IOTConstants.ORG_OBJECTTEAMS_ITEAM, 1));
    if (isReplace)
        arguments[a++] = gen.argument(INDEX, gen.typeReference(TypeBinding.INT));
    arguments[a++] = isReplace ? gen.argument(CALLIN_ID, gen.createArrayTypeReference(TypeBinding.INT, 1))
            : gen.argument(CALLIN_ID, gen.typeReference(TypeBinding.INT));
    arguments[a++] = gen.argument(BOUND_METHOD_ID, gen.typeReference(TypeBinding.INT));
    arguments[a++] = gen.argument(ARGUMENTS,
            gen.qualifiedArrayTypeReference(TypeConstants.JAVA_LANG_OBJECT, 1));
    if (isAfter)
        arguments[a++] = gen.argument(_OT_RESULT, gen.qualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT));

    TypeReference returnTypeRef = isReplace ? gen.qualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT)
            : gen.typeReference(TypeBinding.VOID);

    final MethodDeclaration callMethod = gen.method(teamDecl.compilationResult, AccPublic, returnTypeRef,
            methodName, arguments);
    callMethod.isMappingWrapper = AbstractMethodDeclaration.WrapperKind.CALLIN;

    AstEdit.addMethod(teamDecl, callMethod);

    MethodModel.addCallinFlag(callMethod, IOTConstants.CALLIN_FLAG_WRAPPER);
    callMethod.model._declaringMappings = callinDecls;

    MethodModel.getModel(callMethod).setStatementsGenerator(new AbstractStatementsGenerator() {

        protected boolean generateStatements(AbstractMethodDeclaration methodDecl) {

            // into head of tryStats we generate local vars to be shared by case statements:
            List<Statement> tryStats = new ArrayList<Statement>();

            SwitchStatement switchStat = new SwitchStatement();
            switchStat.expression = isReplace
                    ? gen.arrayReference(gen.singleNameReference(CALLIN_ID), gen.singleNameReference(INDEX)) // switch(callinId[index]) {  ...
                    : gen.singleNameReference(CALLIN_ID); // switch(callinId) { ...

            // statements for the body of the switchStatement:
            List<Statement> statements = new ArrayList<Statement>();

            int callinIdCount = teamDecl.getTeamModel().getCallinIdCount();
            // callinIds not handled here will be handled using a super-call.
            boolean[] handledCallinIds = new boolean[callinIdCount];
            // do we need to catch LiftingFailedException?
            boolean canLiftingFail = false;
            // one case block per callin mapping:
            for (CallinMappingDeclaration callinDecl : callinDecls) {
                if (callinDecl.ignoreFurtherInvestigation
                        || RoleModel.isRoleWithBaseProblem(callinDecl.scope.referenceType()))
                    continue;
                if (!callinDecl.hasParsedParamMappings) // during reconcile we may not be interested in this level of detail (e.g., of a role file)
                    continue;

                gen.retargetFrom(callinDecl);

                // one case label per bound base method:
                for (MethodSpec baseSpec : callinDecl.baseMethodSpecs) {
                    statements.add(gen.caseStatement(gen.intLiteral(baseSpec.callinID))); // case <baseMethod.callinId>: 
                    handledCallinIds[baseSpec.callinID] = true;

                    PredicateGenerator predGen = new PredicateGenerator(callinDecl.binding._declaringRoleClass,
                            callinDecl.isReplaceCallin());

                    TypeBinding baseReturn = baseSpec.resolvedType();
                    boolean isStaticRoleMethod = callinDecl.getRoleMethod().isStatic();
                    ReferenceBinding roleType = callinDecl.scope.enclosingSourceType();
                    if (roleType.isGenericType()) // cannot handle generic role in this generated code
                        roleType = (ReferenceBinding) callinDecl.scope.environment().convertToRawType(roleType,
                                false);
                    MethodBinding roleMethodBinding = callinDecl.getRoleMethod();

                    boolean needLiftedRoleVar = !isStaticRoleMethod
                            && roleType.isCompatibleWith(roleMethodBinding.declaringClass);

                    List<Statement> blockStatements = new ArrayList<Statement>();

                    // do we need to expose _OT$result as result?
                    char[] resultName = null;
                    if (callinDecl.callinModifier == TerminalTokens.TokenNameafter
                            && (callinDecl.mappings != null || callinDecl.predicate != null)
                            && baseReturn != TypeBinding.VOID) {
                        resultName = RESULT;
                        callinDecl.resultVar = gen.localBaseVariable(RESULT, baseReturn, //   BaseReturnType result = (BaseReturnType)_OT$result; 
                                gen.createCastOrUnboxing(gen.singleNameReference(_OT_RESULT), baseReturn,
                                        true/*baseAccess*/));
                        blockStatements.add(callinDecl.resultVar);
                    }
                    // expose casted _base$ as "base":
                    blockStatements.add(gen.localVariable(IOTConstants.BASE,
                            gen.alienScopeTypeReference(gen.baseTypeReference(roleType.baseclass()),
                                    callinDecl.scope),
                            gen.castExpression(gen.baseNameReference(_BASE$),
                                    gen.alienScopeTypeReference(gen.baseTypeReference(roleType.baseclass()),
                                            callinDecl.scope),
                                    CastExpression.RAW)));

                    // -------------- base predicate check -------
                    boolean hasBasePredicate = false;
                    for (MethodSpec baseMethodSpec : callinDecl.baseMethodSpecs) { // FIXME: check this inner loop, outer already loops over baseMethods!!
                        char[] resultName2 = null;
                        if (callinDecl.callinModifier == TerminalTokens.TokenNameafter
                                && baseMethodSpec.resolvedType() != TypeBinding.VOID) {
                            resultName2 = IOTConstants.RESULT;
                        }
                        // FIXME(SH): only call predidate for the current base method (from BoundMethodID?)
                        Statement predicateCheck = predGen.createBasePredicateCheck(callinDecl, baseMethodSpec,
                                resultName2, gen);
                        if (predicateCheck != null) {
                            blockStatements.add(predicateCheck); //   if (!base$when(baseArg,...)) throw new LiftingVetoException();
                            hasBasePredicate = true;
                        }
                    }
                    Expression resetFlag = CallinImplementor.setExecutingCallin(roleType.roleModel,
                            blockStatements); //   boolean _OT$oldIsExecutingCallin = _OT$setExecutingCallin(true);

                    // ----------- receiver for role method call: -----------
                    Expression receiver;
                    char[] roleVar = null;
                    if (!isStaticRoleMethod) {
                        if (needLiftedRoleVar) {

                            canLiftingFail |= checkLiftingProblem(teamDecl, callinDecl, roleType);

                            roleVar = (LOCAL_ROLE + statements.size()).toCharArray();
                            TypeReference roleTypeReference = gen
                                    .roleTypeReference(teamDecl.getTeamModel().getTThis(), roleType, 0);
                            blockStatements.add(gen.localVariable(roleVar, //   RoleType local$n = this._OT$liftToRoleType((BaseType)base);
                                    gen.alienScopeTypeReference(roleTypeReference, callinDecl.scope),
                                    ClassFileConstants.AccFinal,
                                    Lifting.liftCall(callMethod.scope, gen.thisReference(),
                                            gen.baseNameReference(IOTConstants.BASE), callMethod.scope
                                                    .getType(IOTConstants.ORG_OBJECTTEAMS_IBOUNDBASE2, 3),
                                            roleType, false, gen)));
                            receiver = gen.thislikeNameReference(roleVar);
                            // private receiver needs to be casted to the class.
                        } else {
                            // method is from role's enclosing team
                            receiver = gen.qualifiedThisReference(TeamModel
                                    .strengthenEnclosing(teamDecl.binding, roleMethodBinding.declaringClass));
                        }
                    } else {
                        receiver = gen
                                .singleNameReference(callinDecl.getRoleMethod().declaringClass.sourceName());
                    }

                    int baseArgOffset = 0;
                    if (baseSpec.isCallin())
                        baseArgOffset += MethodSignatureEnhancer.getEnhancingArgLen(WeavingScheme.OTDRE);
                    if (baseSpec.isStatic() && baseSpec.getDeclaringClass().isRole())
                        baseArgOffset += 2;
                    // unpack arguments to be used by parameter mappings and base predicate:
                    // ArgTypeN argn = args[n]
                    if (callinDecl.mappings != null || (hasBasePredicate && baseSpec.arguments != null)) {
                        TypeBinding[] baseParams = baseSpec.resolvedParameters();
                        for (int i = 0; i < baseSpec.arguments.length; i++) { //   BaseType baseArg = castAndOrUnbox(arguments[n]);
                            Argument baseArg = baseSpec.arguments[i];
                            Expression rawArg = gen.arrayReference(gen.singleNameReference(ARGUMENTS),
                                    i + baseArgOffset);
                            Expression init = rawArg;
                            if (!baseParams[i].isTypeVariable())
                                init = gen.createCastOrUnboxing(rawArg, baseParams[i], callinDecl.scope);
                            LocalDeclaration baseArgLocal = gen.localVariable(baseArg.name,
                                    gen.alienScopeTypeReference(baseArg.type, callinDecl.scope), init);
                            baseArgLocal.modifiers |= (baseArg.modifiers & ClassFileConstants.AccFinal);
                            if (hasBasePredicate) {
                                // add to front so it is already available for the base predicate check:
                                blockStatements.add(i, baseArgLocal);
                            } else {
                                // otherwise give it a chance for expressions/types that depend on the role instance
                                baseArgLocal.initialization = new PotentialRoleReceiverExpression(init, roleVar,
                                        gen.typeReference(roleType));
                                blockStatements.add(baseArgLocal);
                            }
                        }
                    }

                    // -- assemble arguments:
                    TypeBinding[] roleParams = callinDecl.roleMethodSpec.resolvedParameters();
                    Expression[] callArgs = new Expression[roleParams.length
                            + (isReplace ? MethodSignatureEnhancer.getEnhancingArgLen(WeavingScheme.OTDRE)
                                    : 0)];
                    int idx = 0;
                    if (isReplace)
                        for (char[] argName : REPLACE_ARG_NAMES)
                            callArgs[idx++] = gen.singleNameReference(argName); //    prepare: base, teams, boundMethodId, callinIds, index, arguments ...

                    // prepare parameter mappings:
                    callinDecl.traverse(new ReplaceResultReferenceVisitor(callinDecl),
                            callinDecl.scope.classScope());

                    boolean hasArgError = false;
                    for (int i = 0; i < roleParams.length; i++) {
                        Expression arg;
                        TypeBinding roleParam = roleParams[i];
                        if (roleParam.isTypeVariable()) {
                            TypeVariableBinding tvb = (TypeVariableBinding) roleParam;
                            if (tvb.declaringElement instanceof MethodBinding) {
                                if (TypeBinding.equalsEquals(
                                        ((MethodBinding) tvb.declaringElement).declaringClass, roleType))
                                    // don't use type variable of target method, see test4140_callinReplaceCompatibility10s()
                                    roleParam = roleParam.erasure();
                            }
                        }
                        TypeReference localTypeRef = null;
                        if (callinDecl.mappings == null) {
                            // ------------ unmapped arguments --------------
                            arg = gen.arrayReference(gen.singleNameReference(ARGUMENTS), i + baseArgOffset); //    prepare: somePreparation(arguments[i])
                            TypeBinding baseArgType = baseSpec.resolvedParameters()[i];
                            if (roleParam.isBaseType()) {
                                // this includes intermediate cast to boxed type:
                                arg = gen.createUnboxing(arg, (BaseTypeBinding) roleParam);
                            } else if (baseArgType.isBaseType()) {
                                // Object -> BoxingType
                                arg = gen.castExpression(arg,
                                        gen.qualifiedTypeReference(
                                                AstGenerator.boxTypeName((BaseTypeBinding) baseArgType)),
                                        CastExpression.RAW);
                            } else {
                                // Object -> MyBaseClass
                                ReferenceBinding baseclass = roleType.baseclass();
                                if (baseclass instanceof DependentTypeBinding
                                        && baseArgType instanceof ReferenceBinding)
                                    baseArgType = RoleTypeCreator.maybeInstantiateFromPlayedBy(callinDecl.scope,
                                            (ReferenceBinding) baseArgType);
                                arg = gen.castExpression(arg,
                                        gen.alienScopeTypeReference(gen.typeReference(baseArgType),
                                                callinDecl.scope),
                                        CastExpression.DO_WRAP);
                                if (!roleParam.leafComponentType().isBaseType() && PotentialLiftExpression
                                        .isLiftingRequired(callinDecl.scope, roleParam, baseArgType, arg)) {
                                    // lift?(MyBaseClass)
                                    Reference liftReceiver = null; // default: let gen find the team
                                    if (roleType.isTeam()
                                            && TypeBinding.equalsEquals(roleParam.enclosingType(), roleType))
                                        liftReceiver = gen.singleNameReference(roleVar); // lift to inner role
                                    arg = gen.potentialLift(liftReceiver, arg, roleParam,
                                            isReplace/*reversible*/);
                                    localTypeRef = gen.typeReference(roleParam);
                                    canLiftingFail |= checkLiftingProblem(teamDecl, callinDecl,
                                            (ReferenceBinding) roleParam.leafComponentType());
                                }
                            }
                            if (localTypeRef == null)
                                localTypeRef = gen.baseclassReference(baseArgType); // unless lifting was required above
                        } else {
                            // ------------ mapped arguments --------------
                            if (roleParam.isTypeVariable()
                                    && ((TypeVariableBinding) roleParam).declaringElement instanceof CallinCalloutBinding)
                                localTypeRef = gen.typeReference(roleParam.erasure()); // cannot explicitly mention this TVB
                            else
                                localTypeRef = gen.typeReference(roleParam);

                            arg = getArgument(callinDecl, //    prepare:  <mappedArg<n>>
                                    (MethodDeclaration) methodDecl, callinDecl.getRoleMethod().parameters,
                                    i + idx, baseSpec);
                            if (arg == null) {
                                hasArgError = true;
                                continue; // keep going to find problems with other args, too.
                            }
                            if (Lifting.isLiftToMethodCall(arg))
                                canLiftingFail |= checkLiftingProblem(teamDecl, callinDecl, roleType);
                            boolean isBaseReference = arg instanceof SingleNameReference && CharOperation
                                    .equals(((SingleNameReference) arg).token, IOTConstants.BASE);
                            if (needLiftedRoleVar)
                                arg = new PotentialRoleReceiverExpression(arg, roleVar,
                                        gen.typeReference(roleType.getRealClass()));
                            // mapped expression may require casting: "base" reference has static type IBoundBase2
                            if (isBaseReference)
                                arg = gen.castExpression(arg, gen.typeReference(roleParam), CastExpression.RAW);
                        }
                        char[] localName = (OT_LOCAL + i).toCharArray(); //    RoleParamType _OT$local$n = preparedArg<n>;
                        blockStatements.add(gen.localVariable(localName,
                                gen.alienScopeTypeReference(localTypeRef, callinDecl.scope), arg));
                        callArgs[i + idx] = gen.singleNameReference(localName); //    prepare: ... _OT$local$ ...

                    }
                    if (hasArgError)
                        continue;

                    // -- role side predicate:
                    Expression[] predicateArgs = isReplace
                            ? MethodSignatureEnhancer.retrenchBasecallArguments(callArgs, true,
                                    WeavingScheme.OTDRE)
                            : callArgs;
                    predicateArgs = maybeAddResultReference(callinDecl, predicateArgs, resultName, gen);
                    Statement rolePredicateCheck = predGen.createPredicateCheck( //    if (!when(callArgs)) throw new LiftingVetoException();
                            callinDecl, callinDecl.scope.referenceType(), receiver, predicateArgs, callArgs,
                            gen);
                    if (rolePredicateCheck != null)
                        // predicateCheck(_OT$role)
                        blockStatements.add(rolePredicateCheck);

                    // -- assemble the method call:                                                //    local$n.roleMethod((ArgType0)args[0], .. (ArgTypeN)args[n]);
                    boolean lhsResolvesToTeamMethod = TypeBinding
                            .equalsEquals(callinDecl.getRoleMethod().declaringClass, roleType.enclosingType()); // TODO(SH): more levels
                    MessageSend roleMethodCall = (callinDecl.getRoleMethod().isPrivate()
                            && !lhsResolvesToTeamMethod)
                                    ? new PrivateRoleMethodCall(receiver, callinDecl.roleMethodSpec.selector,
                                            callArgs, false/*c-t-f*/, callinDecl.scope, roleType,
                                            callinDecl.getRoleMethod(), gen)
                                    : gen.messageSend(receiver, callinDecl.roleMethodSpec.selector, callArgs);
                    roleMethodCall.isGenerated = true; // for PrivateRoleMethodCall
                    roleMethodCall.isPushedOutRoleMethodCall = true;

                    // -- post processing:
                    Statement[] messageSendStatements;
                    if (isReplace) {
                        Expression result = roleMethodCall;
                        if (baseSpec.returnNeedsTranslation) {
                            // lowering:
                            TypeBinding[]/*role,base*/ returnTypes = getReturnTypes(callinDecl, 0);
                            //   who is responsible for lowering: the team or the current role?
                            Expression lowerReceiver = (isRoleOfCurrentRole(roleType, returnTypes[0]))
                                    ? gen.singleNameReference(roleVar)
                                    : genTeamThis(gen, returnTypes[0]);
                            result = new Lowering().lowerExpression(methodDecl.scope, result, returnTypes[0],
                                    returnTypes[1], lowerReceiver, true/*needNullCheck*/,
                                    true/*delayedResolve*/);
                        }
                        // possibly convert using result mapping
                        callinDecl.checkResultMapping();
                        boolean isResultBoxed = baseReturn.isBaseType() && baseReturn != TypeBinding.VOID;
                        if (callinDecl.mappings != null && callinDecl.isResultMapped) {
                            if (isResultBoxed)
                                result = gen.createUnboxing(result, (BaseTypeBinding) baseReturn);
                            Expression mappedResult = new PotentialRoleReceiverExpression(
                                    callinDecl.getResultExpression(baseSpec, isResultBoxed, gen/*stepOverGen*/),
                                    roleVar, gen.typeReference(roleType.getRealClass()));
                            messageSendStatements = new Statement[] {
                                    callinDecl.resultVar = gen.localVariable(IOTConstants.RESULT, baseReturn, //   result = (Type)role.roleMethod(args);
                                            gen.castExpression(result, gen.typeReference(baseReturn),
                                                    CastExpression.RAW)),
                                    // cast because role return might be generalized
                                    gen.returnStatement(mappedResult) //   return mappedResult(result);
                            };
                        } else {
                            if (isResultBoxed) { // $if_need_result_unboxing$
                                messageSendStatements = new Statement[] {
                                        gen.localVariable(IOTConstants.OT_RESULT, //   Object _OT$result = role.roleMethod(args);
                                                gen.qualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT),
                                                result),
                                        CallinImplementor.genResultNotProvidedCheck( //    if (_OT$result == null)
                                                teamDecl.binding.readableName(), //      throw new ResultNotProvidedException(..)
                                                roleType.readableName(), roleMethodBinding,
                                                roleType.baseclass(), baseSpec, gen),
                                        gen.returnStatement(gen.singleNameReference(IOTConstants.OT_RESULT)) //  return _OT$result;
                                };
                            } else { // $endif$
                                messageSendStatements = new Statement[] { gen.returnStatement(result) }; //   return role.roleMethod(args);
                            }
                        }
                    } else {
                        messageSendStatements = new Statement[] { roleMethodCall, //   role.roleMethod(args);
                                gen.breakStatement() //   break;
                        };
                    }
                    // assemble:
                    //      try { roleMessageSend(); }
                    //      catch(Exception _OT$caughtException) { throw new SneakyException(_OT$caughtException); }
                    //      finally { _OT$setExecutingCallin(_OT$oldIsExecutingCallin); } 
                    blockStatements.add(
                            protectRoleMethodCall(messageSendStatements, roleMethodBinding, resetFlag, gen));
                    statements.add(gen.block(blockStatements.toArray(new Statement[blockStatements.size()])));
                    // collectively report the problem(s)
                    if (canLiftingFail && callinDecl.rolesWithLiftingProblem != null)
                        for (Map.Entry<ReferenceBinding, Integer> entry : callinDecl.rolesWithLiftingProblem
                                .entrySet())
                            callinDecl.scope.problemReporter().callinDespiteLiftingProblem(entry.getKey(),
                                    entry.getValue(), callinDecl);
                }
            } // END for (CallinMappingDeclaration callinDecl : callinDecls) 

            gen.retargetFrom(teamDecl);

            boolean needSuperCall = false;
            // do we have a relevant super team, which possibly defines more callins?
            ReferenceBinding superTeam = aTeam.getBinding().superclass();
            if (superTeam != null && superTeam.isTeam() && superTeam.id != IOTConstants.T_OrgObjectTeamsTeam) {
                // callinIds to be handled by super call?
                for (int i = 0; i < callinIdCount; i++)
                    if (!handledCallinIds[i]) {
                        statements.add(gen.caseStatement(gen.intLiteral(i))); // case callinIdOfSuper:
                        needSuperCall = true;
                    }
                if (!isReplace)
                    needSuperCall = true;
                // a super call might become necessary after the fact when this dispatch method
                // is copy-inherited to a tsub-team, because the tsub-team may have a super
                // with more callins, see test1111_roleInheritsCallinFromTsupers1.
                // TODO: can we safely handle this for the replace-case, too??
                // (replace needs to "return _OT$callNext();" in the default branch, see below).
                // See https://bugs.eclipse.org/433123
            }
            if (needSuperCall) {
                if (!isReplace)
                    statements.add(gen.caseStatement(null)); // default label
                char[] selector;
                char[][] argNames;
                if (isReplace) {
                    selector = OT_CALL_REPLACE;
                    argNames = REPLACE_ARG_NAMES;
                } else if (isAfter) {
                    selector = OT_CALL_AFTER;
                    argNames = AFTER_ARG_NAMES;
                } else {
                    selector = OT_CALL_BEFORE;
                    argNames = BEFORE_ARG_NAMES;
                }
                Expression[] superCallArgs = new Expression[argNames.length];
                for (int idx = 0; idx < argNames.length; idx++)
                    superCallArgs[idx] = gen.singleNameReference(argNames[idx]);
                // if we have a tsuper team which a corresponding dispatch method that one takes precedence:
                MessageSend superCall = aTeam.hasTSuperTeamMethod(selector)
                        ? gen.tsuperMessageSend(gen.thisReference(), selector, superCallArgs)
                        : gen.messageSend(gen.superReference(), selector, superCallArgs);
                if (isReplace)
                    statements.add(gen.returnStatement(superCall)); //    return super._OT$callReplace(..);
                else
                    statements.add(superCall); //    super._OT$callBefore/After(..);
            }

            Statement catchStatement1 = gen.emptyStatement();
            Statement catchStatement2 = gen.emptyStatement();
            if (isReplace) {

                // default: callNext:
                Expression[] callArgs = new Expression[REPLACE_ARG_NAMES.length + 1];
                for (int idx = 0; idx < REPLACE_ARG_NAMES.length; idx++)
                    callArgs[idx] = gen.singleNameReference(REPLACE_ARG_NAMES[idx]);
                callArgs[callArgs.length - 1] = gen.nullLiteral(); // no explicit baseCallArguments
                statements.add(gen.caseStatement(null)); // default:
                statements.add(gen.returnStatement( //    return _OT$callNext(..);
                        gen.messageSend(gen.qualifiedThisReference(aTeam.getBinding()), OT_CALL_NEXT,
                                callArgs)));
                catchStatement1 = gen.returnStatement(gen
                        .messageSend(gen.qualifiedThisReference(aTeam.getBinding()), OT_CALL_NEXT, callArgs));
                catchStatement2 = gen.returnStatement(gen
                        .messageSend(gen.qualifiedThisReference(aTeam.getBinding()), OT_CALL_NEXT, callArgs));
            }

            // ==== overall assembly: ====
            switchStat.statements = statements.toArray(new Statement[statements.size()]);
            Argument[] exceptionArguments;
            Statement[][] exceptionStatementss;
            if (canLiftingFail) {
                exceptionArguments = new Argument[] { gen.argument("ex".toCharArray(), //$NON-NLS-1$
                        gen.qualifiedTypeReference(IOTConstants.ORG_OBJECTTEAMS_LIFTING_VETO)),
                        gen.argument("ex".toCharArray(), //$NON-NLS-1$
                                gen.qualifiedTypeReference(IOTConstants.O_O_LIFTING_FAILED_EXCEPTION)) };
                exceptionStatementss = new Statement[][] { { catchStatement1 }, { catchStatement2 } };
            } else {
                exceptionArguments = new Argument[] { gen.argument("ex".toCharArray(), //$NON-NLS-1$
                        gen.qualifiedTypeReference(IOTConstants.ORG_OBJECTTEAMS_LIFTING_VETO)) };
                exceptionStatementss = new Statement[][] { { catchStatement1 } };
            }
            tryStats.add(switchStat);
            methodDecl.statements = new Statement[] {
                    gen.tryCatch(tryStats.toArray(new Statement[tryStats.size()]),
                            // expected exception is ignored, do nothing (before/after) or proceed to callNext (replace)
                            exceptionArguments, exceptionStatementss) };
            methodDecl.hasParsedStatements = true;
            return true;
        }

    });
}

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

License:Open Source License

/** This method drives the creation of a callout implementation for one callout mapping. */
private MethodDeclaration createCallout(CalloutMappingDeclaration calloutMappingDeclaration, boolean needBody,
        boolean isInferred) {
    CallinCalloutScope calloutScope = calloutMappingDeclaration.scope;

    calloutMappingDeclaration.updateTSuperMethods();

    // This binding is part of the interface part of a role:
    MethodBinding roleMethodBinding = calloutMappingDeclaration.getRoleMethod();

    if (roleMethodBinding == null) // CLOVER: never true in jacks suite
    {/*from   w  w  w .  j  a v a 2  s .c o m*/
        // problemreporting already done in find-Base/Role-MethodBinding
        assert (calloutMappingDeclaration.ignoreFurtherInvestigation);
        return null;
    }
    if (!roleMethodBinding.isValidBinding()) {
        if (roleMethodBinding.problemId() != ProblemReasons.NotFound) {
            // CLOVER: never true in jacks suite
            calloutMappingDeclaration.tagAsHavingErrors();
            // hopefully error has been reported!
            return null;
        } else { // shorthand style callout
            // help sourceMethod() below to find another callout method
            MethodBinding existingMethod = calloutScope.enclosingSourceType().getExactMethod(
                    roleMethodBinding.selector, roleMethodBinding.parameters,
                    calloutScope.compilationUnitScope());
            if (existingMethod != null)
                roleMethodBinding = existingMethod;
        }
    }

    MethodDeclaration roleMethodDeclaration = null;
    if (TypeBinding.equalsEquals(roleMethodBinding.declaringClass, calloutScope.enclosingSourceType()))
        roleMethodDeclaration = (MethodDeclaration) roleMethodBinding.sourceMethod();

    // have a binding but no declaration for method? -> requires creation of declaration
    boolean foundRoleDecl = roleMethodDeclaration != null;
    MethodBinding overriddenTSuper = null;
    // The following code allows to use tsuper in parameter mappings
    // (see 3.2.32-otjld-tsuper-access-1)
    if (foundRoleDecl && roleMethodDeclaration.isCopied // foundRoleDecl => (roleMethodDeclaration != null)
            && (roleMethodDeclaration.modifiers & AccAbstract) == 0
            && !TSuperHelper.isTSuper(roleMethodDeclaration.binding)) {
        // mapping conflicts with an implicitly inherited method.
        // make the latter a tsuper version, now.
        overriddenTSuper = roleMethodBinding;
        // save a clone of the method binding before adding the marker arg, for use below.
        roleMethodBinding = new MethodBinding(roleMethodBinding, roleMethodBinding.declaringClass); // clone

        TSuperHelper.addMarkerArg(roleMethodDeclaration,
                roleMethodDeclaration.binding.copyInheritanceSrc.declaringClass.enclosingType());
        foundRoleDecl = false; // re-create the method;
    }

    if (!foundRoleDecl) {
        roleMethodDeclaration = createAbstractRoleMethodDeclaration(roleMethodBinding,
                calloutMappingDeclaration);
        if (overriddenTSuper != null)
            roleMethodDeclaration.binding.addOverriddenTSuper(overriddenTSuper);
    } else {
        roleMethodDeclaration.isReusingSourceMethod = true; // foundRoleDecl => (roleMethodDeclaration != null)
        // mark existing method as generated by the callout mapping:
        roleMethodDeclaration.isMappingWrapper = WrapperKind.CALLOUT;

        // match locator may want to know this for the interface part, too:
        // (SH: unsure, if this is really needed, but it doesn't hurt either ;-)
        if (roleMethodDeclaration.interfacePartMethod != null) {
            roleMethodDeclaration.interfacePartMethod.isReusingSourceMethod = true;
            roleMethodDeclaration.interfacePartMethod.isMappingWrapper = WrapperKind.CALLOUT;
        }
    }

    if (calloutMappingDeclaration.hasSignature) {
        // Adjust arguments:
        Argument[] args = calloutMappingDeclaration.roleMethodSpec.arguments;
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                // if we already have a declaration and if we have signatures
                // in the mapping declaration, use the argument names from the
                // method mapping rather than those from the original declaration
                // (needed for parameter mapping!).
                if (foundRoleDecl)
                    roleMethodDeclaration.arguments[i].updateName(args[i].name);

                // also link best names of arguments of roleMethodSpec and actual wrapper
                // ( requires wrapper argument to be bound, do this first.
                //   Note that all args must be bound in order!).
                roleMethodDeclaration.arguments[i].bind(roleMethodDeclaration.scope, args[i].binding.type,
                        false);
                args[i].binding.setBestNameFromStat(roleMethodDeclaration.arguments[i]);
            }
        }
    }

    if (roleMethodDeclaration != null) // try again
    {
        // Note: do not query the binding (as isAbstract() would do).
        // Binding may have corrected modifiers, but take the raw modifiers.
        if (!roleMethodDeclaration.isCopied && !roleMethodDeclaration.isGenerated
                && (roleMethodDeclaration.modifiers & AccAbstract) == 0) {
            // bad overriding of existing / non-existant methods is handled in MethodMappingResolver already
            roleMethodDeclaration.ignoreFurtherInvestigation = true; // don't throw "abstract method.. can only be defined by abstract class" error
            calloutScope.problemReporter().calloutOverridesLocal(this._role.getAst(), calloutMappingDeclaration,
                    roleMethodDeclaration.binding);
            return null;
        }

        // fix flags (even if not needing body):
        roleMethodDeclaration.isCopied = false;
        int flagsToRemove = AccAbstract | ExtraCompilerModifiers.AccSemicolonBody | AccNative;
        roleMethodDeclaration.modifiers &= ~flagsToRemove;
        roleMethodDeclaration.binding.modifiers &= ~flagsToRemove;
        roleMethodDeclaration.isGenerated = true; // even if not generated via AstGenerator.
        if (needBody && calloutMappingDeclaration.binding.isValidBinding()) {
            // defer generation of statements:
            final CalloutMappingDeclaration mappingDeclaration = calloutMappingDeclaration;
            MethodModel methodModel = MethodModel.getModel(roleMethodDeclaration);
            if (isInferred)
                methodModel._inferredCallout = mappingDeclaration;
            methodModel.setStatementsGenerator(new AbstractStatementsGenerator() {
                public boolean generateStatements(AbstractMethodDeclaration methodDecl) {
                    createCalloutMethodBody((MethodDeclaration) methodDecl, mappingDeclaration);
                    return true;
                }
            });
        } else if (calloutMappingDeclaration.ignoreFurtherInvestigation) {
            roleMethodDeclaration.binding.bytecodeMissing = true; // will not be generated, so don't complain later.
        }
    } else // roleMethodDeclaration still null
    {
        // CLOVER: never reached in jacks suite ;-)
        throw new InternalCompilerError("OT-Compiler Error: couldn't create method declaration for callout! " //$NON-NLS-1$
                + calloutMappingDeclaration.toString());
    }
    return roleMethodDeclaration;
}

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

License:Open Source License

/**
 * Report errors if there are more than one mapping for the given
 * role-method./*from ww w  .ja  v a2 s .  c  om*/
 * @param roleMethodKey name&signature of method to check
 * @return true if there's only one mapping for the method else false.
 */
private boolean checkForDuplicateMethodMappings(String roleMethodKey) {
    List<CalloutMappingDeclaration> methodSpecs = this._foundRoleMethods.get(roleMethodKey);
    if (methodSpecs.size() > 1) {
        for (Iterator<CalloutMappingDeclaration> iter = methodSpecs.iterator(); iter.hasNext();) {
            CalloutMappingDeclaration mapping = iter.next();
            if (TypeBinding.equalsEquals(mapping.binding._declaringRoleClass, this._role.getBinding())) {
                mapping.scope.problemReporter().duplicateCalloutBinding(this._role.getAst(),
                        mapping.roleMethodSpec);
            }
        }
        return false;
    }
    return true; // no dupes found
}

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

License:Open Source License

/** Is ifc the synthetic interface part of clazz? */
public static boolean isSynthIfcOfClass(ReferenceBinding ifc, ReferenceBinding clazz) {
    if (ifc.isSynthInterface() && ifc.roleModel != null)
        if (TypeBinding.equalsEquals(ifc.roleModel.getClassPartBinding(), clazz))
            return true;
    return false;
}

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

License:Open Source License

/**
 * Is role some kind of tsuper role of current?
 * It could be that any enclosing teams are role-and-tsuper-role.
 * Then from there on inwards only role names are compared.
 *///from   w  w w .  jav  a  2 s. c o m
public boolean hasTSuperRole(ReferenceBinding role) {
    if (!role.isRole())
        return false;
    ReferenceBinding otherClass = null, otherIfc = null;
    if (role.isInterface()) {
        otherIfc = role;
        otherClass = role.getRealClass();
    } else {
        otherIfc = role.getRealType();
        otherClass = role;
    }
    Dependencies.ensureRoleState(this, ITranslationStates.STATE_LENV_CONNECT_TYPE_HIERARCHY);
    for (int i = 0; i < this.numTSuperRoles; i++) {
        ReferenceBinding other = this._tsuperRoleBindings[i].isInterface() ? otherIfc : otherClass;
        if (TypeBinding.equalsEquals(this._tsuperRoleBindings[i], other))
            return true;
        if (this._tsuperRoleBindings[i].roleModel.hasTSuperRole(other))
            return true;
    }
    ReferenceBinding outerRole = this._binding.enclosingType();
    if (outerRole.isRole()) {
        ReferenceBinding roleOuter = role.enclosingType();
        if (!roleOuter.isRole())
            return false;
        if (!outerRole.roleModel.hasTSuperRole(roleOuter))
            return false;
        return CharOperation.equals(role.internalName(), this._binding.internalName());
    }
    return false;
}