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

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

Introduction

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

Prototype

public TypeDeclaration(CompilationResult compilationResult) 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private TypeDeclaration convert(SourceType typeHandle, CompilationResult compilationResult)
        throws JavaModelException {
    SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) typeHandle.getElementInfo();
    if (typeInfo.isAnonymousMember())
        throw new AnonymousMemberFound();
    /* create type declaration - can be member type */
    TypeDeclaration type = new TypeDeclaration(compilationResult);
    if (typeInfo.getEnclosingType() == null) {
        if (typeHandle.isAnonymous()) {
            type.name = CharOperation.NO_CHAR;
            type.bits |= (ASTNode.IsAnonymousType | ASTNode.IsLocalType);
        } else {/*from  w w w.  ja v a 2  s.c o m*/
            if (typeHandle.isLocal()) {
                type.bits |= ASTNode.IsLocalType;
            }
        }
    } else {
        type.bits |= ASTNode.IsMemberType;
    }
    if ((type.bits & ASTNode.IsAnonymousType) == 0) {
        type.name = typeInfo.getName();
    }
    type.name = typeInfo.getName();
    int start, end; // only positions available
    type.sourceStart = start = typeInfo.getNameSourceStart();
    type.sourceEnd = end = typeInfo.getNameSourceEnd();
    type.modifiers = typeInfo.getModifiers();
    type.declarationSourceStart = typeInfo.getDeclarationSourceStart();
    type.declarationSourceEnd = typeInfo.getDeclarationSourceEnd();
    type.bodyEnd = type.declarationSourceEnd;

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {
        /* convert annotations */
        type.annotations = convertAnnotations(typeHandle);
    }
    /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=324850, even in a 1.4 project, we
       must internalize type variables and observe any parameterization of super class
       and/or super interfaces in order to be able to detect overriding in the presence
       of generics.
     */
    char[][] typeParameterNames = typeInfo.getTypeParameterNames();
    if (typeParameterNames.length > 0) {
        int parameterCount = typeParameterNames.length;
        char[][][] typeParameterBounds = typeInfo.getTypeParameterBounds();
        type.typeParameters = new TypeParameter[parameterCount];
        for (int i = 0; i < parameterCount; i++) {
            type.typeParameters[i] = createTypeParameter(typeParameterNames[i], typeParameterBounds[i], start,
                    end);
        }
    }

    /* set superclass and superinterfaces */
    if (typeInfo.getSuperclassName() != null) {
        type.superclass = createTypeReference(typeInfo.getSuperclassName(), start, end,
                true /* include generics */);
        type.superclass.bits |= ASTNode.IsSuperType;
    }
    char[][] interfaceNames = typeInfo.getInterfaceNames();
    int interfaceCount = interfaceNames == null ? 0 : interfaceNames.length;
    if (interfaceCount > 0) {
        type.superInterfaces = new TypeReference[interfaceCount];
        for (int i = 0; i < interfaceCount; i++) {
            type.superInterfaces[i] = createTypeReference(interfaceNames[i], start, end,
                    true /* include generics */);
            type.superInterfaces[i].bits |= ASTNode.IsSuperType;
        }
    }
    /* convert member types */
    if ((this.flags & MEMBER_TYPE) != 0) {
        SourceType[] sourceMemberTypes = typeInfo.getMemberTypeHandles();
        int sourceMemberTypeCount = sourceMemberTypes.length;
        type.memberTypes = new TypeDeclaration[sourceMemberTypeCount];
        for (int i = 0; i < sourceMemberTypeCount; i++) {
            type.memberTypes[i] = convert(sourceMemberTypes[i], compilationResult);
            type.memberTypes[i].enclosingType = type;
        }
    }

    /* convert intializers and fields*/
    InitializerElementInfo[] initializers = null;
    int initializerCount = 0;
    if ((this.flags & LOCAL_TYPE) != 0) {
        initializers = typeInfo.getInitializers();
        initializerCount = initializers.length;
    }
    SourceField[] sourceFields = null;
    int sourceFieldCount = 0;
    if ((this.flags & FIELD) != 0) {
        sourceFields = typeInfo.getFieldHandles();
        sourceFieldCount = sourceFields.length;
    }
    int length = initializerCount + sourceFieldCount;
    if (length > 0) {
        type.fields = new FieldDeclaration[length];
        for (int i = 0; i < initializerCount; i++) {
            type.fields[i] = convert(initializers[i], compilationResult);
        }
        int index = 0;
        for (int i = initializerCount; i < length; i++) {
            type.fields[i] = convert(sourceFields[index++], type, compilationResult);
        }
    }

    /* convert methods - need to add default constructor if necessary */
    boolean needConstructor = (this.flags & CONSTRUCTOR) != 0;
    boolean needMethod = (this.flags & METHOD) != 0;
    if (needConstructor || needMethod) {

        SourceMethod[] sourceMethods = typeInfo.getMethodHandles();
        int sourceMethodCount = sourceMethods.length;

        /* source type has a constructor ?           */
        /* by default, we assume that one is needed. */
        int extraConstructor = 0;
        int methodCount = 0;
        int kind = TypeDeclaration.kind(type.modifiers);
        boolean isAbstract = kind == TypeDeclaration.INTERFACE_DECL
                || kind == TypeDeclaration.ANNOTATION_TYPE_DECL;
        if (!isAbstract) {
            extraConstructor = needConstructor ? 1 : 0;
            for (int i = 0; i < sourceMethodCount; i++) {
                if (sourceMethods[i].isConstructor()) {
                    if (needConstructor) {
                        extraConstructor = 0; // Does not need the extra constructor since one constructor already exists.
                        methodCount++;
                    }
                } else if (needMethod) {
                    methodCount++;
                }
            }
        } else {
            methodCount = needMethod ? sourceMethodCount : 0;
        }
        type.methods = new AbstractMethodDeclaration[methodCount + extraConstructor];
        if (extraConstructor != 0) { // add default constructor in first position
            type.methods[0] = type.createDefaultConstructor(false, false);
        }
        int index = 0;
        boolean hasAbstractMethods = false;
        for (int i = 0; i < sourceMethodCount; i++) {
            SourceMethod sourceMethod = sourceMethods[i];
            SourceMethodElementInfo methodInfo = (SourceMethodElementInfo) sourceMethod.getElementInfo();
            boolean isConstructor = methodInfo.isConstructor();
            if ((methodInfo.getModifiers() & ClassFileConstants.AccAbstract) != 0) {
                hasAbstractMethods = true;
            }
            if ((isConstructor && needConstructor) || (!isConstructor && needMethod)) {
                AbstractMethodDeclaration method = convert(sourceMethod, methodInfo, compilationResult);
                if (isAbstract || method.isAbstract()) { // fix-up flag
                    method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
                }
                type.methods[extraConstructor + index++] = method;
            }
        }
        if (hasAbstractMethods)
            type.bits |= ASTNode.HasAbstractMethods;
    }

    return type;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.BinaryTypeConverter.java

License:Open Source License

private TypeDeclaration convert(IType type, IType alreadyComputedMember,
        TypeDeclaration alreadyComputedMemberDeclaration) throws JavaModelException {
    /* create type declaration - can be member type */
    TypeDeclaration typeDeclaration = new TypeDeclaration(this.compilationResult);

    if (type.getDeclaringType() != null) {
        typeDeclaration.bits |= ASTNode.IsMemberType;
    }/*from w  w  w.  ja  v a 2s .  c  o m*/
    typeDeclaration.name = type.getElementName().toCharArray();
    typeDeclaration.modifiers = type.getFlags();

    /* set superclass and superinterfaces */
    if (type.getSuperclassName() != null) {
        TypeReference typeReference = createTypeReference(type.getSuperclassTypeSignature());
        if (typeReference != null) {
            typeDeclaration.superclass = typeReference;
            typeDeclaration.superclass.bits |= ASTNode.IsSuperType;
        }
    }

    String[] interfaceTypes = type.getSuperInterfaceTypeSignatures();
    int interfaceCount = interfaceTypes == null ? 0 : interfaceTypes.length;
    typeDeclaration.superInterfaces = new TypeReference[interfaceCount];
    int count = 0;
    for (int i = 0; i < interfaceCount; i++) {
        TypeReference typeReference = createTypeReference(interfaceTypes[i]);
        if (typeReference != null) {
            typeDeclaration.superInterfaces[count] = typeReference;
            typeDeclaration.superInterfaces[count++].bits |= ASTNode.IsSuperType;
        }
    }
    if (count != interfaceCount) {
        System.arraycopy(typeDeclaration.fields, 0,
                typeDeclaration.superInterfaces = new TypeReference[interfaceCount], 0, interfaceCount);
    }

    // convert 1.5 specific constructs only if compliance is 1.5 or above
    if (this.has1_5Compliance) {

        /* convert type parameters */
        ITypeParameter[] typeParameters = type.getTypeParameters();
        if (typeParameters != null && typeParameters.length > 0) {
            int parameterCount = typeParameters.length;
            org.eclipse.jdt.internal.compiler.ast.TypeParameter[] typeParams = new org.eclipse.jdt.internal.compiler.ast.TypeParameter[parameterCount];
            for (int i = 0; i < parameterCount; i++) {
                ITypeParameter typeParameter = typeParameters[i];
                typeParams[i] = createTypeParameter(typeParameter.getElementName().toCharArray(),
                        stringArrayToCharArray(typeParameter.getBounds()), 0, 0);
            }

            typeDeclaration.typeParameters = typeParams;
        }
    }

    /* convert member types */
    IType[] memberTypes = type.getTypes();
    int memberTypeCount = memberTypes == null ? 0 : memberTypes.length;
    typeDeclaration.memberTypes = new TypeDeclaration[memberTypeCount];
    for (int i = 0; i < memberTypeCount; i++) {
        if (alreadyComputedMember != null && alreadyComputedMember.getFullyQualifiedName()
                .equals(memberTypes[i].getFullyQualifiedName())) {
            typeDeclaration.memberTypes[i] = alreadyComputedMemberDeclaration;
        } else {
            typeDeclaration.memberTypes[i] = convert(memberTypes[i], null, null);
        }
        typeDeclaration.memberTypes[i].enclosingType = typeDeclaration;
    }

    /* convert fields */
    IField[] fields = type.getFields();
    int fieldCount = fields == null ? 0 : fields.length;
    typeDeclaration.fields = new FieldDeclaration[fieldCount];
    count = 0;
    for (int i = 0; i < fieldCount; i++) {
        FieldDeclaration fieldDeclaration = convert(fields[i], type);
        if (fieldDeclaration != null) {
            typeDeclaration.fields[count++] = fieldDeclaration;
        }
    }
    if (count != fieldCount) {
        System.arraycopy(typeDeclaration.fields, 0, typeDeclaration.fields = new FieldDeclaration[count], 0,
                count);
    }

    /* convert methods - need to add default constructor if necessary */
    IMethod[] methods = type.getMethods();
    int methodCount = methods == null ? 0 : methods.length;

    /* source type has a constructor ?           */
    /* by default, we assume that one is needed. */
    int neededCount = 1;
    for (int i = 0; i < methodCount; i++) {
        if (methods[i].isConstructor()) {
            neededCount = 0;
            // Does not need the extra constructor since one constructor already exists.
            break;
        }
    }
    boolean isInterface = type.isInterface();
    neededCount = isInterface ? 0 : neededCount;
    typeDeclaration.methods = new AbstractMethodDeclaration[methodCount + neededCount];
    if (neededCount != 0) { // add default constructor in first position
        typeDeclaration.methods[0] = typeDeclaration.createDefaultConstructor(false, false);
    }
    boolean hasAbstractMethods = false;
    count = 0;
    for (int i = 0; i < methodCount; i++) {
        AbstractMethodDeclaration method = convert(methods[i], type);
        if (method != null) {
            boolean isAbstract;
            if ((isAbstract = method.isAbstract()) || isInterface) { // fix-up flag
                method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody;
            }
            if (isAbstract) {
                hasAbstractMethods = true;
            }
            typeDeclaration.methods[neededCount + (count++)] = method;
        }
    }
    if (count != methodCount) {
        System.arraycopy(typeDeclaration.methods, 0,
                typeDeclaration.methods = new AbstractMethodDeclaration[count + neededCount], 0,
                count + neededCount);
    }
    if (hasAbstractMethods) {
        typeDeclaration.bits |= ASTNode.HasAbstractMethods;
    }
    return typeDeclaration;
}

From source file:com.google.gwt.dev.javac.BinaryTypeReferenceRestrictionsCheckerTest.java

License:Apache License

/**
 * Creates a mock {@link CompilationUnitDeclaration} that has binary type
 * references in a superclass reference, in a method return type, in an
 * annotation and in a local variable declaration. It then checks that the we
 * find all of these locations except for the one used in an annotation.
 *//*from   ww  w.j a  va  2s . c o m*/
public void testFindAllBinaryTypeReferenceSites() {
    CompilationResult compilationResult = new CompilationResult("TestCompilationUnit.java".toCharArray(), 0, 0,
            0);
    CompilationUnitDeclaration cud = new CompilationUnitDeclaration(null, compilationResult, 1);
    LookupEnvironment lookupEnvironment = createMockLookupEnvironment();
    cud.scope = new CompilationUnitScope(cud, lookupEnvironment);

    TypeDeclaration typeDeclaration = new TypeDeclaration(compilationResult);
    typeDeclaration.scope = new ClassScope(cud.scope, null);
    typeDeclaration.staticInitializerScope = new MethodScope(typeDeclaration.scope, null, false);
    cud.types = new TypeDeclaration[] { typeDeclaration };

    BinaryTypeBinding binaryTypeBinding = new BinaryTypeBinding(null, new MockBinaryType(BINARY_TYPE_NAME),
            lookupEnvironment);
    typeDeclaration.superclass = createMockBinaryTypeReference(binaryTypeBinding);

    MethodDeclaration methodDeclaration = new MethodDeclaration(compilationResult);
    methodDeclaration.scope = new MethodScope(typeDeclaration.scope, null, false);
    methodDeclaration.returnType = createMockBinaryTypeReference(binaryTypeBinding);

    LocalDeclaration localDeclaration = new LocalDeclaration(null, 0, 0);
    localDeclaration.type = createMockBinaryTypeReference(binaryTypeBinding);
    methodDeclaration.statements = new Statement[] { localDeclaration };

    SingleMemberAnnotation annotation = new SingleMemberAnnotation(
            createMockBinaryTypeReference(binaryTypeBinding), 0);
    annotation.memberValue = annotation.type;
    typeDeclaration.annotations = new Annotation[] { annotation };

    typeDeclaration.methods = new AbstractMethodDeclaration[] { methodDeclaration };

    /*
     * Check that we find binary type references in the following expected
     * locations.
     */
    Expression[] expectedExpressions = new Expression[] { typeDeclaration.superclass,
            methodDeclaration.returnType, localDeclaration.type };

    List<BinaryTypeReferenceSite> binaryTypeReferenceSites = BinaryTypeReferenceRestrictionsChecker
            .findAllBinaryTypeReferenceSites(cud);
    assertEquals(expectedExpressions.length, binaryTypeReferenceSites.size());
    for (int i = 0; i < binaryTypeReferenceSites.size(); ++i) {
        BinaryTypeReferenceSite binaryTypeReferenceSite = binaryTypeReferenceSites.get(i);
        assertSame(binaryTypeBinding, binaryTypeReferenceSite.getBinaryTypeBinding());
        assertSame(expectedExpressions[i], binaryTypeReferenceSite.getExpression());
    }
}

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

License:Open Source License

@Override
public ASTNode visitClassDecl(final lombok.ast.ClassDecl node, final Void p) {
    final TypeDeclaration typeDeclaration = new TypeDeclaration(
            ((CompilationUnitDeclaration) sourceNode.top().get()).compilationResult);
    setGeneratedByAndCopyPos(typeDeclaration, source, posHintOf(node));
    typeDeclaration.modifiers = modifiersFor(node.getModifiers());
    if (node.isInterface())
        typeDeclaration.modifiers |= AccInterface;
    typeDeclaration.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    if (node.isLocal())
        typeDeclaration.bits |= ASTNode.IsLocalType;
    if (node.isAnonymous()) {
        typeDeclaration.bits |= ASTNode.IsAnonymousType;
    }//from   ww  w  .  j ava2s  .  co m
    if (Is.empty(node.getName())) {
        typeDeclaration.name = CharOperation.NO_CHAR;
    } else {
        typeDeclaration.name = node.getName().toCharArray();
    }
    typeDeclaration.annotations = toArray(build(node.getAnnotations()), new Annotation[0]);
    typeDeclaration.typeParameters = toArray(build(node.getTypeParameters()), new TypeParameter[0]);
    typeDeclaration.fields = toArray(build(node.getFields()), new FieldDeclaration[0]);
    typeDeclaration.methods = toArray(build(node.getMethods()), new AbstractMethodDeclaration[0]);
    typeDeclaration.memberTypes = toArray(build(node.getMemberTypes()), new TypeDeclaration[0]);
    typeDeclaration.superInterfaces = toArray(build(node.getSuperInterfaces()), new TypeReference[0]);
    typeDeclaration.superclass = build(node.getSuperclass());
    for (final FieldDeclaration field : Each.elementIn(typeDeclaration.fields)) {
        if (isEnumConstant(field) || (field.modifiers & Modifier.STATIC) != 0) {
            typeDeclaration.addClinit();
            break;
        }
    }
    return typeDeclaration;
}

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

License:Open Source License

public EclipseNode makeBuilderClass(EclipseNode tdParent, String builderClassName, TypeParameter[] typeParams,
        ASTNode source) {/* w w w.ja  va 2s . co m*/
    TypeDeclaration parent = (TypeDeclaration) tdParent.get();
    TypeDeclaration builder = new TypeDeclaration(parent.compilationResult);
    builder.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
    builder.modifiers |= ClassFileConstants.AccPublic | ClassFileConstants.AccStatic;
    builder.typeParameters = copyTypeParams(typeParams, source);
    builder.name = builderClassName.toCharArray();
    builder.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
    return injectType(tdParent, builder);
}

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

License:Open Source License

private void createInnerTypeFieldNameConstants(EclipseNode typeNode, EclipseNode errorNode, ASTNode source,
        AccessLevel level, List<EclipseNode> fields, boolean asEnum, String innerTypeName) {
    if (fields.isEmpty())
        return;//from  w  w w . ja  v  a  2 s.  c o  m

    ASTVisitor generatedByVisitor = new SetGeneratedByVisitor(source);
    TypeDeclaration parent = (TypeDeclaration) typeNode.get();
    EclipseNode fieldsType = findInnerClass(typeNode, innerTypeName);
    boolean genConstr = false, genClinit = false;
    char[] name = innerTypeName.toCharArray();
    TypeDeclaration generatedInnerType = null;
    if (fieldsType == null) {
        generatedInnerType = new TypeDeclaration(parent.compilationResult);
        generatedInnerType.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
        generatedInnerType.modifiers = toEclipseModifier(level) | (asEnum ? ClassFileConstants.AccEnum
                : (ClassFileConstants.AccStatic | ClassFileConstants.AccFinal));
        generatedInnerType.name = name;
        fieldsType = injectType(typeNode, generatedInnerType);
        genConstr = true;
        genClinit = asEnum;
        generatedInnerType.traverse(generatedByVisitor, ((TypeDeclaration) typeNode.get()).scope);
    } else {
        TypeDeclaration builderTypeDeclaration = (TypeDeclaration) fieldsType.get();
        if (asEnum && (builderTypeDeclaration.modifiers & ClassFileConstants.AccEnum) == 0) {
            errorNode.addError("Existing " + innerTypeName + " must be declared as an 'enum'.");
            return;
        }
        if (!asEnum && (builderTypeDeclaration.modifiers & ClassFileConstants.AccStatic) == 0) {
            errorNode.addError("Existing " + innerTypeName + " must be declared as a 'static class'.");
            return;
        }
        genConstr = constructorExists(fieldsType) == MemberExistsResult.NOT_EXISTS;
    }

    if (genConstr) {
        ConstructorDeclaration constructor = new ConstructorDeclaration(parent.compilationResult);
        constructor.selector = name;
        constructor.modifiers = ClassFileConstants.AccPrivate;
        ExplicitConstructorCall superCall = new ExplicitConstructorCall(0);
        superCall.sourceStart = source.sourceStart;
        superCall.sourceEnd = source.sourceEnd;
        superCall.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
        constructor.constructorCall = superCall;
        if (!asEnum)
            constructor.statements = new Statement[0];
        injectMethod(fieldsType, constructor);
    }

    if (genClinit) {
        Clinit cli = new Clinit(parent.compilationResult);
        injectMethod(fieldsType, cli);
        cli.traverse(generatedByVisitor, ((TypeDeclaration) fieldsType.get()).scope);
    }

    for (EclipseNode fieldNode : fields) {
        FieldDeclaration field = (FieldDeclaration) fieldNode.get();
        char[] fName = field.name;
        if (fieldExists(new String(fName), fieldsType) != MemberExistsResult.NOT_EXISTS)
            continue;
        int pS = source.sourceStart, pE = source.sourceEnd;
        long p = (long) pS << 32 | pE;
        FieldDeclaration constantField = new FieldDeclaration(fName, pS, pE);
        constantField.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
        if (asEnum) {
            AllocationExpression ac = new AllocationExpression();
            ac.enumConstant = constantField;
            ac.sourceStart = source.sourceStart;
            ac.sourceEnd = source.sourceEnd;
            constantField.initialization = ac;
            constantField.modifiers = 0;
        } else {
            constantField.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING,
                    new long[] { p, p, p });
            constantField.initialization = new StringLiteral(field.name, pS, pE, 0);
            constantField.modifiers = ClassFileConstants.AccPublic | ClassFileConstants.AccStatic
                    | ClassFileConstants.AccFinal;
        }
        injectField(fieldsType, constantField);
        constantField.traverse(generatedByVisitor, ((TypeDeclaration) fieldsType.get()).initializerScope);
    }
}

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

License:Open Source License

private static FieldDeclaration createField(Object anno, EclipseNode fieldNode, ASTNode source) {
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    FieldDeclaration result = null;/*from  ww w.  j  a  va 2s  . co m*/
    FieldDeclaration fieldDecl = (FieldDeclaration) fieldNode.get();

    String relatedFieldName = null;
    boolean isOneToOne = false;
    boolean isUnique = false;

    String baseTypeName = new String(((TypeDeclaration) fieldNode.up().get()).name);

    char[] qualifiedRelationTypeName = null;
    char[] singleRelationTypeName = null;
    TypeReference fieldType = null;
    TypeReference baseType = createTypeReference(baseTypeName.split("\\."), p);
    setGeneratedBy(baseType, source);
    TypeReference referenceType = fieldDecl.type;

    if (anno instanceof OneToOne) {
        isOneToOne = true;
        relatedFieldName = ((OneToOne) anno).field();

        qualifiedRelationTypeName = OneToOneRelation.class.getName().toCharArray();
        singleRelationTypeName = OneToOneRelation.class.getSimpleName().toCharArray();
    } else {
        relatedFieldName = ((OneToMany) anno).field();
        isUnique = ((OneToMany) anno).unique();

        if (referenceType instanceof ParameterizedSingleTypeReference) {
            referenceType = ((ParameterizedSingleTypeReference) referenceType).typeArguments[0];
        } else if (referenceType instanceof ParameterizedQualifiedTypeReference) {
            ParameterizedQualifiedTypeReference type = (ParameterizedQualifiedTypeReference) referenceType;
            referenceType = type.typeArguments[type.typeArguments.length - 1][0];
        }

        qualifiedRelationTypeName = OneToManyRelation.class.getName().toCharArray();
        singleRelationTypeName = OneToManyRelation.class.getSimpleName().toCharArray();
    }

    addImportIfNotExists((CompilationUnitDeclaration) fieldNode.top().get(), qualifiedRelationTypeName, source);

    fieldType = new ParameterizedSingleTypeReference(singleRelationTypeName,
            new TypeReference[] { baseType, referenceType }, 0, p);
    setGeneratedBy(fieldType, source);
    fieldType.sourceStart = pS;
    fieldType.sourceEnd = fieldType.statementEnd = pE;

    CompilationResult compResult = ((CompilationUnitDeclaration) fieldNode.top().get()).compilationResult;

    final TypeDeclaration typeDeclaration = new TypeDeclaration(compResult);
    setGeneratedBy(typeDeclaration, source);
    typeDeclaration.name = CharOperation.NO_CHAR;
    typeDeclaration.bits |= (ASTNode.IsAnonymousType | ASTNode.IsLocalType);
    typeDeclaration.bodyStart = source.sourceStart;
    typeDeclaration.bodyEnd = source.sourceEnd;
    typeDeclaration.declarationSourceStart = source.sourceStart;
    typeDeclaration.declarationSourceEnd = source.sourceEnd;
    typeDeclaration.methods = new AbstractMethodDeclaration[] {
            createGetReferencedKeyMethod(source, relatedFieldName, isOneToOne, baseType, referenceType,
                    compResult),
            createSetReferencedObjectMethod(fieldDecl, source, relatedFieldName, isOneToOne, isUnique, baseType,
                    referenceType, (CompilationUnitDeclaration) fieldNode.top().get()),
            createSetRelatedIdMethod(source, relatedFieldName, isOneToOne, baseType, referenceType,
                    compResult) };

    typeDeclaration.addClinit();

    QualifiedAllocationExpression allocation = new QualifiedAllocationExpression(typeDeclaration);
    setGeneratedBy(allocation, source);
    allocation.sourceStart = pS;
    allocation.sourceEnd = allocation.statementEnd = pE;
    allocation.type = fieldType;

    result = new FieldDeclaration(toUpperCase(new String(fieldDecl.name)).toCharArray(), 0, -1);
    setGeneratedBy(result, source);
    result.declarationSourceEnd = -1;
    result.type = fieldType;
    result.initialization = allocation;
    result.modifiers = ClassFileConstants.AccPrivate | ClassFileConstants.AccFinal
            | ClassFileConstants.AccStatic;

    return result;
}

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

License:Open Source License

private EclipseNode generateBuilderAbstractClass(EclipseNode tdParent, String builderClass,
        TypeReference superclassBuilderClass, TypeParameter[] typeParams, ASTNode source,
        String classGenericName, String builderGenericName) {

    TypeDeclaration parent = (TypeDeclaration) tdParent.get();
    TypeDeclaration builder = new TypeDeclaration(parent.compilationResult);
    builder.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
    builder.modifiers |= ClassFileConstants.AccPublic | ClassFileConstants.AccStatic
            | ClassFileConstants.AccAbstract;
    builder.name = builderClass.toCharArray();

    // Keep any type params of the annotated class.
    builder.typeParameters = Arrays.copyOf(copyTypeParams(typeParams, source), typeParams.length + 2);
    // Add builder-specific type params required for inheritable builders.
    // 1. The return type for the build() method, named "C", which extends the annotated class.
    TypeParameter o = new TypeParameter();
    o.name = classGenericName.toCharArray();
    o.type = cloneSelfType(tdParent, source);
    builder.typeParameters[builder.typeParameters.length - 2] = o;
    // 2. The return type for all setter methods, named "B", which extends this builder class.
    o = new TypeParameter();
    o.name = builderGenericName.toCharArray();
    TypeReference[] typerefs = appendBuilderTypeReferences(typeParams, classGenericName, builderGenericName);
    o.type = new ParameterizedSingleTypeReference(builderClass.toCharArray(), typerefs, 0, 0);
    builder.typeParameters[builder.typeParameters.length - 1] = o;

    builder.superclass = copyType(superclassBuilderClass, source);

    builder.createDefaultConstructor(false, true);

    builder.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
    return injectType(tdParent, builder);
}

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

License:Open Source License

private EclipseNode generateBuilderImplClass(EclipseNode tdParent, String builderImplClass,
        String builderAbstractClass, TypeParameter[] typeParams, ASTNode source) {
    TypeDeclaration parent = (TypeDeclaration) tdParent.get();
    TypeDeclaration builder = new TypeDeclaration(parent.compilationResult);
    builder.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
    builder.modifiers |= ClassFileConstants.AccPrivate | ClassFileConstants.AccStatic
            | ClassFileConstants.AccFinal;
    builder.name = builderImplClass.toCharArray();

    // Add type params if there are any.
    if (typeParams != null && typeParams.length > 0)
        builder.typeParameters = copyTypeParams(typeParams, source);

    if (builderAbstractClass != null) {
        // Extend the abstract builder.
        // 1. Add any type params of the annotated class.
        TypeReference[] typeArgs = new TypeReference[typeParams.length + 2];
        for (int i = 0; i < typeParams.length; i++) {
            typeArgs[i] = new SingleTypeReference(typeParams[i].name, 0);
        }/*from  w  w  w  .j a  va2s  .c  o m*/
        // 2. The return type for the build() method (named "C" in the abstract builder), which is the annotated class.
        // 3. The return type for all setter methods (named "B" in the abstract builder), which is this builder class.
        typeArgs[typeArgs.length - 2] = cloneSelfType(tdParent, source);
        typeArgs[typeArgs.length - 1] = createTypeReferenceWithTypeParameters(builderImplClass, typeParams);
        builder.superclass = new ParameterizedSingleTypeReference(builderAbstractClass.toCharArray(), typeArgs,
                0, 0);
    }

    builder.createDefaultConstructor(false, true);

    builder.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
    return injectType(tdParent, builder);
}

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

License:Open Source License

private TypeDeclaration createITIT(String name, TypeDeclaration enclosing) {
    TypeDeclaration decl = new TypeDeclaration(enclosing.compilationResult);
    decl.enclosingType = enclosing;// w w w.j  a  v  a  2  s.  c  o  m
    decl.name = name.toCharArray();
    ClassScope innerClassScope = new ClassScope(enclosing.scope, decl);
    decl.binding = new MemberTypeBinding(new char[][] { enclosing.name, name.toCharArray() }, innerClassScope,
            enclosing.binding);
    decl.staticInitializerScope = enclosing.staticInitializerScope;
    decl.initializerScope = enclosing.initializerScope;
    decl.scope = innerClassScope;
    decl.binding.superInterfaces = new ReferenceBinding[0];
    decl.binding.typeVariables = new TypeVariableBinding[0];
    decl.binding.memberTypes = new ReferenceBinding[0];
    decl.modifiers = Flags.AccPublic | Flags.AccStatic;
    decl.binding.modifiers = decl.modifiers;

    // also set the bindings, but may have to unset them as well.
    ReferenceBinding[] newBindings = new ReferenceBinding[enclosing.binding.memberTypes.length + 1];
    System.arraycopy(enclosing.binding.memberTypes, 0, newBindings, 0, enclosing.binding.memberTypes.length);
    newBindings[enclosing.binding.memberTypes.length] = decl.binding;
    enclosing.binding.memberTypes = newBindings;
    return decl;
}