Example usage for org.eclipse.jdt.internal.compiler.ast ParameterizedQualifiedTypeReference ParameterizedQualifiedTypeReference

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

Introduction

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

Prototype

public ParameterizedQualifiedTypeReference(char[][] tokens, TypeReference[][] typeArguments, int dim,
        long[] positions) 

Source Link

Usage

From source file:lombok.eclipse.handlers.ast.EclipseASTMaker.java

License:Open Source License

@Override
public ASTNode visitTypeRef(final lombok.ast.TypeRef node, final Void p) {
    final TypeReference[] paramTypes = build(node.getTypeArgs()).toArray(new TypeReference[0]);
    final TypeReference typeReference;
    if (node.getTypeName().equals("void")) {
        typeReference = new SingleTypeReference(TypeBinding.VOID.simpleName, 0);
    } else if (node.getTypeName().contains(".")) {
        final char[][] typeNameTokens = fromQualifiedName(node.getTypeName());
        long[] poss = new long[typeNameTokens.length];
        Arrays.fill(poss, 0);/*from  w w w. j  av a 2  s. co m*/
        if (Is.notEmpty(paramTypes)) {
            final TypeReference[][] typeArguments = new TypeReference[typeNameTokens.length][];
            typeArguments[typeNameTokens.length - 1] = paramTypes;
            typeReference = new ParameterizedQualifiedTypeReference(typeNameTokens, typeArguments, 0, poss);
        } else {
            if (node.getDims() > 0) {
                typeReference = new ArrayQualifiedTypeReference(typeNameTokens, node.getDims(), poss);
            } else {
                typeReference = new QualifiedTypeReference(typeNameTokens, poss);
            }
        }
    } else {
        final char[] typeNameToken = node.getTypeName().toCharArray();
        if (Is.notEmpty(paramTypes)) {
            typeReference = new ParameterizedSingleTypeReference(typeNameToken, paramTypes, 0, 0);
        } else {
            if (node.getDims() > 0) {
                typeReference = new ArrayTypeReference(typeNameToken, node.getDims(), 0);
            } else {
                typeReference = new SingleTypeReference(typeNameToken, 0);
            }
        }
    }
    setGeneratedByAndCopyPos(typeReference, source, posHintOf(node));
    if (node.isSuperType())
        typeReference.bits |= IsSuperType;
    return typeReference;
}

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

License:Open Source License

/**
 * You can't share TypeReference objects or subtle errors start happening.
 * Unfortunately the TypeReference type hierarchy is complicated and there's no clone
 * method on TypeReference itself. This method can clone them.
 */// w ww.  j  a v  a  2  s.c  o  m
public static TypeReference copyType(TypeReference ref, ASTNode source) {
    if (ref instanceof ParameterizedQualifiedTypeReference) {
        ParameterizedQualifiedTypeReference iRef = (ParameterizedQualifiedTypeReference) ref;
        TypeReference[][] args = null;
        if (iRef.typeArguments != null) {
            args = new TypeReference[iRef.typeArguments.length][];
            int idx = 0;
            for (TypeReference[] inRefArray : iRef.typeArguments) {
                if (inRefArray == null)
                    args[idx++] = null;
                else {
                    TypeReference[] outRefArray = new TypeReference[inRefArray.length];
                    int idx2 = 0;
                    for (TypeReference inRef : inRefArray) {
                        outRefArray[idx2++] = copyType(inRef, source);
                    }
                    args[idx++] = outRefArray;
                }
            }
        }

        TypeReference typeRef = new ParameterizedQualifiedTypeReference(iRef.tokens, args, iRef.dimensions(),
                copy(iRef.sourcePositions));
        if (source != null)
            setGeneratedBy(typeRef, source);
        return typeRef;
    }

    if (ref instanceof ArrayQualifiedTypeReference) {
        ArrayQualifiedTypeReference iRef = (ArrayQualifiedTypeReference) ref;
        TypeReference typeRef = new ArrayQualifiedTypeReference(iRef.tokens, iRef.dimensions(),
                copy(iRef.sourcePositions));
        if (source != null)
            setGeneratedBy(typeRef, source);
        return typeRef;
    }

    if (ref instanceof QualifiedTypeReference) {
        QualifiedTypeReference iRef = (QualifiedTypeReference) ref;
        TypeReference typeRef = new QualifiedTypeReference(iRef.tokens, copy(iRef.sourcePositions));
        if (source != null)
            setGeneratedBy(typeRef, source);
        return typeRef;
    }

    if (ref instanceof ParameterizedSingleTypeReference) {
        ParameterizedSingleTypeReference iRef = (ParameterizedSingleTypeReference) ref;
        TypeReference[] args = null;
        if (iRef.typeArguments != null) {
            args = new TypeReference[iRef.typeArguments.length];
            int idx = 0;
            for (TypeReference inRef : iRef.typeArguments) {
                if (inRef == null)
                    args[idx++] = null;
                else
                    args[idx++] = copyType(inRef, source);
            }
        }

        TypeReference typeRef = new ParameterizedSingleTypeReference(iRef.token, args, iRef.dimensions(),
                (long) iRef.sourceStart << 32 | iRef.sourceEnd);
        if (source != null)
            setGeneratedBy(typeRef, source);
        return typeRef;
    }

    if (ref instanceof ArrayTypeReference) {
        ArrayTypeReference iRef = (ArrayTypeReference) ref;
        TypeReference typeRef = new ArrayTypeReference(iRef.token, iRef.dimensions(),
                (long) iRef.sourceStart << 32 | iRef.sourceEnd);
        if (source != null)
            setGeneratedBy(typeRef, source);
        return typeRef;
    }

    if (ref instanceof Wildcard) {
        Wildcard original = (Wildcard) ref;

        Wildcard wildcard = new Wildcard(original.kind);
        wildcard.sourceStart = original.sourceStart;
        wildcard.sourceEnd = original.sourceEnd;
        if (original.bound != null)
            wildcard.bound = copyType(original.bound, source);
        if (source != null)
            setGeneratedBy(wildcard, source);
        return wildcard;
    }

    if (ref instanceof SingleTypeReference) {
        SingleTypeReference iRef = (SingleTypeReference) ref;
        TypeReference typeRef = new SingleTypeReference(iRef.token,
                (long) iRef.sourceStart << 32 | iRef.sourceEnd);
        if (source != null)
            setGeneratedBy(typeRef, source);
        return typeRef;
    }

    return ref;
}

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

License:Open Source License

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

    // Primitives

    char[] base = null;

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

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

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

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

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

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

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

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

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

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

    char[][] parts;

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

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

    boolean isParamized = false;

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

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

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

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

License:Open Source License

public Statement[] createLazyGetterBody(ASTNode source, EclipseNode fieldNode) {
    /*/*  w ww .  java  2  s  .  c o m*/
    java.lang.Object value = this.fieldName.get();
    if (value == null) {
       synchronized (this.fieldName) {
    value = this.fieldName.get();
    if (value == null) {
       final RawValueType actualValue = INITIALIZER_EXPRESSION;
       [IF PRIMITIVE]
       value = actualValue;
       [ELSE]
       value = actualValue == null ? this.fieldName : actualValue;
       [END IF]
       this.fieldName.set(value);
    }
       }
    }
    [IF PRIMITIVE]
    return (BoxedValueType) value;
    [ELSE]
    return (BoxedValueType) (value == this.fieldName ? null : value);
    [END IF]
    */

    FieldDeclaration field = (FieldDeclaration) fieldNode.get();
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    TypeReference rawComponentType = copyType(field.type, source);
    TypeReference boxedComponentType = null;
    boolean isPrimitive = false;
    if (field.type instanceof SingleTypeReference && !(field.type instanceof ArrayTypeReference)) {
        char[][] newType = TYPE_MAP.get(new String(((SingleTypeReference) field.type).token));
        if (newType != null) {
            boxedComponentType = new QualifiedTypeReference(newType, poss(source, 3));
            isPrimitive = true;
        }
    }
    if (boxedComponentType == null)
        boxedComponentType = copyType(field.type, source);
    boxedComponentType.sourceStart = pS;
    boxedComponentType.sourceEnd = boxedComponentType.statementEnd = pE;

    Statement[] statements = new Statement[3];

    /* java.lang.Object value = this.fieldName.get(); */ {
        LocalDeclaration valueDecl = new LocalDeclaration(valueName, pS, pE);
        valueDecl.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(source, 3));
        valueDecl.type.sourceStart = pS;
        valueDecl.type.sourceEnd = valueDecl.type.statementEnd = pE;

        MessageSend getter = new MessageSend();
        getter.sourceStart = pS;
        getter.statementEnd = getter.sourceEnd = pE;
        getter.selector = new char[] { 'g', 'e', 't' };
        getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);

        valueDecl.initialization = getter;
        statements[0] = valueDecl;
    }

    /*
    if (value == null) {
       synchronized (this.fieldName) {
    value = this.fieldName.get();
    if (value == null) { 
       final ValueType actualValue = INITIALIZER_EXPRESSION;
       [IF PRIMITIVE]
       value = actualValue;
       [ELSE]
       value = actualValue == null ? this.fieldName : actualValue;
       [END IF]
       this.fieldName.set(value);
    }
       }
    }
     */ {
        EqualExpression cond = new EqualExpression(new SingleNameReference(valueName, p),
                new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL);
        Block then = new Block(0);
        Expression lock = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
        Block inner = new Block(0);
        inner.statements = new Statement[2];
        /* value = this.fieldName.get(); */ {
            MessageSend getter = new MessageSend();
            getter.sourceStart = pS;
            getter.sourceEnd = getter.statementEnd = pE;
            getter.selector = new char[] { 'g', 'e', 't' };
            getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
            Assignment assign = new Assignment(new SingleNameReference(valueName, p), getter, pE);
            assign.sourceStart = pS;
            assign.statementEnd = assign.sourceEnd = pE;
            inner.statements[0] = assign;
        }
        /* if (value == null) */ {
            EqualExpression innerCond = new EqualExpression(new SingleNameReference(valueName, p),
                    new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL);
            innerCond.sourceStart = pS;
            innerCond.sourceEnd = innerCond.statementEnd = pE;
            Block innerThen = new Block(0);
            innerThen.statements = new Statement[3];
            /* final ValueType actualValue = INITIALIZER_EXPRESSION */ {
                LocalDeclaration actualValueDecl = new LocalDeclaration(actualValueName, pS, pE);
                actualValueDecl.type = rawComponentType;
                actualValueDecl.type.sourceStart = pS;
                actualValueDecl.type.sourceEnd = actualValueDecl.type.statementEnd = pE;
                actualValueDecl.initialization = field.initialization;
                actualValueDecl.modifiers = ClassFileConstants.AccFinal;
                innerThen.statements[0] = actualValueDecl;
            }
            /* [IF PRIMITIVE] value = actualValue; */ {
                if (isPrimitive) {
                    Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p),
                            new SingleNameReference(actualValueName, p), pE);
                    innerAssign.sourceStart = pS;
                    innerAssign.statementEnd = innerAssign.sourceEnd = pE;
                    innerThen.statements[1] = innerAssign;
                }
            }
            /* [ELSE] value = actualValue == null ? this.fieldName : actualValue; */ {
                if (!isPrimitive) {
                    EqualExpression avIsNull = new EqualExpression(new SingleNameReference(actualValueName, p),
                            new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL);
                    avIsNull.sourceStart = pS;
                    avIsNull.sourceEnd = avIsNull.statementEnd = pE;
                    Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
                    ConditionalExpression ternary = new ConditionalExpression(avIsNull, fieldRef,
                            new SingleNameReference(actualValueName, p));
                    ternary.sourceStart = pS;
                    ternary.sourceEnd = ternary.statementEnd = pE;
                    Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p), ternary, pE);
                    innerAssign.sourceStart = pS;
                    innerAssign.statementEnd = innerAssign.sourceEnd = pE;
                    innerThen.statements[1] = innerAssign;
                }
            }

            /* this.fieldName.set(value); */ {
                MessageSend setter = new MessageSend();
                setter.sourceStart = pS;
                setter.sourceEnd = setter.statementEnd = pE;
                setter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
                setter.selector = new char[] { 's', 'e', 't' };
                setter.arguments = new Expression[] { new SingleNameReference(valueName, p) };
                innerThen.statements[2] = setter;
            }

            IfStatement innerIf = new IfStatement(innerCond, innerThen, pS, pE);
            inner.statements[1] = innerIf;
        }

        SynchronizedStatement sync = new SynchronizedStatement(lock, inner, pS, pE);
        then.statements = new Statement[] { sync };

        IfStatement ifStatement = new IfStatement(cond, then, pS, pE);
        statements[1] = ifStatement;
    }

    /* [IF PRIMITIVE] return (BoxedValueType)value; */ {
        if (isPrimitive) {
            CastExpression cast = makeCastExpression(new SingleNameReference(valueName, p), boxedComponentType,
                    source);
            statements[2] = new ReturnStatement(cast, pS, pE);
        }
    }
    /* [ELSE] return (BoxedValueType)(value == this.fieldName ? null : value); */ {
        if (!isPrimitive) {
            EqualExpression vIsThisFieldName = new EqualExpression(new SingleNameReference(valueName, p),
                    createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source),
                    BinaryExpression.EQUAL_EQUAL);
            vIsThisFieldName.sourceStart = pS;
            vIsThisFieldName.sourceEnd = vIsThisFieldName.statementEnd = pE;
            ConditionalExpression ternary = new ConditionalExpression(vIsThisFieldName, new NullLiteral(pS, pE),
                    new SingleNameReference(valueName, p));
            ternary.sourceStart = pS;
            ternary.sourceEnd = ternary.statementEnd = pE;
            ternary.bits |= PARENTHESIZED;
            CastExpression cast = makeCastExpression(ternary, boxedComponentType, source);
            statements[2] = new ReturnStatement(cast, pS, pE);
        }
    }

    // update the field type and init last

    /*    private final java.util.concurrent.atomic.AtomicReference<java.lang.Object> fieldName = new java.util.concurrent.atomic.AtomicReference<java.lang.Object>(); */ {
        TypeReference innerType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(source, 3));
        TypeReference[][] typeParams = new TypeReference[5][];
        typeParams[4] = new TypeReference[] { innerType };
        TypeReference type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5));

        // Some magic here
        type.sourceStart = -1;
        type.sourceEnd = -2;

        field.type = type;
        AllocationExpression init = new AllocationExpression();
        // Some magic here
        init.sourceStart = field.initialization.sourceStart;
        init.sourceEnd = init.statementEnd = field.initialization.sourceEnd;
        init.type = copyType(type, source);
        field.initialization = init;
    }
    return statements;
}

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

License:Open Source License

private static MethodDeclaration createSetReferencedObjectMethod(FieldDeclaration fieldDecl, ASTNode source,
        String relatedFieldName, boolean isOneToOne, boolean isUnique, TypeReference baseType,
        TypeReference referenceType, CompilationUnitDeclaration compilationUnitDeclaration) {
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    TypeReference refType = fieldDecl.type;

    if (isUnique) {
        refType = new ParameterizedQualifiedTypeReference(Eclipse.fromQualifiedName(List.class.getName()),
                new TypeReference[][] { null, null, new TypeReference[] { refType } }, 0,
                new long[] { p, p, p });
        setGeneratedBy(refType, source);
        refType.sourceStart = pS;//from  ww  w  . j a v a2 s .c  o  m
        refType.sourceEnd = pE;
    }

    MethodDeclaration setReferencedObject = new MethodDeclaration(compilationUnitDeclaration.compilationResult);
    setGeneratedBy(setReferencedObject, source);
    setReferencedObject.modifiers = ClassFileConstants.AccPublic;
    setReferencedObject.annotations = new Annotation[] {
            makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source) };
    setReferencedObject.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0);
    setReferencedObject.returnType.sourceStart = pS;
    setReferencedObject.returnType.sourceEnd = pE;
    setReferencedObject.arguments = new Argument[] {
            new Argument("item".toCharArray(), 0, baseType, ClassFileConstants.AccFinal),
            new Argument("related".toCharArray(), 0, refType, ClassFileConstants.AccFinal), };
    setGeneratedBy(setReferencedObject.arguments[0], source);
    setGeneratedBy(setReferencedObject.arguments[1], source);
    setReferencedObject.arguments[0].sourceStart = pS;
    setReferencedObject.arguments[0].sourceEnd = pE;
    setReferencedObject.arguments[1].sourceStart = pS;
    setReferencedObject.arguments[1].sourceEnd = pE;
    setReferencedObject.selector = "setReferencedObject".toCharArray();
    setReferencedObject.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    setReferencedObject.bodyStart = setReferencedObject.declarationSourceStart = setReferencedObject.sourceStart = source.sourceStart;
    setReferencedObject.bodyEnd = setReferencedObject.declarationSourceEnd = setReferencedObject.sourceEnd = source.sourceEnd;

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

    SingleNameReference fieldNameRef = new SingleNameReference("related".toCharArray(), p);
    setGeneratedBy(fieldNameRef, source);
    Expression fieldRef = createFieldAccessor(new String(fieldDecl.name), source, "item".toCharArray());
    setGeneratedBy(fieldRef, source);
    fieldRef.sourceStart = pS;
    fieldRef.sourceEnd = pE;

    if (isUnique) {
        MessageSend get = new MessageSend();
        setGeneratedBy(get, source);
        get.sourceStart = pS;
        get.sourceEnd = get.statementEnd = pE;
        get.receiver = new ThisReference(pS, pE);
        get.selector = "firstOrDefault".toCharArray();
        get.arguments = new Expression[] { fieldNameRef };

        Assignment assignment = new Assignment(fieldRef, get, pE);
        setGeneratedBy(assignment, source);
        assignment.sourceStart = pS;
        assignment.sourceEnd = assignment.statementEnd = pE;

        statements.add(assignment);
    } else {
        Assignment assignment = new Assignment(fieldRef, fieldNameRef, pE);
        assignment.sourceStart = pS;
        assignment.sourceEnd = assignment.statementEnd = pE;
        setGeneratedBy(assignment, source);
        statements.add(assignment);
    }

    setReferencedObject.statements = statements.toArray(new Statement[statements.size()]);

    return setReferencedObject;
}

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

License:Open Source License

@Override
public void handle(AnnotationValues<SuperBuilder> annotation, Annotation ast, EclipseNode annotationNode) {
    handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.SUPERBUILDER_FLAG_USAGE, "@SuperBuilder");

    long p = (long) ast.sourceStart << 32 | ast.sourceEnd;

    SuperBuilder superbuilderAnnotation = annotation.getInstance();

    String builderMethodName = superbuilderAnnotation.builderMethodName();
    String buildMethodName = superbuilderAnnotation.buildMethodName();

    if (builderMethodName == null)
        builderMethodName = "builder";
    if (buildMethodName == null)
        buildMethodName = "build";

    boolean generateBuilderMethod;
    if (builderMethodName.isEmpty()) {
        generateBuilderMethod = false;//  w ww.  j  a  v  a  2s. c  om
    } else if (!checkName("builderMethodName", builderMethodName, annotationNode)) {
        return;
    } else {
        generateBuilderMethod = true;
    }
    if (!checkName("buildMethodName", buildMethodName, annotationNode))
        return;

    boolean toBuilder = superbuilderAnnotation.toBuilder();

    EclipseNode tdParent = annotationNode.up();

    java.util.List<BuilderFieldData> builderFields = new ArrayList<BuilderFieldData>();
    TypeReference returnType;
    TypeParameter[] typeParams;

    boolean addCleaning = false;

    if (!(tdParent.get() instanceof TypeDeclaration)) {
        annotationNode.addError("@SuperBuilder is only supported on types.");
        return;
    }
    TypeDeclaration td = (TypeDeclaration) tdParent.get();

    // Gather all fields of the class that should be set by the builder.
    List<EclipseNode> allFields = new ArrayList<EclipseNode>();
    List<EclipseNode> nonFinalNonDefaultedFields = null;

    boolean valuePresent = (hasAnnotation(lombok.Value.class, tdParent)
            || hasAnnotation("lombok.experimental.Value", tdParent));
    for (EclipseNode fieldNode : HandleConstructor.findAllFields(tdParent, true)) {
        FieldDeclaration fd = (FieldDeclaration) fieldNode.get();
        EclipseNode isDefault = findAnnotation(Builder.Default.class, fieldNode);
        boolean isFinal = ((fd.modifiers & ClassFileConstants.AccFinal) != 0)
                || (valuePresent && !hasAnnotation(NonFinal.class, fieldNode));

        Annotation[] copyableAnnotations = findCopyableAnnotations(fieldNode);

        BuilderFieldData bfd = new BuilderFieldData();
        bfd.rawName = fieldNode.getName().toCharArray();
        bfd.name = removePrefixFromField(fieldNode);
        bfd.annotations = copyAnnotations(fd, copyableAnnotations);
        bfd.type = fd.type;
        bfd.singularData = getSingularData(fieldNode, ast);
        bfd.originalFieldNode = fieldNode;

        if (bfd.singularData != null && isDefault != null) {
            isDefault.addError("@Builder.Default and @Singular cannot be mixed.");
            isDefault = null;
        }

        if (fd.initialization == null && isDefault != null) {
            isDefault.addWarning("@Builder.Default requires an initializing expression (' = something;').");
            isDefault = null;
        }

        if (fd.initialization != null && isDefault == null) {
            if (isFinal)
                continue;
            if (nonFinalNonDefaultedFields == null)
                nonFinalNonDefaultedFields = new ArrayList<EclipseNode>();
            nonFinalNonDefaultedFields.add(fieldNode);
        }

        if (isDefault != null) {
            bfd.nameOfDefaultProvider = prefixWith(DEFAULT_PREFIX, bfd.name);
            bfd.nameOfSetFlag = prefixWith(bfd.name, SET_PREFIX);

            MethodDeclaration md = HandleBuilder.generateDefaultProvider(bfd.nameOfDefaultProvider,
                    td.typeParameters, fieldNode, ast);
            if (md != null)
                injectMethod(tdParent, md);
        }
        addObtainVia(bfd, fieldNode);
        builderFields.add(bfd);
        allFields.add(fieldNode);
    }

    // Set the names of the builder classes.
    String builderClassName = String.valueOf(td.name) + "Builder";
    String builderImplClassName = builderClassName + "Impl";

    typeParams = td.typeParameters != null ? td.typeParameters : new TypeParameter[0];
    returnType = namePlusTypeParamsToTypeReference(td.name, typeParams, p);

    // <C, B> are the generics for our builder.
    String classGenericName = "C";
    String builderGenericName = "B";
    // If these generics' names collide with any generics on the annotated class, modify them.
    // For instance, if there are generics <B, B2, C> on the annotated class, use "C2" and "B3" for our builder.
    java.util.List<String> typeParamStrings = new ArrayList<String>();
    for (TypeParameter typeParam : typeParams)
        typeParamStrings.add(typeParam.toString());
    classGenericName = generateNonclashingNameFor(classGenericName, typeParamStrings);
    builderGenericName = generateNonclashingNameFor(builderGenericName, typeParamStrings);

    TypeReference extendsClause = td.superclass;
    TypeReference superclassBuilderClass = null;
    TypeReference[] typeArguments = new TypeReference[] {
            new SingleTypeReference(classGenericName.toCharArray(), 0),
            new SingleTypeReference(builderGenericName.toCharArray(), 0) };
    if (extendsClause instanceof QualifiedTypeReference) {
        QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) extendsClause;
        String superclassClassName = String.valueOf(qualifiedTypeReference.getLastToken());
        String superclassBuilderClassName = superclassClassName + "Builder";

        char[][] tokens = Arrays.copyOf(qualifiedTypeReference.tokens,
                qualifiedTypeReference.tokens.length + 1);
        tokens[tokens.length] = superclassBuilderClassName.toCharArray();
        long[] poss = new long[tokens.length];
        Arrays.fill(poss, p);

        TypeReference[] superclassTypeArgs = getTypeParametersFrom(extendsClause);

        // Every token may potentially have type args. Here, we only have
        // type args for the last token, the superclass' builder.
        TypeReference[][] typeArgsForTokens = new TypeReference[tokens.length][];
        typeArgsForTokens[typeArgsForTokens.length - 1] = mergeTypeReferences(superclassTypeArgs,
                typeArguments);

        superclassBuilderClass = new ParameterizedQualifiedTypeReference(tokens, typeArgsForTokens, 0, poss);
    } else if (extendsClause != null) {
        String superClass = String.valueOf(extendsClause.getTypeName()[0]);
        String superclassBuilderClassName = superClass + "Builder";

        char[][] tokens = new char[][] { superClass.toCharArray(), superclassBuilderClassName.toCharArray() };
        long[] poss = new long[tokens.length];
        Arrays.fill(poss, p);

        TypeReference[] superclassTypeArgs = getTypeParametersFrom(extendsClause);

        // Every token may potentially have type args. Here, we only have
        // type args for the last token, the superclass' builder.
        TypeReference[][] typeArgsForTokens = new TypeReference[tokens.length][];
        typeArgsForTokens[typeArgsForTokens.length - 1] = mergeTypeReferences(superclassTypeArgs,
                typeArguments);

        superclassBuilderClass = new ParameterizedQualifiedTypeReference(tokens, typeArgsForTokens, 0, poss);
    }
    // If there is no superclass, superclassBuilderClassExpression is still == null at this point.
    // You can use it to check whether to inherit or not.

    generateBuilderBasedConstructor(tdParent, typeParams, builderFields, annotationNode, builderClassName,
            superclassBuilderClass != null);

    // Create the abstract builder class, or reuse an existing one.
    EclipseNode builderType = findInnerClass(tdParent, builderClassName);
    if (builderType == null) {
        builderType = generateBuilderAbstractClass(tdParent, builderClassName, superclassBuilderClass,
                typeParams, ast, classGenericName, builderGenericName);
    } else {
        TypeDeclaration builderTypeDeclaration = (TypeDeclaration) builderType.get();
        if ((builderTypeDeclaration.modifiers
                & (ClassFileConstants.AccStatic | ClassFileConstants.AccAbstract)) == 0) {
            annotationNode.addError("Existing Builder must be an abstract static inner class.");
            return;
        }
        sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderType, annotationNode);
        // Generate errors for @Singular BFDs that have one already defined node.
        for (BuilderFieldData bfd : builderFields) {
            SingularData sd = bfd.singularData;
            if (sd == null)
                continue;
            EclipseSingularizer singularizer = sd.getSingularizer();
            if (singularizer == null)
                continue;
            if (singularizer.checkForAlreadyExistingNodesAndGenerateError(builderType, sd)) {
                bfd.singularData = null;
            }
        }
    }

    // Check validity of @ObtainVia fields, and add check if adding cleaning for @Singular is necessary.
    for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            if (bfd.singularData.getSingularizer().requiresCleaning()) {
                addCleaning = true;
                break;
            }
        }
        if (bfd.obtainVia != null) {
            if (bfd.obtainVia.field().isEmpty() == bfd.obtainVia.method().isEmpty()) {
                bfd.obtainViaNode.addError(
                        "The syntax is either @ObtainVia(field = \"fieldName\") or @ObtainVia(method = \"methodName\").");
                return;
            }
            if (bfd.obtainVia.method().isEmpty() && bfd.obtainVia.isStatic()) {
                bfd.obtainViaNode
                        .addError("@ObtainVia(isStatic = true) is not valid unless 'method' has been set.");
                return;
            }
        }
    }

    // Generate the fields in the abstract builder class that hold the values for the instance.
    generateBuilderFields(builderType, builderFields, ast);
    if (addCleaning) {
        FieldDeclaration cleanDecl = new FieldDeclaration(CLEAN_FIELD_NAME, 0, -1);
        cleanDecl.declarationSourceEnd = -1;
        cleanDecl.modifiers = ClassFileConstants.AccPrivate;
        cleanDecl.type = TypeReference.baseTypeReference(TypeIds.T_boolean, 0);
        injectFieldAndMarkGenerated(builderType, cleanDecl);
    }

    if (toBuilder) {
        // Generate $fillValuesFrom() method in the abstract builder.
        injectMethod(builderType, generateFillValuesMethod(tdParent, superclassBuilderClass != null,
                builderGenericName, classGenericName, builderClassName, typeParams));
        // Generate $fillValuesFromInstanceIntoBuilder() method in the builder implementation class.
        injectMethod(builderType,
                generateStaticFillValuesMethod(tdParent, builderClassName, typeParams, builderFields, ast));
    }

    // Generate abstract self() and build() methods in the abstract builder.
    injectMethod(builderType,
            generateAbstractSelfMethod(tdParent, superclassBuilderClass != null, builderGenericName));
    injectMethod(builderType, generateAbstractBuildMethod(tdParent, buildMethodName,
            superclassBuilderClass != null, classGenericName, ast));

    // Create the setter methods in the abstract builder.
    for (BuilderFieldData bfd : builderFields) {
        generateSetterMethodsForBuilder(builderType, bfd, annotationNode, builderGenericName);
    }

    // Create the toString() method for the abstract builder.
    if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) {
        List<Included<EclipseNode, ToString.Include>> fieldNodes = new ArrayList<Included<EclipseNode, ToString.Include>>();
        for (BuilderFieldData bfd : builderFields) {
            for (EclipseNode f : bfd.createdFields) {
                fieldNodes.add(new Included<EclipseNode, ToString.Include>(f, null, true));
            }
        }
        // Let toString() call super.toString() if there is a superclass, so that it also shows fields from the superclass' builder.
        MethodDeclaration md = HandleToString.createToString(builderType, fieldNodes, true,
                superclassBuilderClass != null, ast, FieldAccess.ALWAYS_FIELD);
        if (md != null) {
            injectMethod(builderType, md);
        }
    }

    if (addCleaning)
        injectMethod(builderType, generateCleanMethod(builderFields, builderType, ast));

    boolean isAbstract = (td.modifiers & ClassFileConstants.AccAbstract) != 0;
    if (isAbstract) {
        // Only non-abstract classes get the Builder implementation.
        return;
    }

    // Create the builder implementation class, or reuse an existing one.
    EclipseNode builderImplType = findInnerClass(tdParent, builderImplClassName);
    if (builderImplType == null) {
        builderImplType = generateBuilderImplClass(tdParent, builderImplClassName, builderClassName, typeParams,
                ast);
    } else {
        TypeDeclaration builderImplTypeDeclaration = (TypeDeclaration) builderImplType.get();
        if ((builderImplTypeDeclaration.modifiers & ClassFileConstants.AccAbstract) != 0
                || (builderImplTypeDeclaration.modifiers & ClassFileConstants.AccStatic) == 0) {
            annotationNode.addError("Existing BuilderImpl must be a non-abstract static inner class.");
            return;
        }
        sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(builderImplType, annotationNode);
    }

    if (toBuilder) {
        // Add the toBuilder() method to the annotated class.
        switch (methodExists(TO_BUILDER_METHOD_NAME_STRING, tdParent, 0)) {
        case EXISTS_BY_USER:
            annotationNode.addWarning("Not generating toBuilder() as it already exists.");
            break;
        case NOT_EXISTS:
            injectMethod(tdParent,
                    generateToBuilderMethod(builderClassName, builderImplClassName, tdParent, typeParams, ast));
        default:
            // Should not happen.
        }
    }

    // Create the self() and build() methods in the BuilderImpl.
    injectMethod(builderImplType, generateSelfMethod(builderImplType, typeParams, p));
    if (methodExists(buildMethodName, builderImplType, -1) == MemberExistsResult.NOT_EXISTS) {
        injectMethod(builderImplType, generateBuildMethod(tdParent, buildMethodName, returnType, ast));
    }

    // Add the builder() method to the annotated class.
    if (generateBuilderMethod && methodExists(builderMethodName, tdParent, -1) != MemberExistsResult.NOT_EXISTS)
        generateBuilderMethod = false;
    if (generateBuilderMethod) {
        MethodDeclaration md = generateBuilderMethod(builderMethodName, builderClassName, builderImplClassName,
                tdParent, typeParams, ast);
        if (md != null)
            injectMethod(tdParent, md);
    }

    if (nonFinalNonDefaultedFields != null && generateBuilderMethod) {
        for (EclipseNode fieldNode : nonFinalNonDefaultedFields) {
            fieldNode.addWarning(
                    "@SuperBuilder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.");
        }
    }
}

From source file:org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.java

License:Open Source License

private TypeReference createTypeReferenceForClassNode(ClassNode classNode) {
    int start = startOffset(classNode);
    int end = endOffset(classNode);

    List<TypeReference> typeArguments = null;

    // need to distinguish between raw usage of a type 'List' and generics
    // usage 'List<T>' -
    // it basically depends upon whether the type variable reference can be
    // resolved within the current 'scope' - if it cannot then this is probably a raw
    // reference (yes?)

    if (classNode.isUsingGenerics()) {
        GenericsType[] genericsInfo = classNode.getGenericsTypes();
        if (genericsInfo != null) {
            for (int g = 0; g < genericsInfo.length; g++) {
                // ClassNode typeArgumentClassNode = genericsInfo[g].getType();
                TypeReference tr = createTypeReferenceForClassNode(genericsInfo[g]);
                if (tr != null) {
                    if (typeArguments == null) {
                        typeArguments = new ArrayList<TypeReference>();
                    }//from w w w .  ja  v a 2s. co m
                    typeArguments.add(tr);
                }
                // if (!typeArgumentClassNode.isGenericsPlaceHolder()) {
                // typeArguments.add(createTypeReferenceForClassNode(typeArgumentClassNode));
                // }
            }
        }
    }

    String name = classNode.getName();

    if (name.length() == 1 && name.charAt(0) == '?') {
        return new Wildcard(Wildcard.UNBOUND);
    }

    int arrayLoc = name.indexOf("[");
    if (arrayLoc == 0) {
        return createTypeReferenceForArrayNameLeadingBrackets(classNode, start, end);
    } else if (arrayLoc > 0) {
        return createTypeReferenceForArrayNameTrailingBrackets(classNode, start, end);
    }

    if (nameToPrimitiveTypeId.containsKey(name)) {
        return TypeReference.baseTypeReference(nameToPrimitiveTypeId.get(name), 0);
    }

    if (name.indexOf(".") == -1) {
        if (typeArguments == null) {
            TypeReference tr = verify(new SingleTypeReference(name.toCharArray(), toPos(start, end - 1)));

            if (!checkGenerics) {
                tr.bits |= TypeReference.IgnoreRawTypeCheck;
            }
            return tr;
        } else {
            // FIXASC determine when array dimension used in this case,
            // is it 'A<T[]> or some silliness?
            long l = toPos(start, end - 1);
            return new ParameterizedSingleTypeReference(name.toCharArray(),
                    typeArguments.toArray(new TypeReference[typeArguments.size()]), 0, l);
        }
    } else {
        char[][] compoundName = CharOperation.splitOn('.', name.toCharArray());
        if (typeArguments == null) {
            TypeReference tr = new QualifiedTypeReference(compoundName, positionsFor(compoundName, start, end));
            if (!checkGenerics) {
                tr.bits |= TypeReference.IgnoreRawTypeCheck;
            }
            return tr;
        } else {
            // FIXASC support individual parameterization of component
            // references A<String>.B<Wibble>
            TypeReference[][] typeReferences = new TypeReference[compoundName.length][];
            typeReferences[compoundName.length - 1] = typeArguments
                    .toArray(new TypeReference[typeArguments.size()]);
            return new ParameterizedQualifiedTypeReference(compoundName, typeReferences, 0,
                    positionsFor(compoundName, start, end));
        }
    }
}

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

License:Open Source License

/**
 * Recursively converts from an aj type reference to a JDT type reference.
 * This class is not involved with Content assist and code select, so the CompletionOn* and SelectionOn* variants of
 * type references should not make it here.
 * @param ajRef/*  w ww.  ja  v  a 2  s .c  om*/
 * @return jdtRef
 */
private TypeReference convertToJDTTypeReference(
        org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference ajRef) {
    if (ajRef == null) {
        return null;
    }
    TypeReference jdtRef = null;
    if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocImplicitTypeReference) {
        org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocImplicitTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocImplicitTypeReference) ajRef;
        jdtRef = new JavadocImplicitTypeReference(castedAJ.token, castedAJ.sourceStart);
    } else if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) {
        if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference) {
            if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference) {
                org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference) ajRef;
                jdtRef = new JavadocArrayQualifiedTypeReference(
                        new JavadocQualifiedTypeReference(castedAJ.tokens, castedAJ.sourcePositions,
                                castedAJ.tagSourceStart, castedAJ.tagSourceEnd),
                        castedAJ.dimensions());
            } else if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference) {
                org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference) ajRef;
                jdtRef = new ParameterizedQualifiedTypeReference(castedAJ.tokens,
                        convertDoubleArray(castedAJ.typeArguments), castedAJ.dimensions(),
                        castedAJ.sourcePositions);
            } else { // assume vanilla ArrayQualifiedTypeReference
                org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference) ajRef;
                jdtRef = new ArrayQualifiedTypeReference(castedAJ.tokens, castedAJ.dimensions(),
                        castedAJ.sourcePositions);
            }
        } else if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocQualifiedTypeReference) {
            org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocQualifiedTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocQualifiedTypeReference) ajRef;
            jdtRef = new JavadocQualifiedTypeReference(castedAJ.tokens, castedAJ.sourcePositions,
                    castedAJ.tagSourceStart, castedAJ.tagSourceEnd);
        } else { // assume vanilla QualifiedTypeReference
            org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) ajRef;
            jdtRef = new QualifiedTypeReference(castedAJ.tokens, castedAJ.sourcePositions);
        }
    } else if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference) {
        if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference) {
            if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocArraySingleTypeReference) {
                org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocArraySingleTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocArraySingleTypeReference) ajRef;
                jdtRef = new JavadocArraySingleTypeReference(castedAJ.token, castedAJ.dimensions,
                        toPos(castedAJ.sourceStart, castedAJ.sourceEnd));
            } else if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference) {
                org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference) ajRef;
                jdtRef = new ParameterizedSingleTypeReference(castedAJ.token,
                        convertSingleArray(castedAJ.typeArguments), castedAJ.dimensions,
                        toPos(castedAJ.sourceStart, castedAJ.sourceEnd));
            } else { // assume vanilla ArrayTypeReference
                org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference) ajRef;
                jdtRef = new ArrayTypeReference(castedAJ.token, castedAJ.dimensions,
                        toPos(castedAJ.sourceStart, castedAJ.sourceEnd));
            }
        } else if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocSingleTypeReference) {
            org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocSingleTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.JavadocSingleTypeReference) ajRef;
            jdtRef = new JavadocSingleTypeReference(castedAJ.token,
                    toPos(castedAJ.sourceStart, castedAJ.sourceEnd), castedAJ.tagSourceStart,
                    castedAJ.tagSourceEnd);
        } else { // assume vanilla SingleTypeReference
            org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference) ajRef;
            jdtRef = new SingleTypeReference(castedAJ.token, toPos(castedAJ.sourceStart, castedAJ.sourceEnd));
        }
    } else if (ajRef instanceof org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard) {
        org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard castedAJ = (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard) ajRef;
        Wildcard castedJDT = new Wildcard(castedAJ.kind);
        castedJDT.bound = convertToJDTTypeReference(castedAJ.bound);
        jdtRef = castedJDT;
    }

    Assert.isNotNull(jdtRef, "Conversion to JDT type reference failed.  Original AJ type reference is: '"
            + ajRef + "' and class '" + ajRef.getClass() + "'");

    // now fill in the rest of the shared fields.  Not all of them will be applicable in all cases
    jdtRef.bits = ajRef.bits;
    jdtRef.implicitConversion = ajRef.implicitConversion;
    jdtRef.statementEnd = ajRef.statementEnd;

    return jdtRef;
}

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

License:Open Source License

protected ParameterizedQualifiedTypeReference computeQualifiedGenericsFromRightSide(TypeReference rightSide,
        int dim) {
    int nameSize = this.identifierLengthStack[this.identifierLengthPtr];
    int tokensSize = nameSize;
    if (rightSide instanceof ParameterizedSingleTypeReference) {
        tokensSize++;/*from w w  w.ja v a2  s.c  om*/
    } else if (rightSide instanceof SingleTypeReference) {
        tokensSize++;
    } else if (rightSide instanceof ParameterizedQualifiedTypeReference) {
        tokensSize += ((QualifiedTypeReference) rightSide).tokens.length;
    } else if (rightSide instanceof QualifiedTypeReference) {
        tokensSize += ((QualifiedTypeReference) rightSide).tokens.length;
    }
    TypeReference[][] typeArguments = new TypeReference[tokensSize][];
    char[][] tokens = new char[tokensSize][];
    long[] positions = new long[tokensSize];
    if (rightSide instanceof ParameterizedSingleTypeReference) {
        ParameterizedSingleTypeReference singleParameterizedTypeReference = (ParameterizedSingleTypeReference) rightSide;
        tokens[nameSize] = singleParameterizedTypeReference.token;
        positions[nameSize] = (((long) singleParameterizedTypeReference.sourceStart) << 32)
                + singleParameterizedTypeReference.sourceEnd;
        typeArguments[nameSize] = singleParameterizedTypeReference.typeArguments;
    } else if (rightSide instanceof SingleTypeReference) {
        SingleTypeReference singleTypeReference = (SingleTypeReference) rightSide;
        tokens[nameSize] = singleTypeReference.token;
        positions[nameSize] = (((long) singleTypeReference.sourceStart) << 32) + singleTypeReference.sourceEnd;
    } else if (rightSide instanceof ParameterizedQualifiedTypeReference) {
        ParameterizedQualifiedTypeReference parameterizedTypeReference = (ParameterizedQualifiedTypeReference) rightSide;
        TypeReference[][] rightSideTypeArguments = parameterizedTypeReference.typeArguments;
        System.arraycopy(rightSideTypeArguments, 0, typeArguments, nameSize, rightSideTypeArguments.length);
        char[][] rightSideTokens = parameterizedTypeReference.tokens;
        System.arraycopy(rightSideTokens, 0, tokens, nameSize, rightSideTokens.length);
        long[] rightSidePositions = parameterizedTypeReference.sourcePositions;
        System.arraycopy(rightSidePositions, 0, positions, nameSize, rightSidePositions.length);
    } else if (rightSide instanceof QualifiedTypeReference) {
        QualifiedTypeReference qualifiedTypeReference = (QualifiedTypeReference) rightSide;
        char[][] rightSideTokens = qualifiedTypeReference.tokens;
        System.arraycopy(rightSideTokens, 0, tokens, nameSize, rightSideTokens.length);
        long[] rightSidePositions = qualifiedTypeReference.sourcePositions;
        System.arraycopy(rightSidePositions, 0, positions, nameSize, rightSidePositions.length);
    }

    int currentTypeArgumentsLength = this.genericsLengthStack[this.genericsLengthPtr--];
    TypeReference[] currentTypeArguments = new TypeReference[currentTypeArgumentsLength];
    this.genericsPtr -= currentTypeArgumentsLength;
    System.arraycopy(this.genericsStack, this.genericsPtr + 1, currentTypeArguments, 0,
            currentTypeArgumentsLength);

    if (nameSize == 1) {
        tokens[0] = this.identifierStack[this.identifierPtr];
        positions[0] = this.identifierPositionStack[this.identifierPtr--];
        typeArguments[0] = currentTypeArguments;
    } else {
        this.identifierPtr -= nameSize;
        System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens, 0, nameSize);
        System.arraycopy(this.identifierPositionStack, this.identifierPtr + 1, positions, 0, nameSize);
        typeArguments[nameSize - 1] = currentTypeArguments;
    }
    this.identifierLengthPtr--;
    return new ParameterizedQualifiedTypeReference(tokens, typeArguments, dim, positions);
}

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

License:Open Source License

protected TypeReference getTypeReferenceForGenericType(int dim, int identifierLength, int numberOfIdentifiers) {
    if (identifierLength == 1 && numberOfIdentifiers == 1) {
        int currentTypeArgumentsLength = this.genericsLengthStack[this.genericsLengthPtr--];
        TypeReference[] typeArguments = null;
        if (currentTypeArgumentsLength < 0) {
            typeArguments = TypeReference.NO_TYPE_ARGUMENTS;
        } else {//from w  ww  . java 2 s  . c om
            typeArguments = new TypeReference[currentTypeArgumentsLength];
            this.genericsPtr -= currentTypeArgumentsLength;
            System.arraycopy(this.genericsStack, this.genericsPtr + 1, typeArguments, 0,
                    currentTypeArgumentsLength);
        }
        ParameterizedSingleTypeReference parameterizedSingleTypeReference = new ParameterizedSingleTypeReference(
                this.identifierStack[this.identifierPtr], typeArguments, dim,
                this.identifierPositionStack[this.identifierPtr--]);
        if (dim != 0) {
            parameterizedSingleTypeReference.sourceEnd = this.endStatementPosition;
        }
        /* We used to eagerly mark the PSTR as constituting diamond usage if we encountered <>, but that is too eager and
           complicates error handling by making it hard to distinguish legitimate use cases from ill formed ones. We are
           more discriminating now and tag a type as being diamond only where <> can legally occur. 
           See https://bugs.eclipse.org/bugs/show_bug.cgi?id=339478#c11
        */
        return parameterizedSingleTypeReference;
    } else {
        TypeReference[][] typeArguments = new TypeReference[numberOfIdentifiers][];
        char[][] tokens = new char[numberOfIdentifiers][];
        long[] positions = new long[numberOfIdentifiers];
        int index = numberOfIdentifiers;
        int currentIdentifiersLength = identifierLength;
        while (index > 0) {
            int currentTypeArgumentsLength = this.genericsLengthStack[this.genericsLengthPtr--];
            if (currentTypeArgumentsLength > 0) {
                this.genericsPtr -= currentTypeArgumentsLength;
                System.arraycopy(this.genericsStack, this.genericsPtr + 1,
                        typeArguments[index - 1] = new TypeReference[currentTypeArgumentsLength], 0,
                        currentTypeArgumentsLength);
            } else if (currentTypeArgumentsLength < 0) {
                // diamond case for qualified type reference (java.util.ArrayList<>)
                typeArguments[index - 1] = TypeReference.NO_TYPE_ARGUMENTS;
            }
            switch (currentIdentifiersLength) {
            case 1:
                // we are in a case A<B>.C<D> or A<B>.C<D>
                tokens[index - 1] = this.identifierStack[this.identifierPtr];
                positions[index - 1] = this.identifierPositionStack[this.identifierPtr--];
                break;
            default:
                // we are in a case A.B.C<B>.C<D> or A.B.C<B>...
                this.identifierPtr -= currentIdentifiersLength;
                System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens,
                        index - currentIdentifiersLength, currentIdentifiersLength);
                System.arraycopy(this.identifierPositionStack, this.identifierPtr + 1, positions,
                        index - currentIdentifiersLength, currentIdentifiersLength);
            }
            index -= currentIdentifiersLength;
            if (index > 0) {
                currentIdentifiersLength = this.identifierLengthStack[this.identifierLengthPtr--];
            }
        }
        ParameterizedQualifiedTypeReference parameterizedQualifiedTypeReference = new ParameterizedQualifiedTypeReference(
                tokens, typeArguments, dim, positions);
        if (dim != 0) {
            parameterizedQualifiedTypeReference.sourceEnd = this.endStatementPosition;
        }
        /* We used to eagerly mark the PQTR as constituting diamond usage if we encountered <>, but that is too eager and
           complicates error handling by making it hard to distinguish legitimate use cases from ill formed ones. We are
           more discriminating now and tag a type as being diamond only where <> can legally occur. 
           See https://bugs.eclipse.org/bugs/show_bug.cgi?id=339478#c11
        */
        return parameterizedQualifiedTypeReference;
    }
}