Java Code Examples for org.codehaus.groovy.ast.FieldNode#isFinal()
The following examples show how to use
org.codehaus.groovy.ast.FieldNode#isFinal() .
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: DefaultPropertyHandler.java From groovy with Apache License 2.0 | 6 votes |
@Override public Statement createPropInit(AbstractASTTransformation xform, AnnotationNode anno, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) { String name = pNode.getName(); FieldNode fNode = pNode.getField(); boolean useSetters = xform.memberHasValue(anno, "useSetters", true); boolean hasSetter = cNode.getProperty(name) != null && !fNode.isFinal(); if (namedArgsMap != null) { return assignFieldS(useSetters, namedArgsMap, name); } else { Expression var = varX(name); if (useSetters && hasSetter) { return setViaSetterS(name, var); } else { return assignToFieldS(name, var); } } }
Example 2
Source File: GroovyNodeToStringUtils.java From groovy-language-server with Apache License 2.0 | 5 votes |
public static String variableToString(Variable variable, ASTNodeVisitor ast) { StringBuilder builder = new StringBuilder(); if (variable instanceof FieldNode) { FieldNode fieldNode = (FieldNode) variable; if (fieldNode.isPublic()) { builder.append("public "); } if (fieldNode.isProtected()) { builder.append("protected "); } if (fieldNode.isPrivate()) { builder.append("private "); } if (fieldNode.isFinal()) { builder.append("final "); } if (fieldNode.isStatic()) { builder.append("static "); } } ClassNode varType = null; if (variable instanceof ASTNode) { varType = GroovyASTUtils.getTypeOfNode((ASTNode) variable, ast); } else { varType = variable.getType(); } builder.append(varType.getNameWithoutPackage()); builder.append(" "); builder.append(variable.getName()); return builder.toString(); }
Example 3
Source File: ExpressionUtils.java From groovy with Apache License 2.0 | 5 votes |
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 4
Source File: ImmutableASTTransformation.java From groovy with Apache License 2.0 | 5 votes |
private static void ensureNotPublic(AbstractASTTransformation xform, String cNode, FieldNode fNode) { String fName = fNode.getName(); // TODO: do we need to lock down things like: $ownClass if (fNode.isPublic() && !fName.contains("$") && !(fNode.isStatic() && fNode.isFinal())) { xform.addError("Public field '" + fName + "' not allowed for " + MY_TYPE_NAME + " class '" + cNode + "'.", fNode); } }
Example 5
Source File: ClassCompletionVerifier.java From groovy with Apache License 2.0 | 5 votes |
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 6
Source File: AsmClassGenerator.java From groovy with Apache License 2.0 | 5 votes |
@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 7
Source File: ImmutablePropertyHandler.java From groovy with Apache License 2.0 | 5 votes |
@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 8
Source File: LegacyHashMapPropertyHandler.java From groovy with Apache License 2.0 | 5 votes |
@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 createLegacyConstructorStatementMapSpecial(fNode); }
Example 9
Source File: FieldASTTransformation.java From groovy with Apache License 2.0 | 4 votes |
public void visit(ASTNode[] nodes, SourceUnit source) { sourceUnit = source; if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; if (parent instanceof DeclarationExpression) { DeclarationExpression de = (DeclarationExpression) parent; ClassNode cNode = de.getDeclaringClass(); if (!cNode.isScript()) { addError("Annotation " + MY_TYPE_NAME + " can only be used within a Script.", parent); return; } candidate = de; // GROOVY-4548: temp fix to stop CCE until proper support is added if (de.isMultipleAssignmentDeclaration()) { addError("Annotation " + MY_TYPE_NAME + " not supported with multiple assignment notation.", parent); return; } VariableExpression ve = de.getVariableExpression(); variableName = ve.getName(); // set owner null here, it will be updated by addField fieldNode = new FieldNode(variableName, ve.getModifiers(), ve.getType(), null, de.getRightExpression()); fieldNode.setSourcePosition(de); cNode.addField(fieldNode); // provide setter for CLI Builder purposes unless final if (fieldNode.isFinal()) { if (!de.getAnnotations(OPTION_TYPE).isEmpty()) { addError("Can't have a final field also annotated with @" + OPTION_TYPE.getNameWithoutPackage(), de); } } else { String setterName = getSetterName(variableName); cNode.addMethod(setterName, ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, params(param(ve.getType(), variableName)), ClassNode.EMPTY_ARRAY, block( stmt(assignX(propX(varX("this"), variableName), varX(variableName))) )); } // GROOVY-4833 : annotations that are not Groovy transforms should be transferred to the generated field // GROOVY-6112 : also copy acceptable Groovy transforms final List<AnnotationNode> annotations = de.getAnnotations(); for (AnnotationNode annotation : annotations) { // GROOVY-6337 HACK: in case newly created field is @Lazy if (annotation.getClassNode().equals(LAZY_TYPE)) { LazyASTTransformation.visitField(this, annotation, fieldNode); } final ClassNode annotationClassNode = annotation.getClassNode(); if (notTransform(annotationClassNode) || acceptableTransform(annotation)) { fieldNode.addAnnotation(annotation); } } super.visitClass(cNode); // GROOVY-5207 So that Closures can see newly added fields // (not super efficient for a very large class with many @Fields but we chose simplicity // and understandability of this solution over more complex but efficient alternatives) VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source); scopeVisitor.visitClass(cNode); } }
Example 10
Source File: GeneralUtils.java From groovy with Apache License 2.0 | 4 votes |
public static List<PropertyNode> getAllProperties(final Set<String> names, final ClassNode origType, final ClassNode cNode, final boolean includeProperties, final boolean includeFields, final boolean includePseudoGetters, final boolean includePseudoSetters, final boolean traverseSuperClasses, final boolean skipReadonly, final boolean reverse, final boolean allNames, final boolean includeStatic) { List<PropertyNode> result = new ArrayList<>(); if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && !reverse) { result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly)); } if (includeProperties) { for (PropertyNode pNode : cNode.getProperties()) { if ((!pNode.isStatic() || includeStatic) && !names.contains(pNode.getName())) { result.add(pNode); names.add(pNode.getName()); } } if (includePseudoGetters || includePseudoSetters) { BeanUtils.addPseudoProperties(origType, cNode, result, names, includeStatic, includePseudoGetters, includePseudoSetters); } } if (includeFields) { for (FieldNode fNode : cNode.getFields()) { if ((fNode.isStatic() && !includeStatic) || fNode.isSynthetic() || cNode.getProperty(fNode.getName()) != null || names.contains(fNode.getName())) { continue; } // internal field if (fNode.getName().contains("$") && !allNames) { continue; } if (fNode.isPrivate() && !cNode.equals(origType)) { continue; } if (fNode.isFinal() && fNode.getInitialExpression() != null && skipReadonly) { continue; } result.add(new PropertyNode(fNode, fNode.getModifiers(), null, null)); names.add(fNode.getName()); } } if (cNode != ClassHelper.OBJECT_TYPE && traverseSuperClasses && reverse) { result.addAll(getAllProperties(names, origType, cNode.getSuperClass(), includeProperties, includeFields, includePseudoGetters, includePseudoSetters, true, skipReadonly)); } return result; }
Example 11
Source File: Verifier.java From groovy with Apache License 2.0 | 4 votes |
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 12
Source File: AsmClassGenerator.java From groovy with Apache License 2.0 | 4 votes |
private boolean tryPropertyOfSuperClass(final PropertyExpression pexp, final String propertyName) { ClassNode classNode = controller.getClassNode(); if (!controller.getCompileStack().isLHS()) { String methodName = "get" + capitalize(propertyName); // TODO: "is" callX(pexp.getObjectExpression(), methodName).visit(this); return true; } FieldNode fieldNode = classNode.getSuperClass().getField(propertyName); if (fieldNode == null) { throw new RuntimeParserException("Failed to find field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp); } if (fieldNode.isFinal()) { throw new RuntimeParserException("Cannot modify final field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp); } MethodNode setter = classNode.getSuperClass().getSetterMethod(getSetterName(propertyName)); MethodNode getter = classNode.getSuperClass().getGetterMethod("get" + capitalize(propertyName)); if (fieldNode.isPrivate() && (setter == null || getter == null || !setter.getDeclaringClass().equals(getter.getDeclaringClass()))) { throw new RuntimeParserException("Cannot access private field[" + propertyName + "] of " + classNode.getName() + "'s super class", pexp); } OperandStack operandStack = controller.getOperandStack(); operandStack.doAsType(fieldNode.getType()); MethodVisitor mv = controller.getMethodVisitor(); mv.visitVarInsn(ALOAD, 0); operandStack.push(classNode); operandStack.swap(); String owner = BytecodeHelper.getClassInternalName(classNode.getSuperClass().getName()); String desc = BytecodeHelper.getTypeDescription(fieldNode.getType()); if (fieldNode.isPublic() || fieldNode.isProtected()) { mv.visitFieldInsn(PUTFIELD, owner, propertyName, desc); } else { mv.visitMethodInsn(INVOKESPECIAL, owner, setter.getName(), BytecodeHelper.getMethodDescriptor(setter), false); } return true; }
Example 13
Source File: JavaStubGenerator.java From groovy with Apache License 2.0 | 4 votes |
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(";"); }