Example usage for org.eclipse.jdt.internal.compiler.ast ExplicitConstructorCall Super

List of usage examples for org.eclipse.jdt.internal.compiler.ast ExplicitConstructorCall Super

Introduction

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

Prototype

int Super

To view the source code for org.eclipse.jdt.internal.compiler.ast ExplicitConstructorCall Super.

Click Source Link

Usage

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

License:Open Source License

/**
 * Generates a constructor that has a builder as the only parameter.
 * The values from the builder are used to initialize the fields of new instances.
 *
 * @param typeNode// ww  w  .  j a  v  a  2  s.c  o  m
 *            the type (with the {@code @Builder} annotation) for which a
 *            constructor should be generated.
 * @param typeParams
 * @param builderFields a list of fields in the builder which should be assigned to new instances.
 * @param source the annotation (used for setting source code locations for the generated code).
 * @param callBuilderBasedSuperConstructor
 *            If {@code true}, the constructor will explicitly call a super
 *            constructor with the builder as argument. Requires
 *            {@code builderClassAsParameter != null}.
 */
private void generateBuilderBasedConstructor(EclipseNode typeNode, TypeParameter[] typeParams,
        List<BuilderFieldData> builderFields, EclipseNode sourceNode, String builderClassName,
        boolean callBuilderBasedSuperConstructor) {

    ASTNode source = sourceNode.get();

    TypeDeclaration typeDeclaration = ((TypeDeclaration) typeNode.get());
    long p = (long) source.sourceStart << 32 | source.sourceEnd;

    ConstructorDeclaration constructor = new ConstructorDeclaration(
            ((CompilationUnitDeclaration) typeNode.top().get()).compilationResult);

    constructor.modifiers = toEclipseModifier(AccessLevel.PROTECTED);
    constructor.selector = typeDeclaration.name;
    if (callBuilderBasedSuperConstructor) {
        constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.Super);
        constructor.constructorCall.arguments = new Expression[] {
                new SingleNameReference(BUILDER_VARIABLE_NAME, p) };
    } else {
        constructor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.ImplicitSuper);
    }
    constructor.constructorCall.sourceStart = source.sourceStart;
    constructor.constructorCall.sourceEnd = source.sourceEnd;
    constructor.thrownExceptions = null;
    constructor.typeParameters = null;
    constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = source.sourceStart;
    constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = source.sourceEnd;

    TypeReference[] wildcards = new TypeReference[] { new Wildcard(Wildcard.UNBOUND),
            new Wildcard(Wildcard.UNBOUND) };
    TypeReference builderType = new ParameterizedSingleTypeReference(builderClassName.toCharArray(),
            mergeToTypeReferences(typeParams, wildcards), 0, p);
    constructor.arguments = new Argument[] {
            new Argument(BUILDER_VARIABLE_NAME, p, builderType, Modifier.FINAL) };

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

    for (BuilderFieldData fieldNode : builderFields) {
        char[] fieldName = removePrefixFromField(fieldNode.originalFieldNode);
        FieldReference fieldInThis = new FieldReference(fieldNode.rawName, p);
        int s = (int) (p >> 32);
        int e = (int) p;
        fieldInThis.receiver = new ThisReference(s, e);

        Expression assignmentExpr;
        if (fieldNode.singularData != null && fieldNode.singularData.getSingularizer() != null) {
            fieldNode.singularData.getSingularizer().appendBuildCode(fieldNode.singularData, typeNode,
                    statements, fieldNode.name, BUILDER_VARIABLE_NAME_STRING);
            assignmentExpr = new SingleNameReference(fieldNode.name, p);
        } else {
            char[][] variableInBuilder = new char[][] { BUILDER_VARIABLE_NAME, fieldName };
            long[] positions = new long[] { p, p };
            assignmentExpr = new QualifiedNameReference(variableInBuilder, positions, s, e);
        }
        Statement assignment = new Assignment(fieldInThis, assignmentExpr, (int) p);

        // In case of @Builder.Default, set the value to the default if it was NOT set in the builder.
        if (fieldNode.nameOfSetFlag != null) {
            char[][] setVariableInBuilder = new char[][] { BUILDER_VARIABLE_NAME, fieldNode.nameOfSetFlag };
            long[] positions = new long[] { p, p };
            QualifiedNameReference setVariableInBuilderRef = new QualifiedNameReference(setVariableInBuilder,
                    positions, s, e);

            MessageSend defaultMethodCall = new MessageSend();
            defaultMethodCall.sourceStart = source.sourceStart;
            defaultMethodCall.sourceEnd = source.sourceEnd;
            defaultMethodCall.receiver = new SingleNameReference(((TypeDeclaration) typeNode.get()).name, 0L);
            defaultMethodCall.selector = fieldNode.nameOfDefaultProvider;
            defaultMethodCall.typeArguments = typeParameterNames(
                    ((TypeDeclaration) typeNode.get()).typeParameters);

            Statement defaultAssignment = new Assignment(fieldInThis, defaultMethodCall, (int) p);
            IfStatement ifBlockForDefault = new IfStatement(setVariableInBuilderRef, assignment,
                    defaultAssignment, s, e);
            statements.add(ifBlockForDefault);
        } else {
            statements.add(assignment);
        }

        if (hasNonNullAnnotations(fieldNode.originalFieldNode)) {
            Statement nullCheck = generateNullCheck((FieldDeclaration) fieldNode.originalFieldNode.get(),
                    sourceNode);
            if (nullCheck != null)
                statements.add(nullCheck);
        }
    }

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

    constructor.traverse(new SetGeneratedByVisitor(source), typeDeclaration.scope);

    injectMethod(typeNode, constructor);
}

From source file:org.eclipse.ajdt.core.parserbridge.AJSourceElementNotifier.java

License:Open Source License

protected void notifySourceElementRequestor(AbstractMethodDeclaration methodDeclaration) {

    // range check
    boolean isInRange = initialPosition <= methodDeclaration.declarationSourceStart
            && eofPosition >= methodDeclaration.declarationSourceEnd;

    if (methodDeclaration.isClinit()) {
        this.visitIfNeeded(methodDeclaration);
        return;/*from  www. j  a v  a  2 s. c o  m*/
    }

    if (methodDeclaration.isDefaultConstructor()) {
        if (reportReferenceInfo) {
            ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration;
            ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall;
            if (constructorCall != null) {
                switch (constructorCall.accessMode) {
                case ExplicitConstructorCall.This:
                    requestor.acceptConstructorReference(typeNames[nestedTypeIndex - 1],
                            constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
                            constructorCall.sourceStart);
                    break;
                case ExplicitConstructorCall.Super:
                case ExplicitConstructorCall.ImplicitSuper:
                    requestor.acceptConstructorReference(superTypeNames[nestedTypeIndex - 1],
                            constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
                            constructorCall.sourceStart);
                    break;
                }
            }
        }
        return;
    }
    char[][] argumentTypes = null;
    char[][] argumentNames = null;
    boolean isVarArgs = false;
    Argument[] arguments = methodDeclaration.arguments;
    if (arguments != null) {
        char[][][] argumentTypesAndNames = this.getArguments(arguments);
        argumentTypes = argumentTypesAndNames[0];
        argumentNames = argumentTypesAndNames[1];

        isVarArgs = arguments[arguments.length - 1].isVarArgs();
    }
    char[][] thrownExceptionTypes = getThrownExceptions(methodDeclaration);
    // by default no selector end position
    int selectorSourceEnd = -1;
    if (methodDeclaration.isConstructor()) {
        selectorSourceEnd = this.sourceEnds.get(methodDeclaration);
        if (isInRange) {
            int currentModifiers = methodDeclaration.modifiers;
            if (isVarArgs)
                currentModifiers |= ClassFileConstants.AccVarargs;

            // remember deprecation so as to not lose it below
            boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0
                    || hasDeprecatedAnnotation(methodDeclaration.annotations);

            ISourceElementRequestor.MethodInfo methodInfo = new ISourceElementRequestor.MethodInfo();
            methodInfo.isConstructor = true;
            methodInfo.declarationStart = methodDeclaration.declarationSourceStart;
            methodInfo.modifiers = deprecated
                    ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag) | ClassFileConstants.AccDeprecated
                    : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
            methodInfo.name = methodDeclaration.selector;
            methodInfo.nameSourceStart = methodDeclaration.sourceStart;
            methodInfo.nameSourceEnd = selectorSourceEnd;
            methodInfo.parameterTypes = argumentTypes;
            methodInfo.parameterNames = argumentNames;
            methodInfo.exceptionTypes = thrownExceptionTypes;
            methodInfo.typeParameters = getTypeParameterInfos(methodDeclaration.typeParameters());
            methodInfo.categories = (char[][]) this.nodesToCategories.get(methodDeclaration);
            methodInfo.annotations = methodDeclaration.annotations;
            methodInfo.node = methodDeclaration;
            requestor.enterConstructor(methodInfo);
        }
        if (reportReferenceInfo) {
            ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) methodDeclaration;
            ExplicitConstructorCall constructorCall = constructorDeclaration.constructorCall;
            if (constructorCall != null) {
                switch (constructorCall.accessMode) {
                case ExplicitConstructorCall.This:
                    requestor.acceptConstructorReference(typeNames[nestedTypeIndex - 1],
                            constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
                            constructorCall.sourceStart);
                    break;
                case ExplicitConstructorCall.Super:
                case ExplicitConstructorCall.ImplicitSuper:
                    requestor.acceptConstructorReference(superTypeNames[nestedTypeIndex - 1],
                            constructorCall.arguments == null ? 0 : constructorCall.arguments.length,
                            constructorCall.sourceStart);
                    break;
                }
            }
        }
        this.visitIfNeeded(methodDeclaration);
        if (isInRange) {
            requestor.exitConstructor(methodDeclaration.declarationSourceEnd);
        }
        return;
    }
    selectorSourceEnd = this.sourceEnds.get(methodDeclaration);

    // AspectJ Change Begin
    // recreate source locations for Pointcuts and Advice
    org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration ajmDec = new org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration(
            new org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult(
                    methodDeclaration.compilationResult.fileName, methodDeclaration.compilationResult.unitIndex,
                    methodDeclaration.compilationResult.totalUnitsKnown, 500));
    if (ajmDec instanceof PointcutDeclaration) {
        selectorSourceEnd = methodDeclaration.sourceStart + methodDeclaration.selector.length - 1;
    }
    if (ajmDec instanceof AdviceDeclaration) {
        selectorSourceEnd = methodDeclaration.sourceStart + ((AdviceDeclaration) ajmDec).kind.getName().length()
                - 1;
    }
    // AspectJ Change End

    if (isInRange) {
        int currentModifiers = methodDeclaration.modifiers;
        if (isVarArgs)
            currentModifiers |= ClassFileConstants.AccVarargs;

        // remember deprecation so as to not lose it below
        boolean deprecated = (currentModifiers & ClassFileConstants.AccDeprecated) != 0
                || hasDeprecatedAnnotation(methodDeclaration.annotations);

        TypeReference returnType = methodDeclaration instanceof MethodDeclaration
                ? ((MethodDeclaration) methodDeclaration).returnType
                : null;
        ISourceElementRequestor.MethodInfo methodInfo = new ISourceElementRequestor.MethodInfo();
        methodInfo.isAnnotation = methodDeclaration instanceof AnnotationMethodDeclaration;
        methodInfo.declarationStart = methodDeclaration.declarationSourceStart;
        methodInfo.modifiers = deprecated
                ? (currentModifiers & ExtraCompilerModifiers.AccJustFlag) | ClassFileConstants.AccDeprecated
                : currentModifiers & ExtraCompilerModifiers.AccJustFlag;
        methodInfo.returnType = returnType == null ? null
                : CharOperation.concatWith(returnType.getParameterizedTypeName(), '.');
        methodInfo.name = methodDeclaration.selector;
        methodInfo.nameSourceStart = methodDeclaration.sourceStart;
        methodInfo.nameSourceEnd = selectorSourceEnd;
        methodInfo.parameterTypes = argumentTypes;
        methodInfo.parameterNames = argumentNames;
        methodInfo.exceptionTypes = thrownExceptionTypes;
        methodInfo.typeParameters = getTypeParameterInfos(methodDeclaration.typeParameters());
        methodInfo.categories = (char[][]) this.nodesToCategories.get(methodDeclaration);
        methodInfo.annotations = methodDeclaration.annotations;
        methodInfo.node = methodDeclaration;
        requestor.enterMethod(methodInfo);
    }

    this.visitIfNeeded(methodDeclaration);

    if (isInRange) {
        if (methodDeclaration instanceof AnnotationMethodDeclaration) {
            AnnotationMethodDeclaration annotationMethodDeclaration = (AnnotationMethodDeclaration) methodDeclaration;
            Expression expression = annotationMethodDeclaration.defaultValue;
            if (expression != null) {
                requestor.exitMethod(methodDeclaration.declarationSourceEnd, expression);
                return;
            }
        }
        requestor.exitMethod(methodDeclaration.declarationSourceEnd,
                (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression) null);
    }
}

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

License:Open Source License

/**
* @param baseExpr//from  w  ww  .j  a  v  a2  s . c  o m
*/
private ExplicitConstructorCall genLiftCtorCall(Expression baseExpr) {
    ExplicitConstructorCall constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.Super);
    constructorCall.arguments = new Expression[] { baseExpr };
    constructorCall.sourceStart = this.sourceStart;
    constructorCall.sourceEnd = this.sourceEnd;
    return constructorCall;
}

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

License:Open Source License

/**
 * At a specific point the constructor chain turns from this calls (w/ marker args)
 * to real super calls. Create a constructor which does nothing but this turning.
 * @param teamDecl//from  w  w  w  .  j av  a2 s .  c  o m
 * @param superTeamCtor
 * @param gen
 *
 * @return a binding if a new method has been generated, else null.
 */
public static MethodBinding maybeCreateTurningCtor(TypeDeclaration teamDecl, MethodBinding superTeamCtor,
        AstGenerator gen) {
    // constructor chains are created during resolve, so super team must be resolved.
    Dependencies.ensureTeamState(teamDecl.binding.superclass().getTeamModel(),
            ITranslationStates.STATE_RESOLVED);

    boolean hasMarkerArg = (superTeamCtor.parameters.length > 0
            && TSuperHelper.isMarkerInterface(superTeamCtor.parameters[superTeamCtor.parameters.length - 1]));

    TypeBinding[] newParams = superTeamCtor.parameters;
    if (!hasMarkerArg) {
        TypeBinding markerType = TSuperHelper.getMarkerInterface(teamDecl.scope, superTeamCtor.declaringClass);
        newParams = AstEdit.extendTypeArray(superTeamCtor.parameters, markerType);
    }

    // do we need to work at all?
    MethodBinding existingCtor = teamDecl.binding.getExactConstructor(newParams);
    if (existingCtor != null)
        return existingCtor;

    // start creating:
    Argument[] arguments = AstConverter.createArgumentsFromParameters(superTeamCtor.parameters, gen);
    ConstructorDeclaration newCtor = gen.constructor(teamDecl.compilationResult, ClassFileConstants.AccPublic,
            teamDecl.name, arguments);
    // arguments
    if (!hasMarkerArg) {
        TSuperHelper.addMarkerArg(newCtor, superTeamCtor.declaringClass);
        arguments = newCtor.arguments;
    }
    // constructor call
    newCtor.constructorCall = new ExplicitConstructorCall(ExplicitConstructorCall.Super);
    int length = superTeamCtor.parameters.length;// as many as the target (super) expects.
    Expression[] selfcallArgs = new Expression[length];
    for (int i = 0; i < length; i++) {
        selfcallArgs[i] = gen.singleNameReference(arguments[i].name);
    }
    newCtor.constructorCall.arguments = selfcallArgs;
    // empty body
    newCtor.setStatements(new Statement[0]);

    newCtor.isTSuper = true; // no matter if new or old marker arg
    AstEdit.addMethod(teamDecl, newCtor);

    return newCtor.binding;
}

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

License:Open Source License

/**
 * @param baseClassBinding/*  www.j  a  v a 2  s .c  o m*/
 * @param liftToConstructorDeclaration generated constructor
 * @param baseArgName name of the base argument, either generated or from source
* @param gen for generating AST nodes
 */
private static void genLiftToConstructorSuperCall(ReferenceBinding baseClassBinding, TypeDeclaration roleType,
        ConstructorDeclaration liftToConstructorDeclaration, char[] baseArgName, AstGenerator gen) {
    liftToConstructorDeclaration.constructorCall = gen.explicitConstructorCall(ExplicitConstructorCall.Super);
    // mode maybe refined in ExplicitConstructorCall.resolve()->updateFromTSuper()
    liftToConstructorDeclaration.constructorCall.arguments = new Expression[] {
            gen.singleNameReference(baseArgName) };
    // start with an empty statements list, except for this._OT$InitFields();
    liftToConstructorDeclaration.setStatements(new Statement[] {
            RoleInitializationMethod.genInvokeInitMethod(gen.thisReference(), roleType.binding, gen) });
}

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

License:Open Source License

private void genLiftToConstructorStatements(ReferenceBinding baseClassBinding, TypeDeclaration roleType,
        ConstructorDeclaration liftToConstructorDeclaration, char[] baseArgName, AstGenerator gen) {
    liftToConstructorDeclaration.constructorCall = gen.explicitConstructorCall(ExplicitConstructorCall.Super);
    boolean useRoleCache = RoleModel.getInstantiationPolicy(roleType.binding).isOndemand();
    Statement[] statements = new Statement[useRoleCache ? 4 : 2];
    // _OT$base = <baseArgName>;
    SingleNameReference lhs = gen.singleNameReference(_OT_BASE);
    statements[0] = gen.assignment(lhs, gen.singleNameReference(baseArgName));

    int idx = 1;//  w w  w.  j ava 2  s  .  c  om
    if (useRoleCache) {
        Statement[] regStats = genRoleRegistrationStatements(this._boundRootRoleModel.getAst().scope,
                this._boundRootRoleModel, baseClassBinding, liftToConstructorDeclaration, gen);
        System.arraycopy(regStats, 0, statements, idx, regStats.length);
        idx += 2;
    }

    // after initializing _OT$base and storing in the cache we are ready to execute field initializers:

    // this._OT$InitFields();
    statements[idx] = RoleInitializationMethod.genInvokeInitMethod(gen.thisReference(), roleType.binding, gen);
    liftToConstructorDeclaration.setStatements(statements);
}