Example usage for org.eclipse.jdt.internal.compiler.classfmt ClassFileConstants AccPrivate

List of usage examples for org.eclipse.jdt.internal.compiler.classfmt ClassFileConstants AccPrivate

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.classfmt ClassFileConstants AccPrivate.

Prototype

int AccPrivate

To view the source code for org.eclipse.jdt.internal.compiler.classfmt ClassFileConstants AccPrivate.

Click Source Link

Usage

From source file:ch.uzh.ifi.seal.changedistiller.ast.java.JavaASTHelper.java

License:Apache License

private boolean isPrivate(int ecjModifier) {
    return (ecjModifier & ClassFileConstants.AccPrivate) != 0;
}

From source file:com.android.tools.lint.psi.EcjPsiBuilder.java

License:Apache License

private EcjPsiModifierList toModifierList(@NonNull EcjPsiSourceElement parent, int modifiers,
        Annotation[] annotations) {
    int flags = 0;
    if ((modifiers & ClassFileConstants.AccStatic) != 0) {
        flags |= Modifier.STATIC;
    }//from   w  ww .  j av a  2 s . c  om
    if ((modifiers & ClassFileConstants.AccFinal) != 0) {
        flags |= Modifier.FINAL;
    }
    if ((modifiers & ClassFileConstants.AccAbstract) != 0) {
        flags |= Modifier.ABSTRACT;
    }
    if ((modifiers & ClassFileConstants.AccPrivate) != 0) {
        flags |= Modifier.PRIVATE;
    }
    if ((modifiers & ClassFileConstants.AccProtected) != 0) {
        flags |= Modifier.PROTECTED;
    }
    if ((modifiers & ClassFileConstants.AccPublic) != 0) {
        flags |= Modifier.PUBLIC;
    }
    if ((modifiers & ClassFileConstants.AccSynchronized) != 0) {
        flags |= Modifier.SYNCHRONIZED;
    }
    if ((modifiers & ClassFileConstants.AccVolatile) != 0) {
        flags |= Modifier.VOLATILE;
    }
    if ((modifiers & ExtraCompilerModifiers.AccDefaultMethod) != 0) {
        flags |= EcjPsiModifierList.DEFAULT_MASK;
    }

    EcjPsiModifierList modifierList = new EcjPsiModifierList(mManager, flags);
    parent.adoptChild(modifierList);
    EcjPsiAnnotation[] psiAnnotations = toAnnotations(modifierList, annotations);
    modifierList.setAnnotations(psiAnnotations);
    return modifierList;
}

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

License:Apache License

/**
 * Removes all members of a class to leave it as an empty stub.
 *///from  w  w  w  .  ja v  a 2s.c o m
private static void stripAllMembers(TypeDeclaration tyDecl) {
    tyDecl.superclass = null;
    tyDecl.superInterfaces = new TypeReference[0];
    tyDecl.annotations = new Annotation[0];
    tyDecl.methods = new AbstractMethodDeclaration[0];
    tyDecl.memberTypes = new TypeDeclaration[0];
    tyDecl.fields = new FieldDeclaration[0];
    if (TypeDeclaration.kind(tyDecl.modifiers) != TypeDeclaration.INTERFACE_DECL
            && TypeDeclaration.kind(tyDecl.modifiers) != TypeDeclaration.ENUM_DECL) {
        // Create a default constructor so that the class is proper.
        ConstructorDeclaration constructor = tyDecl.createDefaultConstructor(true, true);
        // Mark only constructor as private so that it can not be instantiated.
        constructor.modifiers = ClassFileConstants.AccPrivate;
        // Clear a bit that is used for marking the constructor as default as it makes JDT
        // assume that the constructor is public.
        constructor.bits &= ~ASTNode.IsDefaultConstructor;
        // Mark the class as final so that it can not be extended.
        tyDecl.modifiers |= ClassFileConstants.AccFinal;
        tyDecl.modifiers &= ~ClassFileConstants.AccAbstract;
    }
}

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

License:Open Source License

/**
 * Turns an {@code AccessLevel} instance into the flag bit used by eclipse.
 *///from w  w  w.j  a v  a 2  s . co m
public static int toEclipseModifier(AccessLevel value) {
    switch (value) {
    case MODULE:
    case PACKAGE:
        return 0;
    default:
    case PUBLIC:
        return ClassFileConstants.AccPublic;
    case PROTECTED:
        return ClassFileConstants.AccProtected;
    case NONE:
    case PRIVATE:
        return ClassFileConstants.AccPrivate;
    }
}

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

License:Open Source License

@Override
public void handle(AnnotationValues<Builder> annotation, Annotation ast, EclipseNode annotationNode) {
    long p = (long) ast.sourceStart << 32 | ast.sourceEnd;

    Builder builderInstance = annotation.getInstance();

    // These exist just to support the 'old' lombok.experimental.Builder, which had these properties. lombok.Builder no longer has them.
    boolean fluent = toBoolean(annotation.getActualExpression("fluent"), true);
    boolean chain = toBoolean(annotation.getActualExpression("chain"), true);

    String builderMethodName = builderInstance.builderMethodName();
    String buildMethodName = builderInstance.buildMethodName();
    String builderClassName = builderInstance.builderClassName();
    String toBuilderMethodName = "toBuilder";
    boolean toBuilder = builderInstance.toBuilder();
    List<char[]> typeArgsForToBuilder = null;

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

    if (!checkName("builderMethodName", builderMethodName, annotationNode))
        return;/*from   w  w w  .  java 2  s .c  o m*/
    if (!checkName("buildMethodName", buildMethodName, annotationNode))
        return;
    if (!builderClassName.isEmpty()) {
        if (!checkName("builderClassName", builderClassName, annotationNode))
            return;
    }

    EclipseNode parent = annotationNode.up();

    List<BuilderFieldData> builderFields = new ArrayList<BuilderFieldData>();
    TypeReference returnType;
    TypeParameter[] typeParams;
    TypeReference[] thrownExceptions;
    char[] nameOfStaticBuilderMethod;
    EclipseNode tdParent;

    EclipseNode fillParametersFrom = parent.get() instanceof AbstractMethodDeclaration ? parent : null;
    boolean addCleaning = false;

    if (parent.get() instanceof TypeDeclaration) {
        tdParent = parent;
        TypeDeclaration td = (TypeDeclaration) tdParent.get();

        List<EclipseNode> allFields = new ArrayList<EclipseNode>();
        @SuppressWarnings("deprecation")
        boolean valuePresent = (hasAnnotation(lombok.Value.class, parent)
                || hasAnnotation(lombok.experimental.Value.class, parent));
        for (EclipseNode fieldNode : HandleConstructor.findAllFields(tdParent)) {
            FieldDeclaration fd = (FieldDeclaration) fieldNode.get();
            // final fields with an initializer cannot be written to, so they can't be 'builderized'. Unfortunately presence of @Value makes
            // non-final fields final, but @Value's handler hasn't done this yet, so we have to do this math ourselves.
            // Value will only skip making a field final if it has an explicit @NonFinal annotation, so we check for that.
            if (fd.initialization != null && valuePresent && !hasAnnotation(NonFinal.class, fieldNode))
                continue;
            BuilderFieldData bfd = new BuilderFieldData();
            bfd.rawName = fieldNode.getName().toCharArray();
            bfd.name = removePrefixFromField(fieldNode);
            bfd.type = fd.type;
            bfd.singularData = getSingularData(fieldNode, ast);
            addObtainVia(bfd, fieldNode);
            builderFields.add(bfd);
            allFields.add(fieldNode);
        }

        new HandleConstructor().generateConstructor(tdParent, AccessLevel.PACKAGE, allFields, false, null,
                SkipIfConstructorExists.I_AM_BUILDER, null, Collections.<Annotation>emptyList(),
                annotationNode);

        returnType = namePlusTypeParamsToTypeReference(td.name, td.typeParameters, p);
        typeParams = td.typeParameters;
        thrownExceptions = null;
        nameOfStaticBuilderMethod = null;
        if (builderClassName.isEmpty())
            builderClassName = new String(td.name) + "Builder";
    } else if (parent.get() instanceof ConstructorDeclaration) {
        ConstructorDeclaration cd = (ConstructorDeclaration) parent.get();
        if (cd.typeParameters != null && cd.typeParameters.length > 0) {
            annotationNode
                    .addError("@Builder is not supported on constructors with constructor type parameters.");
            return;
        }

        tdParent = parent.up();
        TypeDeclaration td = (TypeDeclaration) tdParent.get();
        returnType = namePlusTypeParamsToTypeReference(td.name, td.typeParameters, p);
        typeParams = td.typeParameters;
        thrownExceptions = cd.thrownExceptions;
        nameOfStaticBuilderMethod = null;
        if (builderClassName.isEmpty())
            builderClassName = new String(cd.selector) + "Builder";
    } else if (parent.get() instanceof MethodDeclaration) {
        MethodDeclaration md = (MethodDeclaration) parent.get();
        tdParent = parent.up();
        if (!md.isStatic()) {
            annotationNode.addError("@Builder is only supported on types, constructors, and static methods.");
            return;
        }

        if (toBuilder) {
            final String TO_BUILDER_NOT_SUPPORTED = "@Builder(toBuilder=true) is only supported if you return your own type.";
            char[] token;
            char[][] pkg = null;
            if (md.returnType.dimensions() > 0) {
                annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
                return;
            }

            if (md.returnType instanceof SingleTypeReference) {
                token = ((SingleTypeReference) md.returnType).token;
            } else if (md.returnType instanceof QualifiedTypeReference) {
                pkg = ((QualifiedTypeReference) md.returnType).tokens;
                token = pkg[pkg.length];
                char[][] pkg_ = new char[pkg.length - 1][];
                System.arraycopy(pkg, 0, pkg_, 0, pkg_.length);
                pkg = pkg_;
            } else {
                annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
                return;
            }

            if (pkg != null && !equals(parent.getPackageDeclaration(), pkg)) {
                annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
                return;
            }

            if (tdParent == null || !equals(tdParent.getName(), token)) {
                annotationNode.addError(TO_BUILDER_NOT_SUPPORTED);
                return;
            }

            TypeParameter[] tpOnType = ((TypeDeclaration) tdParent.get()).typeParameters;
            TypeParameter[] tpOnMethod = md.typeParameters;
            TypeReference[][] tpOnRet_ = null;
            if (md.returnType instanceof ParameterizedSingleTypeReference) {
                tpOnRet_ = new TypeReference[1][];
                tpOnRet_[0] = ((ParameterizedSingleTypeReference) md.returnType).typeArguments;
            } else if (md.returnType instanceof ParameterizedQualifiedTypeReference) {
                tpOnRet_ = ((ParameterizedQualifiedTypeReference) md.returnType).typeArguments;
            }

            if (tpOnRet_ != null)
                for (int i = 0; i < tpOnRet_.length - 1; i++) {
                    if (tpOnRet_[i] != null && tpOnRet_[i].length > 0) {
                        annotationNode.addError(
                                "@Builder(toBuilder=true) is not supported if returning a type with generics applied to an intermediate.");
                        return;
                    }
                }
            TypeReference[] tpOnRet = tpOnRet_ == null ? null : tpOnRet_[tpOnRet_.length - 1];
            typeArgsForToBuilder = new ArrayList<char[]>();

            // Every typearg on this method needs to be found in the return type, but the reverse is not true.
            // We also need to 'map' them.

            if (tpOnMethod != null)
                for (TypeParameter onMethod : tpOnMethod) {
                    int pos = -1;
                    if (tpOnRet != null)
                        for (int i = 0; i < tpOnRet.length; i++) {
                            if (tpOnRet[i].getClass() != SingleTypeReference.class)
                                continue;
                            if (!Arrays.equals(((SingleTypeReference) tpOnRet[i]).token, onMethod.name))
                                continue;
                            pos = i;
                        }
                    if (pos == -1 || tpOnType == null || tpOnType.length <= pos) {
                        annotationNode.addError(
                                "@Builder(toBuilder=true) requires that each type parameter on the static method is part of the typeargs of the return value. Type parameter "
                                        + new String(onMethod.name) + " is not part of the return type.");
                        return;
                    }

                    typeArgsForToBuilder.add(tpOnType[pos].name);
                }
        }

        returnType = copyType(md.returnType, ast);
        typeParams = md.typeParameters;
        thrownExceptions = md.thrownExceptions;
        nameOfStaticBuilderMethod = md.selector;
        if (builderClassName.isEmpty()) {
            char[] token;
            if (md.returnType instanceof QualifiedTypeReference) {
                char[][] tokens = ((QualifiedTypeReference) md.returnType).tokens;
                token = tokens[tokens.length - 1];
            } else if (md.returnType instanceof SingleTypeReference) {
                token = ((SingleTypeReference) md.returnType).token;
                if (!(md.returnType instanceof ParameterizedSingleTypeReference) && typeParams != null) {
                    for (TypeParameter tp : typeParams) {
                        if (Arrays.equals(tp.name, token)) {
                            annotationNode.addError(
                                    "@Builder requires specifying 'builderClassName' if used on methods with a type parameter as return type.");
                            return;
                        }
                    }
                }
            } else {
                annotationNode.addError(
                        "Unexpected kind of return type on annotated method. Specify 'builderClassName' to solve this problem.");
                return;
            }

            if (Character.isLowerCase(token[0])) {
                char[] newToken = new char[token.length];
                System.arraycopy(token, 1, newToken, 1, token.length - 1);
                newToken[0] = Character.toTitleCase(token[0]);
                token = newToken;
            }

            builderClassName = new String(token) + "Builder";
        }
    } else {
        annotationNode.addError("@Builder is only supported on types, constructors, and static methods.");
        return;
    }

    if (fillParametersFrom != null) {
        for (EclipseNode param : fillParametersFrom.down()) {
            if (param.getKind() != Kind.ARGUMENT)
                continue;
            BuilderFieldData bfd = new BuilderFieldData();
            Argument arg = (Argument) param.get();
            bfd.rawName = arg.name;
            bfd.name = arg.name;
            bfd.type = arg.type;
            bfd.singularData = getSingularData(param, ast);
            addObtainVia(bfd, param);
            builderFields.add(bfd);
        }
    }

    EclipseNode builderType = findInnerClass(tdParent, builderClassName);
    if (builderType == null) {
        builderType = makeBuilderClass(tdParent, builderClassName, typeParams, ast);
    } else {
        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;
                }
            }
        }
    }

    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;
            }
        }
    }

    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 (constructorExists(builderType) == MemberExistsResult.NOT_EXISTS) {
        ConstructorDeclaration cd = HandleConstructor.createConstructor(AccessLevel.PACKAGE, builderType,
                Collections.<EclipseNode>emptyList(), false, null, annotationNode,
                Collections.<Annotation>emptyList());
        if (cd != null)
            injectMethod(builderType, cd);
    }

    for (BuilderFieldData bfd : builderFields) {
        makeSetterMethodsForBuilder(builderType, bfd, annotationNode, fluent, chain);
    }

    if (methodExists(buildMethodName, builderType, -1) == MemberExistsResult.NOT_EXISTS) {
        MethodDeclaration md = generateBuildMethod(buildMethodName, nameOfStaticBuilderMethod, returnType,
                builderFields, builderType, thrownExceptions, addCleaning, ast);
        if (md != null)
            injectMethod(builderType, md);
    }

    if (methodExists("toString", builderType, 0) == MemberExistsResult.NOT_EXISTS) {
        List<EclipseNode> fieldNodes = new ArrayList<EclipseNode>();
        for (BuilderFieldData bfd : builderFields) {
            fieldNodes.addAll(bfd.createdFields);
        }
        MethodDeclaration md = HandleToString.createToString(builderType, fieldNodes, true, false, ast,
                FieldAccess.ALWAYS_FIELD);
        if (md != null)
            injectMethod(builderType, md);
    }

    if (addCleaning) {
        MethodDeclaration cleanMethod = generateCleanMethod(builderFields, builderType, ast);
        if (cleanMethod != null)
            injectMethod(builderType, cleanMethod);
    }

    if (methodExists(builderMethodName, tdParent, -1) == MemberExistsResult.NOT_EXISTS) {
        MethodDeclaration md = generateBuilderMethod(builderMethodName, builderClassName, tdParent, typeParams,
                ast);
        if (md != null)
            injectMethod(tdParent, md);
    }

    if (toBuilder)
        switch (methodExists(toBuilderMethodName, tdParent, 0)) {
        case EXISTS_BY_USER:
            annotationNode.addWarning("Not generating toBuilder() as it already exists.");
            break;
        case NOT_EXISTS:
            TypeParameter[] tps = typeParams;
            if (typeArgsForToBuilder != null) {
                tps = new TypeParameter[typeArgsForToBuilder.size()];
                for (int i = 0; i < tps.length; i++) {
                    tps[i] = new TypeParameter();
                    tps[i].name = typeArgsForToBuilder.get(i);
                }
            }
            MethodDeclaration md = generateToBuilderMethod(toBuilderMethodName, builderClassName, tdParent, tps,
                    builderFields, fluent, ast);

            if (md != null)
                injectMethod(tdParent, md);
        }
}

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

License:Open Source License

private MethodDeclaration generateCleanMethod(List<BuilderFieldData> builderFields, EclipseNode builderType,
        ASTNode source) {//from   ww  w.j a v a  2  s  .com
    List<Statement> statements = new ArrayList<Statement>();

    for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, builderType, statements);
        }
    }

    FieldReference thisUnclean = new FieldReference(CLEAN_FIELD_NAME, 0);
    thisUnclean.receiver = new ThisReference(0, 0);
    statements.add(new Assignment(thisUnclean, new FalseLiteral(0, 0), 0));
    MethodDeclaration decl = new MethodDeclaration(
            ((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
    decl.selector = CLEAN_METHOD_NAME;
    decl.modifiers = ClassFileConstants.AccPrivate;
    decl.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    decl.returnType = TypeReference.baseTypeReference(TypeIds.T_void, 0);
    decl.statements = statements.toArray(new Statement[0]);
    decl.traverse(new SetGeneratedByVisitor(source), (ClassScope) null);
    return decl;
}

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

License:Open Source License

public void generateBuilderFields(EclipseNode builderType, List<BuilderFieldData> builderFields,
        ASTNode source) {/*from  ww w  . ja v  a  2  s  .c  o m*/
    List<EclipseNode> existing = new ArrayList<EclipseNode>();
    for (EclipseNode child : builderType.down()) {
        if (child.getKind() == Kind.FIELD)
            existing.add(child);
    }

    top: for (BuilderFieldData bfd : builderFields) {
        if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
            bfd.createdFields
                    .addAll(bfd.singularData.getSingularizer().generateFields(bfd.singularData, builderType));
        } else {
            for (EclipseNode exists : existing) {
                char[] n = ((FieldDeclaration) exists.get()).name;
                if (Arrays.equals(n, bfd.name)) {
                    bfd.createdFields.add(exists);
                    continue top;
                }
            }

            FieldDeclaration fd = new FieldDeclaration(bfd.name, 0, 0);
            fd.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
            fd.modifiers = ClassFileConstants.AccPrivate;
            fd.type = copyType(bfd.type);
            fd.traverse(new SetGeneratedByVisitor(source), (MethodScope) null);
            bfd.createdFields.add(injectFieldAndMarkGenerated(builderType, fd));
        }
    }
}

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

License:Open Source License

public void setFieldDefaultsForField(EclipseNode fieldNode, ASTNode pos, AccessLevel level, boolean makeFinal) {
    FieldDeclaration field = (FieldDeclaration) fieldNode.get();
    if (level != null && level != AccessLevel.NONE) {
        if ((field.modifiers & (ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate
                | ClassFileConstants.AccProtected)) == 0) {
            if (!hasAnnotation(PackagePrivate.class, fieldNode)) {
                field.modifiers |= EclipseHandlerUtil.toEclipseModifier(level);
            }/*from   w w w  .  jav  a 2s .  co  m*/
        }
    }

    if (makeFinal && (field.modifiers & ClassFileConstants.AccFinal) == 0) {
        if (!hasAnnotation(NonFinal.class, fieldNode)) {
            if ((field.modifiers & ClassFileConstants.AccStatic) == 0 || field.initialization != null) {
                field.modifiers |= ClassFileConstants.AccFinal;
            }
        }
    }

    fieldNode.rebuild();
}

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  ww . ja va2s.co  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.HandleGetter.java

License:Open Source License

public void createGetterForField(AccessLevel level, EclipseNode fieldNode, EclipseNode errorNode,
        ASTNode source, boolean whineIfExists, boolean lazy, List<Annotation> onMethod) {
    if (fieldNode.getKind() != Kind.FIELD) {
        errorNode.addError("@Getter is only supported on a class or a field.");
        return;//  w ww.  ja  v  a  2 s. c om
    }

    FieldDeclaration field = (FieldDeclaration) fieldNode.get();
    if (lazy) {
        if ((field.modifiers & ClassFileConstants.AccPrivate) == 0
                || (field.modifiers & ClassFileConstants.AccFinal) == 0) {
            errorNode.addError("'lazy' requires the field to be private and final.");
            return;
        }
        if (field.initialization == null) {
            errorNode.addError("'lazy' requires field initialization.");
            return;
        }
    }

    TypeReference fieldType = copyType(field.type, source);
    boolean isBoolean = isBoolean(fieldType);
    String getterName = toGetterName(fieldNode, isBoolean);

    if (getterName == null) {
        errorNode.addWarning(
                "Not generating getter for this field: It does not fit your @Accessors prefix list.");
        return;
    }

    int modifier = toEclipseModifier(level) | (field.modifiers & ClassFileConstants.AccStatic);

    for (String altName : toAllGetterNames(fieldNode, isBoolean)) {
        switch (methodExists(altName, fieldNode, false, 0)) {
        case EXISTS_BY_LOMBOK:
            return;
        case EXISTS_BY_USER:
            if (whineIfExists) {
                String altNameExpl = "";
                if (!altName.equals(getterName))
                    altNameExpl = String.format(" (%s)", altName);
                errorNode.addWarning(
                        String.format("Not generating %s(): A method with that name already exists%s",
                                getterName, altNameExpl));
            }
            return;
        default:
        case NOT_EXISTS:
            //continue scanning the other alt names.
        }
    }

    MethodDeclaration method = createGetter((TypeDeclaration) fieldNode.up().get(), fieldNode, getterName,
            modifier, source, lazy, onMethod);

    injectMethod(fieldNode.up(), method);
}