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

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

Introduction

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

Prototype

int AccFinal

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

Click Source Link

Usage

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

License:Apache License

private boolean isFinal(int ecjModifier) {
    return (ecjModifier & ClassFileConstants.AccFinal) != 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 ww w.j  a  va2  s.  c  o  m*/
    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.  j a  v a 2 s .  com
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.agent.PatchDelegate.java

License:Open Source License

private static MethodDeclaration createDelegateMethod(char[] name, EclipseNode typeNode, BindingTuple pair,
        CompilationResult compilationResult, EclipseNode annNode, DelegateReceiver delegateReceiver) {
    /* public <T, U, ...> ReturnType methodName(ParamType1 name1, ParamType2 name2, ...) throws T1, T2, ... {
     *      (return) delegate.<T, U>methodName(name1, name2);
     *  }/*from  www  .  j av  a2s  . c o  m*/
     */

    boolean isVarargs = (pair.base.modifiers & ClassFileConstants.AccVarargs) != 0;

    try {
        checkConflictOfTypeVarNames(pair, typeNode);
    } catch (CantMakeDelegates e) {
        annNode.addError(
                "There's a conflict in the names of type parameters. Fix it by renaming the following type parameters of your class: "
                        + e.conflicted);
        return null;
    }

    ASTNode source = annNode.get();

    int pS = source.sourceStart, pE = source.sourceEnd;

    MethodBinding binding = pair.parameterized;
    MethodDeclaration method = new MethodDeclaration(compilationResult);
    setGeneratedBy(method, source);
    method.sourceStart = pS;
    method.sourceEnd = pE;
    method.modifiers = ClassFileConstants.AccPublic;

    method.returnType = makeType(binding.returnType, source, false);
    boolean isDeprecated = binding.isDeprecated();

    method.selector = binding.selector;

    if (binding.thrownExceptions != null && binding.thrownExceptions.length > 0) {
        method.thrownExceptions = new TypeReference[binding.thrownExceptions.length];
        for (int i = 0; i < method.thrownExceptions.length; i++) {
            method.thrownExceptions[i] = makeType(binding.thrownExceptions[i], source, false);
        }
    }

    MessageSend call = new MessageSend();
    call.sourceStart = pS;
    call.sourceEnd = pE;
    call.nameSourcePosition = pos(source);
    setGeneratedBy(call, source);
    call.receiver = delegateReceiver.get(source, name);
    call.selector = binding.selector;

    if (binding.typeVariables != null && binding.typeVariables.length > 0) {
        method.typeParameters = new TypeParameter[binding.typeVariables.length];
        call.typeArguments = new TypeReference[binding.typeVariables.length];
        for (int i = 0; i < method.typeParameters.length; i++) {
            method.typeParameters[i] = new TypeParameter();
            method.typeParameters[i].sourceStart = pS;
            method.typeParameters[i].sourceEnd = pE;
            setGeneratedBy(method.typeParameters[i], source);
            method.typeParameters[i].name = binding.typeVariables[i].sourceName;
            call.typeArguments[i] = new SingleTypeReference(binding.typeVariables[i].sourceName, pos(source));
            setGeneratedBy(call.typeArguments[i], source);
            ReferenceBinding super1 = binding.typeVariables[i].superclass;
            ReferenceBinding[] super2 = binding.typeVariables[i].superInterfaces;
            if (super2 == null)
                super2 = new ReferenceBinding[0];
            if (super1 != null || super2.length > 0) {
                int offset = super1 == null ? 0 : 1;
                method.typeParameters[i].bounds = new TypeReference[super2.length + offset - 1];
                if (super1 != null)
                    method.typeParameters[i].type = makeType(super1, source, false);
                else
                    method.typeParameters[i].type = makeType(super2[0], source, false);
                int ctr = 0;
                for (int j = (super1 == null) ? 1 : 0; j < super2.length; j++) {
                    method.typeParameters[i].bounds[ctr] = makeType(super2[j], source, false);
                    method.typeParameters[i].bounds[ctr++].bits |= ASTNode.IsSuperType;
                }
            }
        }
    }

    if (isDeprecated) {
        method.annotations = new Annotation[] { generateDeprecatedAnnotation(source) };
    }

    method.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;

    if (binding.parameters != null && binding.parameters.length > 0) {
        method.arguments = new Argument[binding.parameters.length];
        call.arguments = new Expression[method.arguments.length];
        for (int i = 0; i < method.arguments.length; i++) {
            AbstractMethodDeclaration sourceElem;
            try {
                sourceElem = pair.base.sourceMethod();
            } catch (Exception e) {
                sourceElem = null;
            }
            char[] argName;
            if (sourceElem == null)
                argName = ("arg" + i).toCharArray();
            else {
                argName = sourceElem.arguments[i].name;
            }
            method.arguments[i] = new Argument(argName, pos(source),
                    makeType(binding.parameters[i], source, false), ClassFileConstants.AccFinal);
            setGeneratedBy(method.arguments[i], source);
            call.arguments[i] = new SingleNameReference(argName, pos(source));
            setGeneratedBy(call.arguments[i], source);
        }
        if (isVarargs) {
            method.arguments[method.arguments.length - 1].type.bits |= ASTNode.IsVarArgs;
        }
    }

    Statement body;
    if (method.returnType instanceof SingleTypeReference
            && ((SingleTypeReference) method.returnType).token == TypeConstants.VOID) {
        body = call;
    } else {
        body = new ReturnStatement(call, source.sourceStart, source.sourceEnd);
        setGeneratedBy(body, source);
    }

    method.statements = new Statement[] { body };
    return method;
}

From source file:lombok.eclipse.agent.PatchVal.java

License:Open Source License

public static boolean handleValForLocalDeclaration(LocalDeclaration local, BlockScope scope) {
    if (local == null || !LocalDeclaration.class.equals(local.getClass()))
        return false;
    boolean decomponent = false;

    if (!isVal(local.type, scope))
        return false;

    StackTraceElement[] st = new Throwable().getStackTrace();
    for (int i = 0; i < st.length - 2 && i < 10; i++) {
        if (st[i].getClassName().equals("lombok.launch.PatchFixesHider$Val")) {
            if (st[i + 1].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration")
                    && st[i + 2].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.ForStatement"))
                return false;
            break;
        }//from  w  w  w  . jav a  2s .co m
    }

    Expression init = local.initialization;
    if (init == null && Reflection.initCopyField != null) {
        try {
            init = (Expression) Reflection.initCopyField.get(local);
        } catch (Exception e) {
            // init remains null.
        }
    }

    if (init == null && Reflection.iterableCopyField != null) {
        try {
            init = (Expression) Reflection.iterableCopyField.get(local);
            decomponent = true;
        } catch (Exception e) {
            // init remains null.
        }
    }

    TypeReference replacement = null;

    if (init != null) {
        if (init.getClass().getName().equals("org.eclipse.jdt.internal.compiler.ast.LambdaExpression")) {
            return false;
        }

        TypeBinding resolved = null;
        try {
            resolved = decomponent ? getForEachComponentType(init, scope) : init.resolveType(scope);
        } catch (NullPointerException e) {
            // This definitely occurs if as part of resolving the initializer expression, a
            // lambda expression in it must also be resolved (such as when lambdas are part of
            // a ternary expression). This can't result in a viable 'val' matching, so, we
            // just go with 'Object' and let the IDE print the appropriate errors.
            resolved = null;
        }
        if (resolved != null) {
            try {
                replacement = makeType(resolved, local.type, false);
            } catch (Exception e) {
                // Some type thing failed. It might be an IntersectionType
            }
        }
    }

    local.modifiers |= ClassFileConstants.AccFinal;
    local.annotations = addValAnnotation(local.annotations, local.type, scope);
    local.type = replacement != null ? replacement
            : new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(local.type, 3));

    return false;
}

From source file:lombok.eclipse.agent.PatchVal.java

License:Open Source License

public static boolean handleValForForEach(ForeachStatement forEach, BlockScope scope) {
    if (forEach.elementVariable == null)
        return false;

    if (!isVal(forEach.elementVariable.type, scope))
        return false;

    TypeBinding component = getForEachComponentType(forEach.collection, scope);
    if (component == null)
        return false;
    TypeReference replacement = makeType(component, forEach.elementVariable.type, false);

    forEach.elementVariable.modifiers |= ClassFileConstants.AccFinal;
    forEach.elementVariable.annotations = addValAnnotation(forEach.elementVariable.annotations,
            forEach.elementVariable.type, scope);
    forEach.elementVariable.type = replacement != null ? replacement
            : new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(forEach.elementVariable.type, 3));

    return false;
}

From source file:lombok.eclipse.agent.PatchValEclipse.java

License:Open Source License

public static void addFinalAndValAnnotationToModifierList(Object converter, List<IExtendedModifier> modifiers,
        AST ast, LocalDeclaration in) {//  w  w w  .  j  a  v  a  2s .  c  om
    // First check that 'in' has the final flag on, and a @val / @lombok.val annotation.
    if ((in.modifiers & ClassFileConstants.AccFinal) == 0)
        return;
    if (in.annotations == null)
        return;
    boolean found = false;
    Annotation valAnnotation = null;

    for (Annotation ann : in.annotations) {
        if (PatchVal.couldBeVal(ann.type)) {
            found = true;
            valAnnotation = ann;
            break;
        }
    }

    if (!found)
        return;

    // Now check that 'out' is missing either of these.

    if (modifiers == null)
        return; // This is null only if the project is 1.4 or less. Lombok doesn't work in that.
    boolean finalIsPresent = false;
    boolean valIsPresent = false;

    for (Object present : modifiers) {
        if (present instanceof Modifier) {
            ModifierKeyword keyword = ((Modifier) present).getKeyword();
            if (keyword == null)
                continue;
            if (keyword.toFlagValue() == Modifier.FINAL)
                finalIsPresent = true;
        }

        if (present instanceof org.eclipse.jdt.core.dom.Annotation) {
            Name typeName = ((org.eclipse.jdt.core.dom.Annotation) present).getTypeName();
            if (typeName != null) {
                String fullyQualifiedName = typeName.getFullyQualifiedName();
                if ("val".equals(fullyQualifiedName) || "lombok.val".equals(fullyQualifiedName)) {
                    valIsPresent = true;
                }
            }
        }
    }

    if (!finalIsPresent) {
        modifiers.add(createModifier(ast, ModifierKeyword.FINAL_KEYWORD, valAnnotation.sourceStart,
                valAnnotation.sourceEnd));
    }

    if (!valIsPresent) {
        MarkerAnnotation newAnnotation = createValAnnotation(ast, valAnnotation, valAnnotation.sourceStart,
                valAnnotation.sourceEnd);
        try {
            Reflection.astConverterRecordNodes.invoke(converter, newAnnotation, valAnnotation);
            Reflection.astConverterRecordNodes.invoke(converter, newAnnotation.getTypeName(),
                    valAnnotation.type);
        } catch (IllegalAccessException e) {
            throw Lombok.sneakyThrow(e);
        } catch (InvocationTargetException e) {
            throw Lombok.sneakyThrow(e.getCause());
        }
        modifiers.add(newAnnotation);
    }
}

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

License:Open Source License

private static List<EclipseNode> findFields(EclipseNode typeNode, boolean nullMarked) {
    List<EclipseNode> fields = new ArrayList<EclipseNode>();
    for (EclipseNode child : typeNode.down()) {
        if (child.getKind() != Kind.FIELD)
            continue;
        FieldDeclaration fieldDecl = (FieldDeclaration) child.get();
        if (!filterField(fieldDecl))
            continue;
        boolean isFinal = (fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0;
        boolean isNonNull = nullMarked && findAnnotations(fieldDecl, NON_NULL_PATTERN).length != 0;
        if ((isFinal || isNonNull) && fieldDecl.initialization == null)
            fields.add(child);//from   ww w  . java 2 s.c o  m
    }
    return fields;
}

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

License:Open Source License

static List<EclipseNode> findAllFields(EclipseNode typeNode) {
    List<EclipseNode> fields = new ArrayList<EclipseNode>();
    for (EclipseNode child : typeNode.down()) {
        if (child.getKind() != Kind.FIELD)
            continue;
        FieldDeclaration fieldDecl = (FieldDeclaration) child.get();
        if (!filterField(fieldDecl))
            continue;

        // Skip initialized final fields.
        if (((fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0) && fieldDecl.initialization != null)
            continue;

        fields.add(child);//www  .ja v  a  2s .  co m
    }
    return fields;
}

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

License:Open Source License

public void generateMethods(EclipseNode typeNode, EclipseNode errorNode, List<String> excludes,
        List<String> includes, Boolean callSuper, boolean whineIfExists, FieldAccess fieldAccess,
        List<Annotation> onParam) {
    assert excludes == null || includes == null;

    TypeDeclaration typeDecl = null;// ww w.ja  v a  2 s.c om

    if (typeNode.get() instanceof TypeDeclaration)
        typeDecl = (TypeDeclaration) typeNode.get();
    int modifiers = typeDecl == null ? 0 : typeDecl.modifiers;
    boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation
            | ClassFileConstants.AccEnum)) != 0;

    if (typeDecl == null || notAClass) {
        errorNode.addError("@EqualsAndHashCode is only supported on a class.");
        return;
    }

    boolean implicitCallSuper = callSuper == null;

    if (callSuper == null) {
        try {
            callSuper = ((Boolean) EqualsAndHashCode.class.getMethod("callSuper").getDefaultValue())
                    .booleanValue();
        } catch (Exception ignore) {
            throw new InternalError(
                    "Lombok bug - this cannot happen - can't find callSuper field in EqualsAndHashCode annotation.");
        }
    }

    boolean isDirectDescendantOfObject = true;

    if (typeDecl.superclass != null) {
        String p = typeDecl.superclass.toString();
        isDirectDescendantOfObject = p.equals("Object") || p.equals("java.lang.Object");
    }

    if (isDirectDescendantOfObject && callSuper) {
        errorNode.addError("Generating equals/hashCode with a supercall to java.lang.Object is pointless.");
        return;
    }

    if (!isDirectDescendantOfObject && !callSuper && implicitCallSuper) {
        errorNode.addWarning(
                "Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '@EqualsAndHashCode(callSuper=false)' to your type.");
    }

    List<EclipseNode> nodesForEquality = new ArrayList<EclipseNode>();
    if (includes != null) {
        for (EclipseNode child : typeNode.down()) {
            if (child.getKind() != Kind.FIELD)
                continue;
            FieldDeclaration fieldDecl = (FieldDeclaration) child.get();
            if (includes.contains(new String(fieldDecl.name)))
                nodesForEquality.add(child);
        }
    } else {
        for (EclipseNode child : typeNode.down()) {
            if (child.getKind() != Kind.FIELD)
                continue;
            FieldDeclaration fieldDecl = (FieldDeclaration) child.get();
            if (!filterField(fieldDecl))
                continue;

            //Skip transient fields.
            if ((fieldDecl.modifiers & ClassFileConstants.AccTransient) != 0)
                continue;
            //Skip excluded fields.
            if (excludes != null && excludes.contains(new String(fieldDecl.name)))
                continue;
            nodesForEquality.add(child);
        }
    }

    boolean isFinal = (typeDecl.modifiers & ClassFileConstants.AccFinal) != 0;
    boolean needsCanEqual = !isFinal || !isDirectDescendantOfObject;
    MemberExistsResult equalsExists = methodExists("equals", typeNode, 1);
    MemberExistsResult hashCodeExists = methodExists("hashCode", typeNode, 0);
    MemberExistsResult canEqualExists = methodExists("canEqual", typeNode, 1);
    switch (Collections.max(Arrays.asList(equalsExists, hashCodeExists))) {
    case EXISTS_BY_LOMBOK:
        return;
    case EXISTS_BY_USER:
        if (whineIfExists) {
            String msg = "Not generating equals and hashCode: A method with one of those names already exists. (Either both or none of these methods will be generated).";
            errorNode.addWarning(msg);
        } else if (equalsExists == MemberExistsResult.NOT_EXISTS
                || hashCodeExists == MemberExistsResult.NOT_EXISTS) {
            // This means equals OR hashCode exists and not both.
            // Even though we should suppress the message about not generating these, this is such a weird and surprising situation we should ALWAYS generate a warning.
            // The user code couldn't possibly (barring really weird subclassing shenanigans) be in a shippable state anyway; the implementations of these 2 methods are
            // all inter-related and should be written by the same entity.
            String msg = String.format("Not generating %s: One of equals or hashCode exists. "
                    + "You should either write both of these or none of these (in the latter case, lombok generates them).",
                    equalsExists == MemberExistsResult.NOT_EXISTS ? "equals" : "hashCode");
            errorNode.addWarning(msg);
        }
        return;
    case NOT_EXISTS:
    default:
        //fallthrough
    }

    MethodDeclaration equalsMethod = createEquals(typeNode, nodesForEquality, callSuper, errorNode.get(),
            fieldAccess, needsCanEqual, onParam);
    equalsMethod.traverse(new SetGeneratedByVisitor(errorNode.get()), ((TypeDeclaration) typeNode.get()).scope);
    injectMethod(typeNode, equalsMethod);

    if (needsCanEqual && canEqualExists == MemberExistsResult.NOT_EXISTS) {
        MethodDeclaration canEqualMethod = createCanEqual(typeNode, errorNode.get(), onParam);
        canEqualMethod.traverse(new SetGeneratedByVisitor(errorNode.get()),
                ((TypeDeclaration) typeNode.get()).scope);
        injectMethod(typeNode, canEqualMethod);
    }

    MethodDeclaration hashCodeMethod = createHashCode(typeNode, nodesForEquality, callSuper, errorNode.get(),
            fieldAccess);
    hashCodeMethod.traverse(new SetGeneratedByVisitor(errorNode.get()),
            ((TypeDeclaration) typeNode.get()).scope);
    injectMethod(typeNode, hashCodeMethod);
}