Java Code Examples for org.codehaus.groovy.ast.FieldNode#isStatic()

The following examples show how to use org.codehaus.groovy.ast.FieldNode#isStatic() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addListenerToProperty(SourceUnit source, AnnotationNode node, AnnotatedNode parent) {
    ClassNode declaringClass = parent.getDeclaringClass();
    FieldNode field = ((FieldNode) parent);
    String fieldName = field.getName();
    for (PropertyNode propertyNode : declaringClass.getProperties()) {
        boolean bindable = BindableASTTransformation.hasBindableAnnotation(parent)
                || BindableASTTransformation.hasBindableAnnotation(parent.getDeclaringClass());

        if (propertyNode.getName().equals(fieldName)) {
            if (field.isStatic()) {
                //noinspection ThrowableInstanceNeverThrown
                source.getErrorCollector().addErrorAndContinue("@groovy.beans.Vetoable cannot annotate a static property.", node, source);
            } else {
                createListenerSetter(source, bindable, declaringClass, propertyNode);
            }
            return;
        }
    }
    //noinspection ThrowableInstanceNeverThrown
    source.getErrorCollector().addErrorAndContinue("@groovy.beans.Vetoable must be on a property, not a field.  Try removing the private, protected, or public modifier.", node, source);
}
 
Example 2
Source File: CategoryASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static boolean ensureNoInstanceFieldOrProperty(final SourceUnit source, final ClassNode parent) {
    boolean valid = true;
    for (FieldNode fieldNode : parent.getFields()) {
        if (!fieldNode.isStatic() && fieldNode.getLineNumber()>0) {
            // if <0, probably an AST transform or internal code (like generated metaclass field, ...)
            addUnsupportedError(fieldNode,  source);
            valid = false;
        }
    }
    for (PropertyNode propertyNode : parent.getProperties()) {
        if (!propertyNode.isStatic() && propertyNode.getLineNumber()>0) {
            // if <0, probably an AST transform or internal code (like generated metaclass field, ...)
            addUnsupportedError(propertyNode, source);
            valid = false;
        }
    }
    return valid;
}
 
Example 3
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void createSoftSetter(FieldNode fieldNode, ClassNode type) {
    final BlockStatement body = new BlockStatement();
    final Expression fieldExpr = varX(fieldNode);
    final String name = getSetterName(fieldNode.getName().substring(1));
    final Parameter parameter = param(type, "value");
    final Expression paramExpr = varX(parameter);
    body.addStatement(ifElseS(
            notNullX(paramExpr),
            assignS(fieldExpr, ctorX(SOFT_REF, paramExpr)),
            assignS(fieldExpr, nullX())
    ));
    int visibility = ACC_PUBLIC;
    if (fieldNode.isStatic()) visibility |= ACC_STATIC;
    ClassNode declaringClass = fieldNode.getDeclaringClass();
    addGeneratedMethod(declaringClass, name, visibility, ClassHelper.VOID_TYPE, params(parameter), ClassNode.EMPTY_ARRAY, body);
}
 
Example 4
Source File: StaticVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitVariableExpression(VariableExpression ve) {
    if (ve.getAccessedVariable() instanceof DynamicVariable && (ve.isInStaticContext() || inSpecialConstructorCall) && !inClosure) {
        // GROOVY-5687: interface constants not visible to implementing sub-class in static context
        if (methodNode != null && methodNode.isStatic()) {
            FieldNode fieldNode = getDeclaredOrInheritedField(methodNode.getDeclaringClass(), ve.getName());
            if (fieldNode != null && fieldNode.isStatic()) {
                return;
            }
        }
        addError("Apparent variable '" + ve.getName() + "' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:\n" +
                "You attempted to reference a variable in the binding or an instance variable from a static context.\n" +
                "You misspelled a classname or statically imported field. Please check the spelling.\n" +
                "You attempted to use a method '" + ve.getName() + "' but left out brackets in a place not allowed by the grammar.", ve);
    }
}
 
Example 5
Source File: BindableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addListenerToProperty(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field) {
    String fieldName = field.getName();
    for (PropertyNode propertyNode : declaringClass.getProperties()) {
        if (propertyNode.getName().equals(fieldName)) {
            if (field.isStatic()) {
                //noinspection ThrowableInstanceNeverThrown
                source.getErrorCollector().addErrorAndContinue("@groovy.beans.Bindable cannot annotate a static property.", node, source);
            } else {
                if (needsPropertyChangeSupport(declaringClass, source)) {
                    addPropertyChangeSupport(declaringClass);
                }
                createListenerSetter(declaringClass, propertyNode);
            }
            return;
        }
    }
    //noinspection ThrowableInstanceNeverThrown
    source.getErrorCollector().addErrorAndContinue("@groovy.beans.Bindable must be on a property, not a field.  Try removing the private, protected, or public modifier.", node, source);
}
 
Example 6
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void create(FieldNode fieldNode, final Expression initExpr) {
    final BlockStatement body = new BlockStatement();
    if (fieldNode.isStatic()) {
        addHolderClassIdiomBody(body, fieldNode, initExpr);
    } else if (fieldNode.isVolatile()) {
        addDoubleCheckedLockingBody(body, fieldNode, initExpr);
    } else {
        addNonThreadSafeBody(body, fieldNode, initExpr);
    }
    addMethod(fieldNode, body, fieldNode.getType());
}
 
Example 7
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addMethod(FieldNode fieldNode, BlockStatement body, ClassNode type) {
    int visibility = ACC_PUBLIC;
    if (fieldNode.isStatic()) visibility |= ACC_STATIC;
    String propName = capitalize(fieldNode.getName().substring(1));
    ClassNode declaringClass = fieldNode.getDeclaringClass();
    addGeneratedMethod(declaringClass, "get" + propName, visibility, type, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body);
    if (ClassHelper.boolean_TYPE.equals(type)) {
        addGeneratedMethod(declaringClass, "is" + propName, visibility, type,
                Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, stmt(callThisX("get" + propName)));
    }
}
 
Example 8
Source File: ExpressionUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression findConstant(final FieldNode fn) {
    if (fn != null && !fn.isEnum() && fn.isStatic() && fn.isFinal()
            && fn.getInitialValueExpression() instanceof ConstantExpression) {
        return fn.getInitialValueExpression();
    }
    return null;
}
 
Example 9
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitField(final FieldNode fieldNode) {
    onLineNumber(fieldNode, "visitField: " + fieldNode.getName());
    ClassNode t = fieldNode.getType();
    String signature = BytecodeHelper.getGenericsBounds(t);

    Expression initialValueExpression = fieldNode.getInitialValueExpression();
    ConstantExpression cexp = initialValueExpression instanceof ConstantExpression? (ConstantExpression) initialValueExpression :null;
    if (cexp!=null) {
        cexp = Verifier.transformToPrimitiveConstantIfPossible(cexp);
    }
    Object value = cexp != null && ClassHelper.isStaticConstantInitializerType(cexp.getType())
            && cexp.getType().equals(t) && fieldNode.isStatic() && fieldNode.isFinal()
            ? cexp.getValue() : null; // GROOVY-5150
    if (value != null) {
        // byte, char and short require an extra cast
        if (ClassHelper.byte_TYPE.equals(t) || ClassHelper.short_TYPE.equals(t)) {
            value = ((Number) value).intValue();
        } else if (ClassHelper.char_TYPE.equals(t)) {
            value = Integer.valueOf((Character)value);
        }
    }
    FieldVisitor fv = classVisitor.visitField(
            fieldNode.getModifiers(),
            fieldNode.getName(),
            BytecodeHelper.getTypeDescription(t),
            signature,
            value);
    visitAnnotations(fieldNode, fv);
    fv.visitEnd();
}
 
Example 10
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean checkStaticOuterField(final PropertyExpression pexp, final String propertyName) {
    for (final ClassNode outer : controller.getClassNode().getOuterClasses()) {
        FieldNode field = outer.getDeclaredField(propertyName);
        if (field != null) {
            if (!field.isStatic()) break;

            Expression outerClass = classX(outer);
            outerClass.setNodeMetaData(PROPERTY_OWNER, outer);
            outerClass.setSourcePosition(pexp.getObjectExpression());

            Expression outerField = attrX(outerClass, pexp.getProperty());
            outerField.setSourcePosition(pexp);
            outerField.visit(this);
            return true;
        } else {
            field = outer.getField(propertyName); // checks supers
            if (field != null && !field.isPrivate() && (field.isPublic() || field.isProtected()
                    || Objects.equals(field.getDeclaringClass().getPackageName(), outer.getPackageName()))) {
                if (!field.isStatic()) break;

                Expression upperClass = classX(field.getDeclaringClass());
                upperClass.setNodeMetaData(PROPERTY_OWNER, field.getDeclaringClass());
                upperClass.setSourcePosition(pexp.getObjectExpression());

                Expression upperField = propX(upperClass, pexp.getProperty());
                upperField.setSourcePosition(pexp);
                upperField.visit(this);
                return true;
            }
        }
    }
    return false;
}
 
Example 11
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static List<FieldNode> getSuperNonPropertyFields(final ClassNode cNode) {
    List<FieldNode> result;
    if (cNode == ClassHelper.OBJECT_TYPE) {
        result = new ArrayList<>();
    } else {
        result = getSuperNonPropertyFields(cNode.getSuperClass());
    }
    for (FieldNode fNode : cNode.getFields()) {
        if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) {
            result.add(fNode);
        }
    }
    return result;
}
 
Example 12
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Statement createPropInit(AbstractASTTransformation xform, AnnotationNode anno, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) {
    FieldNode fNode = pNode.getField();
    if (fNode.isFinal() && fNode.isStatic()) return null;
    if (fNode.isFinal() && fNode.getInitialExpression() != null) {
        return checkFinalArgNotOverridden(cNode, fNode);
    }
    return createConstructorStatement(xform, cNode, pNode, namedArgsMap);
}
 
Example 13
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkFinalFieldAccess(Expression expression) {
    if (!(expression instanceof VariableExpression) && !(expression instanceof PropertyExpression)) return;
    Variable v = null;
    if (expression instanceof VariableExpression) {
        VariableExpression ve = (VariableExpression) expression;
        v = ve.getAccessedVariable();
    } else {
        PropertyExpression propExp = ((PropertyExpression) expression);
        Expression objectExpression = propExp.getObjectExpression();
        if (objectExpression instanceof VariableExpression) {
            VariableExpression varExp = (VariableExpression) objectExpression;
            if (varExp.isThisExpression()) {
                v = currentClass.getDeclaredField(propExp.getPropertyAsString());
            }
        }
    }
    if (v instanceof FieldNode) {
        FieldNode fn = (FieldNode) v;

        /*
         *  if it is static final but not accessed inside a static constructor, or,
         *  if it is an instance final but not accessed inside a instance constructor, it is an error
         */
        boolean isFinal = fn.isFinal();
        boolean isStatic = fn.isStatic();
        boolean error = isFinal && ((isStatic && !inStaticConstructor) || (!isStatic && !inConstructor));

        if (error) addError("cannot modify" + (isStatic ? " static" : "") + " final field '" + fn.getName() +
                "' outside of " + (isStatic ? "static initialization block." : "constructor."), expression);
    }
}
 
Example 14
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean isClosureCall(final MethodCallExpression call) {
    // are we a local variable?
    // it should not be an explicitly "this" qualified method call
    // and the current class should have a possible method
    ClassNode classNode = controller.getClassNode();
    String methodName = call.getMethodAsString();
    if (methodName == null) return false;
    if (!call.isImplicitThis()) return false;
    if (!AsmClassGenerator.isThisExpression(call.getObjectExpression())) return false;
    FieldNode field = classNode.getDeclaredField(methodName);
    if (field == null) return false;
    if (isStaticInvocation(call) && !field.isStatic()) return false;
    Expression arguments = call.getArguments();
    return !classNode.hasPossibleMethod(methodName, arguments);
}
 
Example 15
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static Expression syncTarget(FieldNode fieldNode) {
    return fieldNode.isStatic() ? classX(fieldNode.getDeclaringClass()) : varX("this");
}
 
Example 16
Source File: IndexedPropertyASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static int getModifiers(FieldNode fNode) {
    int mods = ACC_PUBLIC;
    if (fNode.isStatic()) mods |= ACC_STATIC;
    return mods;
}
 
Example 17
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
boolean makeGetField(final Expression receiver, final ClassNode receiverType, final String fieldName, final boolean safe, final boolean implicitThis) {
    FieldNode field = receiverType.getField(fieldName);

    if (field != null && isDirectAccessAllowed(field, controller.getClassNode())) {
        CompileStack compileStack = controller.getCompileStack();
        MethodVisitor mv = controller.getMethodVisitor();
        ClassNode replacementType = field.getOriginType();
        OperandStack operandStack = controller.getOperandStack();
        if (field.isStatic()) {
            mv.visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(field.getOwner()), fieldName, BytecodeHelper.getTypeDescription(replacementType));
            operandStack.push(replacementType);
        } else {
            if (implicitThis) {
                compileStack.pushImplicitThis(implicitThis);
                receiver.visit(controller.getAcg());
                compileStack.popImplicitThis();
            } else {
                receiver.visit(controller.getAcg());
            }
            Label exit = new Label();
            if (safe) {
                mv.visitInsn(DUP);
                Label doGet = new Label();
                mv.visitJumpInsn(IFNONNULL, doGet);
                mv.visitInsn(POP);
                mv.visitInsn(ACONST_NULL);
                mv.visitJumpInsn(GOTO, exit);
                mv.visitLabel(doGet);
            }
            if (!operandStack.getTopOperand().isDerivedFrom(field.getOwner())) {
                mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(field.getOwner()));
            }
            mv.visitFieldInsn(GETFIELD, BytecodeHelper.getClassInternalName(field.getOwner()), fieldName, BytecodeHelper.getTypeDescription(replacementType));
            if (safe) {
                if (ClassHelper.isPrimitiveType(replacementType)) {
                    operandStack.replace(replacementType);
                    operandStack.box();
                    replacementType = operandStack.getTopOperand();
                }
                mv.visitLabel(exit);
            }
        }
        operandStack.replace(replacementType);
        return true;
    }

    for (ClassNode face : receiverType.getInterfaces()) {
        // GROOVY-7039
        if (face != receiverType && makeGetField(receiver, face, fieldName, safe, implicitThis)) {
            return true;
        }
    }

    ClassNode superClass = receiverType.getSuperClass();
    if (superClass != null && !OBJECT_TYPE.equals(superClass)) {
        return makeGetField(receiver, superClass, fieldName, safe, implicitThis);
    }
    return false;
}
 
Example 18
Source File: Verifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void addInitialization(ClassNode node, ConstructorNode constructorNode) {
    Statement firstStatement = constructorNode.getFirstStatement();
    // if some transformation decided to generate constructor then it probably knows who it does
    if (firstStatement instanceof BytecodeSequence)
        return;

    ConstructorCallExpression first = getFirstIfSpecialConstructorCall(firstStatement);

    // in case of this(...) let the other constructor do the init
    if (first != null && (first.isThisCall())) return;

    List<Statement> statements = new ArrayList<Statement>();
    List<Statement> staticStatements = new ArrayList<Statement>();
    final boolean isEnum = node.isEnum();
    List<Statement> initStmtsAfterEnumValuesInit = new ArrayList<Statement>();
    Set<String> explicitStaticPropsInEnum = new HashSet<String>();
    if (isEnum) {
        for (PropertyNode propNode : node.getProperties()) {
            if (!propNode.isSynthetic() && propNode.getField().isStatic()) {
                explicitStaticPropsInEnum.add(propNode.getField().getName());
            }
        }
        for (FieldNode fieldNode : node.getFields()) {
            if (!fieldNode.isSynthetic() && fieldNode.isStatic() && fieldNode.getType() != node) {
                explicitStaticPropsInEnum.add(fieldNode.getName());
            }
        }
    }

    if (!Traits.isTrait(node)) {
        for (FieldNode fn : node.getFields()) {
            addFieldInitialization(statements, staticStatements, fn, isEnum,
                    initStmtsAfterEnumValuesInit, explicitStaticPropsInEnum);
        }
    }

    statements.addAll(node.getObjectInitializerStatements());

    BlockStatement block = getCodeAsBlock(constructorNode);
    List<Statement> otherStatements = block.getStatements();
    if (!otherStatements.isEmpty()) {
        if (first != null) {
            // it is super(..) since this(..) is already covered
            otherStatements.remove(0);
            statements.add(0, firstStatement);
        }
        Statement stmtThis$0 = getImplicitThis$0StmtIfInnerClass(otherStatements);
        if (stmtThis$0 != null) {
            // since there can be field init statements that depend on method/property dispatching
            // that uses this$0, it needs to bubble up before the super call itself (GROOVY-4471)
            statements.add(0, stmtThis$0);
        }
        statements.addAll(otherStatements);
    }
    BlockStatement newBlock = new BlockStatement(statements, block.getVariableScope());
    newBlock.setSourcePosition(block);
    constructorNode.setCode(newBlock);


    if (!staticStatements.isEmpty()) {
        if (isEnum) {
            /*
             * GROOVY-3161: initialize statements for explicitly declared static fields
             * inside an enum should come after enum values are initialized
             */
            staticStatements.removeAll(initStmtsAfterEnumValuesInit);
            node.addStaticInitializerStatements(staticStatements, true);
            if (!initStmtsAfterEnumValuesInit.isEmpty()) {
                node.positionStmtsAfterEnumInitStmts(initStmtsAfterEnumValuesInit);
            }
        } else {
            node.addStaticInitializerStatements(staticStatements, true);
        }
    }
}
 
Example 19
Source File: Verifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void addFieldInitialization(List list, List staticList, FieldNode fieldNode,
                                      boolean isEnumClassNode, List initStmtsAfterEnumValuesInit, Set explicitStaticPropsInEnum) {
    Expression expression = fieldNode.getInitialExpression();
    if (expression != null) {
        final FieldExpression fe = new FieldExpression(fieldNode);
        if (fieldNode.getType().equals(ClassHelper.REFERENCE_TYPE) && ((fieldNode.getModifiers() & ACC_SYNTHETIC) != 0)) {
            fe.setUseReferenceDirectly(true);
        }
        ExpressionStatement statement =
                new ExpressionStatement(
                        new BinaryExpression(
                                fe,
                                Token.newSymbol(Types.EQUAL, fieldNode.getLineNumber(), fieldNode.getColumnNumber()),
                                expression));
        if (fieldNode.isStatic()) {
            // GROOVY-3311: pre-defined constants added by groovy compiler for numbers/characters should be
            // initialized first so that code dependent on it does not see their values as empty
            Expression initialValueExpression = fieldNode.getInitialValueExpression();
            Expression transformed = transformInlineConstants(initialValueExpression, fieldNode.getType());
            if (transformed instanceof ConstantExpression) {
                ConstantExpression cexp = (ConstantExpression) transformed;
                cexp = transformToPrimitiveConstantIfPossible(cexp);
                if (fieldNode.isFinal() && ClassHelper.isStaticConstantInitializerType(cexp.getType()) && cexp.getType().equals(fieldNode.getType())) {
                    fieldNode.setInitialValueExpression(transformed);
                    return; // GROOVY-5150: primitive type constants will be initialized directly
                }
                staticList.add(0, statement);
            } else {
                staticList.add(statement);
            }
            fieldNode.setInitialValueExpression(null); // to avoid double initialization in case of several constructors
            /*
             * If it is a statement for an explicitly declared static field inside an enum, store its
             * reference. For enums, they need to be handled differently as such init statements should
             * come after the enum values have been initialized inside <clinit> block. GROOVY-3161.
             */
            if (isEnumClassNode && explicitStaticPropsInEnum.contains(fieldNode.getName())) {
                initStmtsAfterEnumValuesInit.add(statement);
            }
        } else {
            list.add(statement);
        }
    }
}
 
Example 20
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void printField(PrintWriter out, FieldNode fieldNode, boolean isInterface) {
    if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
    printAnnotations(out, fieldNode);
    if (!isInterface) {
        printModifiers(out, fieldNode.getModifiers());
    }

    ClassNode type = fieldNode.getType();
    printType(out, type);

    out.print(" ");
    out.print(fieldNode.getName());
    if (isInterface || (fieldNode.getModifiers() & Opcodes.ACC_FINAL) != 0) {
        out.print(" = ");
        Expression valueExpr = fieldNode.getInitialValueExpression();
        if (valueExpr instanceof ConstantExpression) {
            valueExpr = Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) valueExpr);
        }
        if (valueExpr instanceof ConstantExpression
                && fieldNode.isStatic() && fieldNode.isFinal()
                && ClassHelper.isStaticConstantInitializerType(valueExpr.getType())
                && valueExpr.getType().equals(fieldNode.getType())) {
            // GROOVY-5150 : Initialize value with a dummy constant so that Java cross compiles correctly
            if (ClassHelper.STRING_TYPE.equals(valueExpr.getType())) {
                out.print(formatString(valueExpr.getText()));
            } else if (ClassHelper.char_TYPE.equals(valueExpr.getType())) {
                out.print("'"+valueExpr.getText()+"'");
            } else {
                ClassNode constantType = valueExpr.getType();
                out.print('(');
                printType(out, type);
                out.print(") ");
                out.print(valueExpr.getText());
                if (ClassHelper.Long_TYPE.equals(ClassHelper.getWrapper(constantType))) out.print('L');
            }
        } else if (ClassHelper.isPrimitiveType(type)) {
            String val = type == ClassHelper.boolean_TYPE ? "false" : "0";
            out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")");
        } else {
            out.print("null");
        }
    }
    out.println(";");
}