Example usage for org.eclipse.jdt.internal.compiler.ast ThisReference implicitThis

List of usage examples for org.eclipse.jdt.internal.compiler.ast ThisReference implicitThis

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.ast ThisReference implicitThis.

Prototype

public static ThisReference implicitThis() 

Source Link

Usage

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

License:Open Source License

/**
 * Generates a <code>$fillValuesFrom()</code> method in the abstract builder class that looks
 * like this://from  w  w w  . ja va  2  s  .  co m
 * <pre>
 * protected B $fillValuesFrom(final C instance) {
 *     super.$fillValuesFrom(instance);
 *     FoobarBuilderImpl.$fillValuesFromInstanceIntoBuilder(instance, this);
 *     return self();
 * }
 * </pre>
 */
private MethodDeclaration generateFillValuesMethod(EclipseNode tdParent, boolean inherited,
        String builderGenericName, String classGenericName, String builderClassName,
        TypeParameter[] typeParams) {
    MethodDeclaration out = new MethodDeclaration(
            ((CompilationUnitDeclaration) tdParent.top().get()).compilationResult);
    out.selector = FILL_VALUES_METHOD_NAME;
    out.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    out.modifiers = ClassFileConstants.AccProtected;
    if (inherited)
        out.annotations = new Annotation[] {
                makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, tdParent.get()) };
    out.returnType = new SingleTypeReference(builderGenericName.toCharArray(), 0);

    TypeReference builderType = new SingleTypeReference(classGenericName.toCharArray(), 0);
    out.arguments = new Argument[] { new Argument(INSTANCE_VARIABLE_NAME, 0, builderType, Modifier.FINAL) };

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

    if (inherited) {
        // Call super.
        MessageSend callToSuper = new MessageSend();
        callToSuper.receiver = new SuperReference(0, 0);
        callToSuper.selector = FILL_VALUES_METHOD_NAME;
        callToSuper.arguments = new Expression[] { new SingleNameReference(INSTANCE_VARIABLE_NAME, 0) };
        body.add(callToSuper);
    }

    // Call the builder implemention's helper method that actually fills the values from the instance.
    MessageSend callStaticFillValuesMethod = new MessageSend();
    callStaticFillValuesMethod.receiver = new SingleNameReference(builderClassName.toCharArray(), 0);
    callStaticFillValuesMethod.selector = FILL_VALUES_STATIC_METHOD_NAME;
    callStaticFillValuesMethod.arguments = new Expression[] {
            new SingleNameReference(INSTANCE_VARIABLE_NAME, 0), new ThisReference(0, 0) };
    body.add(callStaticFillValuesMethod);

    // Return self().
    MessageSend returnCall = new MessageSend();
    returnCall.receiver = ThisReference.implicitThis();
    returnCall.selector = SELF_METHOD_NAME;
    body.add(new ReturnStatement(returnCall, 0, 0));

    out.statements = body.isEmpty() ? null : body.toArray(new Statement[0]);

    return out;
}

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

License:Open Source License

private void generateSetterMethodsForBuilder(EclipseNode builderType, BuilderFieldData bfd,
        EclipseNode sourceNode, final String builderGenericName) {
    boolean deprecate = isFieldDeprecated(bfd.originalFieldNode);

    TypeReferenceMaker returnTypeMaker = new TypeReferenceMaker() {
        @Override//from  ww w. j  av  a 2  s . com
        public TypeReference make() {
            return new SingleTypeReference(builderGenericName.toCharArray(), 0);
        }
    };

    StatementMaker returnStatementMaker = new StatementMaker() {
        @Override
        public ReturnStatement make() {
            MessageSend returnCall = new MessageSend();
            returnCall.receiver = ThisReference.implicitThis();
            returnCall.selector = SELF_METHOD_NAME;
            return new ReturnStatement(returnCall, 0, 0);
        }
    };

    if (bfd.singularData == null || bfd.singularData.getSingularizer() == null) {
        generateSimpleSetterMethodForBuilder(builderType, deprecate, bfd.createdFields.get(0),
                bfd.nameOfSetFlag, returnTypeMaker.make(), returnStatementMaker.make(), sourceNode,
                bfd.annotations);
    } else {
        bfd.singularData.getSingularizer().generateMethods(bfd.singularData, deprecate, builderType, true,
                returnTypeMaker, returnStatementMaker);
    }
}

From source file:org.eclipse.jdt.internal.compiler.parser.Parser.java

License:Open Source License

protected void consumeMethodInvocationName() {
    // MethodInvocation ::= Name '(' ArgumentListopt ')'

    // when the name is only an identifier...we have a message send to "this" (implicit)

    MessageSend m = newMessageSend();/*  ww  w. j a v a 2 s  .  c o  m*/
    m.sourceEnd = this.rParenPos;
    m.sourceStart = (int) ((m.nameSourcePosition = this.identifierPositionStack[this.identifierPtr]) >>> 32);
    m.selector = this.identifierStack[this.identifierPtr--];
    if (this.identifierLengthStack[this.identifierLengthPtr] == 1) {
        m.receiver = ThisReference.implicitThis();
        this.identifierLengthPtr--;
    } else {
        this.identifierLengthStack[this.identifierLengthPtr]--;
        m.receiver = getUnspecifiedReference();
        m.sourceStart = m.receiver.sourceStart;
    }
    pushOnExpressionStack(m);
}

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

License:Open Source License

/**
 * Same as above, but consider specified signature for argument mapping (using AnchorMapping).
 * @param receiverType receiver of the method call.
 * @param scope//ww  w.j a va2s . co m
 * @param isBaseSide
 * @param callinExpected whether this method spec is the LHS of a replace callin.
 * @param allowEnclosing whether a method may be found in an enclosing type of receiverType
 */
public void resolveFeatureWithArgMapping(ReferenceBinding receiverType, BlockScope scope, boolean isBaseSide,
        boolean callinExpected, boolean allowEnclosing) {
    FieldReference receiver = null;
    if (isBaseSide) {
        // construct temporary faked receiver
        ReferenceContext referenceContext = scope.referenceContext();
        CheckPoint cp = referenceContext.compilationResult().getCheckPoint(referenceContext);
        receiver = new FieldReference(IOTConstants._OT_BASE, 0L); // can't fail, help the compiler recognize that receiver won't be null below.
        try {
            receiver.receiver = ThisReference.implicitThis();
            receiver.resolveType(scope);
        } finally {
            if (receiver.binding == null || !receiver.binding.isValidBinding()) {
                // resolve didn't work, which happens if role is ifc, thus has no base field
                // at least set the receiver type.
                // TODO(SH): this means, role ifcs can not use base-anchored types.
                receiver.resolvedType = receiverType;
                referenceContext.compilationResult().rollBack(cp);
            }
        }
    }
    AnchorMapping anchorMapping = null;
    try {
        anchorMapping = AnchorMapping.setupNewMapping(receiver, this.arguments, scope);
        resolveFeature(receiverType, scope, callinExpected, isBaseSide, allowEnclosing);
    } finally {
        AnchorMapping.removeCurrentMapping(anchorMapping);
    }
}

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

License:Open Source License

/**
 * Instead of parsing statements, possibly generate them just before resolving.
 *///  ww w. j a v a 2  s.  c om
public void resolveStatements() {
    if (this.ignoreFurtherInvestigation)
        return;
    MethodBinding tsuperInit = getTSuperInit(this.scope.referenceType().getRoleModel());
    if (tsuperInit != null) {
        AstGenerator gen = new AstGenerator(this.sourceStart, this.sourceEnd);
        // there is a tsuper-version, so call it:
        MessageSend tsuperCall = gen.messageSend(ThisReference.implicitThis(), this.selector, null);
        tsuperCall.arguments = TSuperHelper.addMarkerArgument(null/*qualification*/, tsuperCall,
                tsuperCall.arguments, this.scope);
        if (this.statements == null)
            setStatements(new Statement[] { tsuperCall });
        else {
            // already have a casted local due to signature weakening
            int len = this.statements.length;
            Statement[] newStatements = new Statement[len + 1];
            System.arraycopy(this.statements, 0, newStatements, 0, len);
            newStatements[len] = tsuperCall;
            setStatements(newStatements);
        }
        super.resolveStatements();
    } else {
        setStatements(new Statement[0]); // maybe remove useless casted local
    }
}

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

License:Open Source License

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

    // names:/*from   ww w.j a v  a 2 s  . co  m*/
    char[] oldName = argument.name;
    char[] newName = CharOperation.concat(OT_DOLLAR_NAME, oldName);
    argument.updateName(newName);

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

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

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

    return declaration;
}

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

License:Open Source License

private FieldReference createCacheFieldRef() {
    // _OT$team_param._OT$cache_OT$RootRole
    return this._gen.fieldReference(this._gen.setPos(ThisReference.implicitThis()),
            LiftingEnvironment.getCacheName(this._boundRootRoleModel), DecapsulationState.REPORTED);
}

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

License:Open Source License

private Statement createLiftedRoleVar(CallinMappingDeclaration callinBindingDeclaration, RoleModel roleModel,
        ReferenceBinding baseTypeBinding, char[] otBaseArg, AstGenerator gen) {
    MessageSend liftCall = Lifting.liftCall(callinBindingDeclaration.scope, ThisReference.implicitThis(),
            gen.baseNameReference(otBaseArg), baseTypeBinding, roleModel.getBinding(),
            callinBindingDeclaration.isReplaceCallin()/* needLowering*/);

    ReferenceBinding roleVarType = roleModel.getInterfacePartBinding();
    // does lifting use type parameters? If so, use the same types as type arguments for the role variable
    MethodBinding[] liftMethod = roleVarType.enclosingType().getMethods(liftCall.selector);
    if (liftMethod != null && liftMethod.length > 0) {
        TypeBinding[] typeArguments = liftMethod[0].typeVariables();
        if (typeArguments != Binding.NO_TYPE_VARIABLES)
            try {
                // FIXME: pass null annotations, once JDT supports those on a type declaration.
                roleVarType = Config.getLookupEnvironment().createParameterizedType(roleVarType, typeArguments,
                        null, -1, roleModel.getBinding().enclosingType(), Binding.NO_ANNOTATIONS);
            } catch (NotConfiguredException e) {
                e.logWarning("Cannot lookup parameterized type"); //$NON-NLS-1$
            }// ww  w. ja  v  a2  s . c o  m
    }
    return gen.localVariable(ROLE_VAR_NAME, roleVarType, liftCall);
}

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;//  w  w  w  .jav  a2  s.  c om
    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.statemachine.copyinheritance.CopyInheritance.java

License:Open Source License

/**
 * Create an invocation of a creation method, which will replace a given
 * allocation expression, i.e.,/*w w w.  ja v a2s.co  m*/
 *      new R(args) ==> _OT$createR(args)
 *
 * PRE: allocationExpr.type has a simple name.
 *
 * @param scope
 * @param allocationExpr
 * @return the fully assembled expression.
 */
public static MessageSend createConstructorMethodInvocationExpression(Scope scope,
        AllocationExpression allocationExpr) {
    // some elements from allocationExpression can be reused, since that
    // expression will be discarded (replaced by the result of this method).
    // These parts will only be used one more time by the current
    // TransformStatementsVisitor, so don't delete yet.

    if (!(allocationExpr.type instanceof SingleTypeReference)) {
        scope.problemReporter().roleCreationNotRelativeToEnclosingTeam(allocationExpr);
        allocationExpr.resolvedType = allocationExpr.type.resolvedType;
        return null;
    }

    AstGenerator gen = new AstGenerator(allocationExpr.sourceStart, allocationExpr.sourceEnd);
    char[] typeName = allocationExpr.type.getTypeName()[0];
    char[] selector = CharOperation.concat(CREATOR_PREFIX_NAME, typeName);

    Expression receiver = null;
    if (allocationExpr instanceof QualifiedAllocationExpression) {
        // Sharing 'receiver' breaks tree structure, but MessageSend and
        // RoleTypeReference avoid double resolving.
        receiver = ((QualifiedAllocationExpression) allocationExpr).enclosingInstance;
    }
    if (receiver == null && allocationExpr.type instanceof ParameterizedSingleTypeReference) {
        ParameterizedSingleTypeReference psType = (ParameterizedSingleTypeReference) allocationExpr.type;
        if (psType.typeAnchors != null) {
            assert psType.typeAnchors.length == 1 : "Currently only one value parameter supported."; //$NON-NLS-1$
            receiver = psType.typeAnchors[0].anchor;
        }
    }
    if (receiver != null) {
        ReferenceBinding receiverType = (ReferenceBinding) receiver.resolvedType;
        // TransformStatementsVisitor calls us before resolve, but that transformer
        // has an identifier-based strategy to ensure that the role exists.
        if (receiverType != null) {
            receiverType = receiverType.getRealClass();
            Dependencies.ensureBindingState(receiverType, STATE_LENV_CONNECT_TYPE_HIERARCHY);
            if (receiverType.getMemberType(typeName) == null) {
                scope.problemReporter().noSuchRoleInTeam(allocationExpr.type, receiverType);
                return null;
            }
        }
    } else {
        receiver = ThisReference.implicitThis();
    }
    MessageSend message = new RoleConstructorCall(allocationExpr);
    gen.setPos(message);
    message.nameSourcePosition = gen.pos;
    message.selector = selector;
    message.receiver = receiver;
    message.arguments = allocationExpr.arguments;

    // remove left-overs (if any):
    allocationExpr.resolvedType = null;

    return message;
}