org.codehaus.groovy.ast.FieldNode Java Examples

The following examples show how to use org.codehaus.groovy.ast.FieldNode. 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: LegacyHashMapPropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Statement createLegacyConstructorStatementMapSpecial(FieldNode fNode) {
    final Expression fieldExpr = varX(fNode);
    final ClassNode fieldType = fieldExpr.getType();
    final Expression initExpr = fNode.getInitialValueExpression();
    final Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
    } else {
        assignInit = assignS(fieldExpr, cloneCollectionExpr(initExpr, fieldType));
    }
    Expression namedArgs = findArg(fNode.getName());
    Expression baseArgs = varX("args");
    Statement assignStmt = ifElseS(
            equalsNullX(namedArgs),
            ifElseS(
                    isTrueX(callX(baseArgs, "containsKey", constX(fNode.getName()))),
                    assignS(fieldExpr, namedArgs),
                    assignS(fieldExpr, cloneCollectionExpr(baseArgs, fieldType))),
            ifElseS(
                    isOneX(callX(baseArgs, "size")),
                    assignS(fieldExpr, cloneCollectionExpr(namedArgs, fieldType)),
                    assignS(fieldExpr, cloneCollectionExpr(baseArgs, fieldType)))
    );
    return ifElseS(equalsNullX(baseArgs), assignInit, assignStmt);
}
 
Example #2
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean validateEnumConstant(Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) exp;
        String name = pe.getPropertyAsString();
        if (pe.getObjectExpression() instanceof ClassExpression && name != null) {
            ClassExpression ce = (ClassExpression) pe.getObjectExpression();
            ClassNode type = ce.getType();
            if (type.isEnum()) {
                boolean ok = false;
                try {
                    FieldNode enumField = type.getDeclaredField(name);
                    ok = enumField != null && enumField.getType().equals(type);
                } catch(Exception ex) {
                    // ignore
                }
                if(!ok) {
                    addError("No enum const " + type.getName() + "." + name, pe);
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #3
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private ConstantExpression getConstantExpression(Expression exp, ClassNode attrType) {
    Expression result = exp;
    if (!(result instanceof ConstantExpression)) {
        result = transformInlineConstants(result, attrType);
    }
    if (result instanceof ConstantExpression) {
        return (ConstantExpression) result;
    }
    String base = "Expected '" + exp.getText() + "' to be an inline constant of type " + attrType.getName();
    if (exp instanceof PropertyExpression) {
        addError(base + " not a property expression", exp);
    } else if (exp instanceof VariableExpression && ((VariableExpression)exp).getAccessedVariable() instanceof FieldNode) {
        addError(base + " not a field expression", exp);
    } else {
        addError(base, exp);
    }
    ConstantExpression ret = new ConstantExpression(null);
    ret.setSourcePosition(exp);
    return ret;
}
 
Example #4
Source File: SourceURIASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void setScriptURIOnField(final FieldNode fieldNode, final AnnotationNode node) {
    if (fieldNode.hasInitialExpression()) {
        addError("Annotation " + MY_TYPE_NAME + " not supported with variable assignment.", fieldNode);
        return;
    }

    URI uri = getSourceURI(node);

    if (uri == null) {
        addError("Unable to get the URI for the source of this class!", fieldNode);
    } else {
        // Set the RHS to '= URI.create("string for this URI")'.
        // That may throw an IllegalArgumentExpression wrapping the URISyntaxException.
        fieldNode.setInitialValueExpression(getExpression(uri));
    }
}
 
Example #5
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static boolean isValidFieldNodeForByteCodeAccess(final FieldNode fn, final ClassNode accessingNode) {
    if (fn == null) return false;
    ClassNode declaringClass = fn.getDeclaringClass();
    // same class is always allowed access
    if (fn.isPublic() || declaringClass.equals(accessingNode)) return true;
    boolean samePackages = Objects.equals(declaringClass.getPackageName(), accessingNode.getPackageName());
    // protected means same class or same package, or subclass
    if (fn.isProtected() && (samePackages || accessingNode.isDerivedFrom(declaringClass))) {
        return true;
    }
    if (!fn.isPrivate()) {
        // package private is the only modifier left. It means  same package is allowed, subclass not, same class is
        return samePackages;
    }
    return false;
}
 
Example #6
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void genField(FieldNode fieldNode, PrintWriter out) {
    // <netbeans>
    if (fieldNode.isSynthetic() || "metaClass".equals(fieldNode.getName())) { // NOI18N
        return;
    }
    // </netbeans>
    if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) {
        return;
    }
    printModifiers(out, fieldNode.getModifiers());

    printType(fieldNode.getType(), out);

    out.print(" ");
    out.print(fieldNode.getName());
    out.println(";");
}
 
Example #7
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 #8
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static String getRefDescriptor(ASTNode ref) {
    if (ref instanceof FieldNode) {
        FieldNode f = (FieldNode) ref;
        return "the field "+f.getName()+" ";
    } else if (ref instanceof PropertyNode) {
        PropertyNode p = (PropertyNode) ref;
        return "the property "+p.getName()+" ";
    } else if (ref instanceof ConstructorNode) {
        return "the constructor "+ref.getText()+" ";
    } else if (ref instanceof MethodNode) {
        return "the method "+ref.getText()+" ";
    } else if (ref instanceof ClassNode) {
        return "the super class "+ref+" ";
    }
    return "<unknown with class "+ref.getClass()+"> ";
}
 
Example #9
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected Statement createConstructorStatement(AbstractASTTransformation xform, ClassNode cNode, PropertyNode pNode, Parameter namedArgsMap) {
    final List<String> knownImmutableClasses = ImmutablePropertyUtils.getKnownImmutableClasses(xform, cNode);
    final List<String> knownImmutables = ImmutablePropertyUtils.getKnownImmutables(xform, cNode);
    FieldNode fNode = pNode.getField();
    final ClassNode fType = fNode.getType();
    Statement statement;
    boolean shouldNullCheck = NullCheckASTTransformation.hasIncludeGenerated(cNode);
    if (ImmutablePropertyUtils.isKnownImmutableType(fType, knownImmutableClasses) || isKnownImmutable(pNode.getName(), knownImmutables)) {
        statement = createConstructorStatementDefault(fNode, namedArgsMap, shouldNullCheck);
    } else if (fType.isArray() || implementsCloneable(fType)) {
        statement = createConstructorStatementArrayOrCloneable(fNode, namedArgsMap, shouldNullCheck);
    } else if (derivesFromDate(fType)) {
        statement = createConstructorStatementDate(fNode, namedArgsMap, shouldNullCheck);
    } else if (isOrImplements(fType, COLLECTION_TYPE) || fType.isDerivedFrom(COLLECTION_TYPE) || isOrImplements(fType, MAP_TYPE) || fType.isDerivedFrom(MAP_TYPE)) {
        statement = createConstructorStatementCollection(fNode, namedArgsMap, shouldNullCheck);
    } else if (fType.isResolved()) {
        xform.addError(ImmutablePropertyUtils.createErrorMessage(cNode.getName(), fNode.getName(), fType.getName(), "compiling"), fNode);
        statement = EmptyStatement.INSTANCE;
    } else {
        statement = createConstructorStatementGuarded(fNode, namedArgsMap, knownImmutables, knownImmutableClasses, shouldNullCheck);
    }
    return statement;
}
 
Example #10
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void createBuilderForAnnotatedClass(BuilderASTTransformation transform, ClassNode buildee, AnnotationNode anno, boolean useSetters, boolean allNames, boolean force) {
    List<String> excludes = new ArrayList<String>();
    List<String> includes = new ArrayList<String>();
    includes.add(Undefined.STRING);
    if (!getIncludeExclude(transform, anno, buildee, excludes, includes)) return;
    if (includes.size() == 1 && Undefined.isUndefined(includes.get(0))) includes = null;
    List<FieldNode> fields = getFields(transform, anno, buildee);
    List<FieldNode> filteredFields = filterFields(fields, includes, excludes, allNames);
    if (filteredFields.isEmpty()) {
        transform.addError("Error during " + BuilderASTTransformation.MY_TYPE_NAME +
                " processing: at least one property is required for this strategy", anno);
    }
    ClassNode builder = createInnerHelperClass(buildee, getBuilderClassName(buildee, anno), filteredFields.size());
    addFields(buildee, filteredFields, builder);

    buildCommon(buildee, anno, filteredFields, builder);
    boolean needsConstructor = !AnnotatedNodeUtils.hasAnnotation(buildee, TUPLECONS_TYPE) || force;
    createBuildeeConstructors(transform, buildee, builder, filteredFields, needsConstructor, useSetters);
}
 
Example #11
Source File: GroovyIndexer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void indexField(ASTField child, IndexDocument document) {

            StringBuilder sb = new StringBuilder(child.getName());
            FieldNode node = (FieldNode) child.getNode();

            sb.append(';').append(org.netbeans.modules.groovy.editor.java.Utilities.translateClassLoaderTypeName(
                    node.getType().getName()));

            int flags = getFieldModifiersFlag(child.getModifiers());
            if (flags != 0 || child.isProperty()) {
                sb.append(';');
                sb.append(IndexedElement.flagToFirstChar(flags));
                sb.append(IndexedElement.flagToSecondChar(flags));
            }

            if (child.isProperty()) {
                sb.append(';');
                sb.append(child.isProperty());
            }

            // TODO - gather documentation on fields? naeh
            document.addPair(FIELD_NAME, sb.toString(), true, true);
        }
 
Example #12
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 #13
Source File: StaticVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static FieldNode getDeclaredOrInheritedField(ClassNode cn, String fieldName) {
    ClassNode node = cn;
    while (node != null) {
        FieldNode fn = node.getDeclaredField(fieldName);
        if (fn != null) return fn;
        List<ClassNode> interfacesToCheck = new ArrayList<>(Arrays.asList(node.getInterfaces()));
        while (!interfacesToCheck.isEmpty()) {
            ClassNode nextInterface = interfacesToCheck.remove(0);
            fn = nextInterface.getDeclaredField(fieldName);
            if (fn != null) return fn;
            interfacesToCheck.addAll(Arrays.asList(nextInterface.getInterfaces()));
        }
        node = node.getSuperClass();
    }
    return null;
}
 
Example #14
Source File: NewifyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void newifyMethodOrField(AnnotatedNode parent, boolean autoFlag, ListExpression list, final Pattern cnPattern) {

        final ListExpression oldClassesToNewify = classesToNewify;
        final boolean oldAuto = auto;
        final Pattern oldCnPattern = classNamePattern;

        checkClassLevelClashes(list);
        checkAutoClash(autoFlag, parent);

        classesToNewify = list;
        auto = autoFlag;
        classNamePattern = cnPattern;

        if (parent instanceof FieldNode) {
            super.visitField((FieldNode) parent);
        } else {
            super.visitMethod((MethodNode) parent);
        }

        classesToNewify = oldClassesToNewify;
        auto = oldAuto;
        classNamePattern = oldCnPattern;
    }
 
Example #15
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 #16
Source File: GeneralUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static Statement createConstructorStatementDefault(final FieldNode fNode) {
    final String name = fNode.getName();
    final ClassNode fType = fNode.getType();
    final Expression fieldExpr = propX(varX("this"), name);
    Expression initExpr = fNode.getInitialValueExpression();
    Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        if (ClassHelper.isPrimitiveType(fType)) {
            assignInit = EmptyStatement.INSTANCE;
        } else {
            assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
        }
    } else {
        assignInit = assignS(fieldExpr, initExpr);
    }
    fNode.setInitialValueExpression(null);
    Expression value = findArg(name);
    return ifElseS(equalsNullX(value), assignInit, assignS(fieldExpr, castX(fType, value)));
}
 
Example #17
Source File: ImmutablePropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Statement createConstructorStatementGuarded(FieldNode fNode, Parameter namedArgsMap, List<String> knownImmutables, List<String> knownImmutableClasses, boolean shouldNullCheck) {
    final Expression fieldExpr = propX(varX("this"), fNode.getName());
    Expression param = getParam(fNode, namedArgsMap != null);
    Statement assignStmt = assignS(fieldExpr, createCheckImmutable(fNode, param, knownImmutables, knownImmutableClasses));
    assignStmt = ifElseS(
            equalsNullX(param),
            shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr),
            assignStmt);
    Expression initExpr = fNode.getInitialValueExpression();
    final Statement assignInit;
    if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression) initExpr).isNullExpression())) {
        assignInit = shouldNullCheck ? NullCheckASTTransformation.makeThrowStmt(fNode.getName()) : assignNullS(fieldExpr);
    } else {
        assignInit = assignS(fieldExpr, createCheckImmutable(fNode, initExpr, knownImmutables, knownImmutableClasses));
    }
    return assignFieldWithDefault(namedArgsMap, fNode, assignStmt, assignInit);
}
 
Example #18
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createSimpleClone(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    if (cNode.getDeclaredConstructors().isEmpty()) {
        // add no-arg constructor
        addGeneratedConstructor(cNode, ACC_PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, block(EmptyStatement.INSTANCE));
    }
    addSimpleCloneHelperMethod(cNode, fieldNodes, excludes);
    final Expression result = localVarX("_result");
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, block(
        declS(result, ctorX(cNode)),
        stmt(callThisX("cloneOrCopyMembers", args(result))),
        returnS(result)));
}
 
Example #19
Source File: UnionTypeClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public FieldNode getDeclaredField(final String name) {
    for (ClassNode delegate : delegates) {
        FieldNode node = delegate.getDeclaredField(name);
        if (node != null) return node;
    }
    return null;
}
 
Example #20
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addSimpleCloneHelperMethod(ClassNode cNode, List<FieldNode> fieldNodes, List<String> excludes) {
    Parameter methodParam = new Parameter(GenericsUtils.nonGeneric(cNode), "other");
    final Expression other = varX(methodParam);
    boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
    BlockStatement methodBody = new BlockStatement();
    if (hasParent) {
        methodBody.addStatement(stmt(callSuperX("cloneOrCopyMembers", args(other))));
    }
    for (FieldNode fieldNode : fieldNodes) {
        String name = fieldNode.getName();
        if (excludes != null && excludes.contains(name)) continue;
        ClassNode fieldType = fieldNode.getType();
        Expression direct = propX(varX("this"), name);
        Expression to = propX(other, name);
        Statement assignDirect = assignS(to, direct);
        Statement assignCloned = assignS(to, castX(fieldType, callCloneDirectX(direct)));
        Statement assignClonedDynamic = assignS(to, castX(fieldType, callCloneDynamicX(direct)));
        if (isCloneableType(fieldType)) {
            methodBody.addStatement(assignCloned);
        } else if (!possiblyCloneable(fieldType)) {
            methodBody.addStatement(assignDirect);
        } else {
            methodBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
        }
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "cloneOrCopyMembers", ACC_PROTECTED, ClassHelper.VOID_TYPE, params(methodParam), exceptions, methodBody);
}
 
Example #21
Source File: TupleConstructorASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression providedOrDefaultInitialValue(FieldNode fNode) {
    Expression initialExp = fNode.getInitialExpression() != null ? fNode.getInitialExpression() : nullX();
    final ClassNode paramType = fNode.getType();
    if (ClassHelper.isPrimitiveType(paramType) && isNull(initialExp)) {
        initialExp = primitivesInitialValues.get(paramType.getTypeClass());
    }
    return initialExp;
}
 
Example #22
Source File: DetectorTransform.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
  if (nodes.length == 0 || !(nodes[0] instanceof ModuleNode)) {
    source.getErrorCollector().addError(new SimpleMessage(
      "internal error in DetectorTransform", source));
    return;
  }
  ModuleNode module = (ModuleNode)nodes[0];
  for (ClassNode clazz : (List<ClassNode>)module.getClasses()) {
    FieldNode field = clazz.getField(VERSION_FIELD_NAME);
    if (field != null) {
      field.setInitialValueExpression(new ConstantExpression(ReleaseInfo.getVersion()));
      break;
    }
  }
}
 
Example #23
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 #24
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static FieldNode checkFieldDoesNotExist(ClassNode node, String fieldName) {
    FieldNode ret = node.getDeclaredField(fieldName);
    if (ret != null) {
        if (isPublic(ret.getModifiers()) &&
                ret.getType().redirect() == ClassHelper.boolean_TYPE) {
            return ret;
        }
        throw new RuntimeParserException("The class " + node.getName() +
                " cannot declare field '" + fieldName + "' as this" +
                " field is needed for internal groovy purposes", ret);
    }
    return null;
}
 
Example #25
Source File: ExternalizeMethodsASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createReadExternal(ClassNode cNode, List<String> excludes, List<FieldNode> list) {
    final BlockStatement body = new BlockStatement();
    Parameter oin = param(OBJECTINPUT_TYPE, "oin");
    for (FieldNode fNode : list) {
        if (excludes != null && excludes.contains(fNode.getName())) continue;
        if ((fNode.getModifiers() & ACC_TRANSIENT) != 0) continue;
        String suffix = suffixForField(fNode);
        MethodCallExpression readObject = callX(varX(oin), "read" + suffix);
        readObject.setImplicitThis(false);
        body.addStatement(assignS(varX(fNode), suffix.equals("Object") ? castX(GenericsUtils.nonGeneric(fNode.getType()), readObject) : readObject));
    }
    addGeneratedMethod(cNode, "readExternal", ACC_PUBLIC, ClassHelper.VOID_TYPE, params(oin), ClassNode.EMPTY_ARRAY, body);
}
 
Example #26
Source File: PackageScopeASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    boolean legacyMode = LEGACY_TYPE_NAME.equals(node.getClassNode().getName());
    if (!MY_TYPE.equals(node.getClassNode()) && !legacyMode) return;

    Expression value = node.getMember("value");
    if (parent instanceof ClassNode) {
        List<groovy.transform.PackageScopeTarget> targets;
        if (value == null) targets = Collections.singletonList(legacyMode ? PackageScopeTarget.FIELDS : PackageScopeTarget.CLASS);
        else targets = determineTargets(value);
        visitClassNode((ClassNode) parent, targets);
        parent.getAnnotations();
    } else {
        if (value != null) {
            addError("Error during " + MY_TYPE_NAME
                    + " processing: " + TARGET_CLASS_NAME + " only allowed at class level.", parent);
            return;
        }
        if (parent instanceof MethodNode) {
            visitMethodNode((MethodNode) parent);
        } else if (parent instanceof FieldNode) {
            visitFieldNode((FieldNode) parent);
        }
    }
}
 
Example #27
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ConstructorNode createInitializerConstructor(ClassNode buildee, ClassNode builder, List<FieldNode> fields) {
    ClassNode paramType = makeClassSafeWithGenerics(builder, setGenTypes(fields.size()));
    List<Expression> argsList = new ArrayList<Expression>();
    Parameter initParam = param(paramType, "initializer");
    for (FieldNode fieldNode : fields) {
        argsList.add(propX(varX(initParam), fieldNode.getName()));
    }
    return addGeneratedConstructor(buildee, ACC_PUBLIC, params(param(paramType, "initializer")), NO_EXCEPTIONS, block(ctorThisS(args(argsList))));
}
 
Example #28
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 #29
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void printEnumFields(PrintWriter out, List<FieldNode> fields) {
    if (!fields.isEmpty()) {
        boolean first = true;
        for (FieldNode field : fields) {
            if (!first) {
                out.print(", ");
            } else {
                first = false;
            }
            out.print(field.getName());
        }
    }
    out.println(";");
}
 
Example #30
Source File: ClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    Variable v = expression.getAccessedVariable();
    if (v == null) return;
    if (!(v instanceof FieldNode)) return;
    String name = expression.getName();
    FieldNode fn = icn.getDeclaredField(name);
    if (fn != null) { // only overwrite if we find something more specific
        expression.setAccessedVariable(fn);
    }
}