Java Code Examples for org.codehaus.groovy.ast.expr.ListExpression#getExpressions()

The following examples show how to use org.codehaus.groovy.ast.expr.ListExpression#getExpressions() . 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: ExpressionUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Given a list of constants, transform each item in the list.
 *
 * @param origList the list to transform
 * @param attrType the target type
 * @return the transformed list or the original if nothing was changed
 */
public static Expression transformListOfConstants(final ListExpression origList, final ClassNode attrType) {
    ListExpression newList = new ListExpression();
    boolean changed = false;
    for (Expression e : origList.getExpressions()) {
        try {
            Expression transformed = transformInlineConstants(e, attrType);
            newList.addExpression(transformed);
            if (transformed != e) changed = true;
        } catch(Exception ignored) {
            newList.addExpression(e);
        }
    }
    if (changed) {
        newList.setSourcePosition(origList);
        return newList;
    }
    return origList;
}
 
Example 2
Source File: ImmutablePropertyUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static List<String> getKnownImmutables(AbstractASTTransformation xform, ClassNode cNode) {
    List<AnnotationNode> annotations = cNode.getAnnotations(ImmutablePropertyUtils.IMMUTABLE_OPTIONS_TYPE);
    AnnotationNode anno = annotations.isEmpty() ? null : annotations.get(0);
    final List<String> immutables = new ArrayList<String>();
    if (anno == null) return immutables;

    final Expression expression = anno.getMember(MEMBER_KNOWN_IMMUTABLES);
    if (expression == null) return immutables;

    if (!(expression instanceof ListExpression)) {
        xform.addError("Use the Groovy list notation [el1, el2] to specify known immutable property names via \"" + MEMBER_KNOWN_IMMUTABLES + "\"", anno);
        return immutables;
    }

    final ListExpression listExpression = (ListExpression) expression;
    for (Expression listItemExpression : listExpression.getExpressions()) {
        if (listItemExpression instanceof ConstantExpression) {
            immutables.add((String) ((ConstantExpression) listItemExpression).getValue());
        }
    }
    if (!xform.checkPropertyList(cNode, immutables, "knownImmutables", anno, "immutable class", false)) return immutables;

    return immutables;
}
 
Example 3
Source File: ImmutablePropertyUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static List<String> getKnownImmutableClasses(AbstractASTTransformation xform, ClassNode cNode) {
    List<AnnotationNode> annotations = cNode.getAnnotations(ImmutablePropertyUtils.IMMUTABLE_OPTIONS_TYPE);
    AnnotationNode anno = annotations.isEmpty() ? null : annotations.get(0);
    final List<String> immutableClasses = new ArrayList<String>();

    if (anno == null) return immutableClasses;
    final Expression expression = anno.getMember(MEMBER_KNOWN_IMMUTABLE_CLASSES);
    if (expression == null) return immutableClasses;

    if (!(expression instanceof ListExpression)) {
        xform.addError("Use the Groovy list notation [el1, el2] to specify known immutable classes via \"" + MEMBER_KNOWN_IMMUTABLE_CLASSES + "\"", anno);
        return immutableClasses;
    }

    final ListExpression listExpression = (ListExpression) expression;
    for (Expression listItemExpression : listExpression.getExpressions()) {
        if (listItemExpression instanceof ClassExpression) {
            immutableClasses.add(listItemExpression.getType().getName());
        }
    }

    return immutableClasses;
}
 
Example 4
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static boolean containsSpreadExpression(final Expression arguments) {
    List<Expression> args;
    if (arguments instanceof TupleExpression) {
        TupleExpression tupleExpression = (TupleExpression) arguments;
        args = tupleExpression.getExpressions();
    } else if (arguments instanceof ListExpression) {
        ListExpression le = (ListExpression) arguments;
        args = le.getExpressions();
    } else {
        return arguments instanceof SpreadExpression;
    }
    for (Expression arg : args) {
        if (arg instanceof SpreadExpression) return true;
    }
    return false;
}
 
Example 5
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 6 votes vote down vote up
private Expression serialize(Expression e) {
    if (e instanceof AnnotationConstantExpression) {
        AnnotationConstantExpression ace = (AnnotationConstantExpression) e;
        return serialize((AnnotationNode) ace.getValue());
    } else if (e instanceof ListExpression) {
        boolean annotationConstant = false;
        ListExpression le = (ListExpression) e;
        List<Expression> list = le.getExpressions();
        List<Expression> newList = new ArrayList<>(list.size());
        for (Expression exp: list) {
            annotationConstant = annotationConstant || exp instanceof AnnotationConstantExpression;
            newList.add(serialize(exp));
        }
        ClassNode type = ClassHelper.OBJECT_TYPE;
        if (annotationConstant) type = type.makeArray();
        return new ArrayExpression(type, newList);
    }
    return e;
}
 
Example 6
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 6 votes vote down vote up
private List<AnnotationNode> getTargetListFromValue(AnnotationNode collector, AnnotationNode aliasAnnotationUsage, SourceUnit source) {
    Expression memberValue = collector.getMember("value");
    if (memberValue == null) {
        return Collections.emptyList();
    }
    if (!(memberValue instanceof ListExpression)) {
        addError("Annotation collector expected a list of classes, but got a "+memberValue.getClass(), collector, source);
        return Collections.emptyList();
    }
    ListExpression memberListExp = (ListExpression) memberValue;
    List<Expression> memberList = memberListExp.getExpressions();
    if (memberList.isEmpty()) {
        return Collections.emptyList();
    }
    List<AnnotationNode> ret = new ArrayList<>();
    for (Expression e : memberList) {
        AnnotationNode toAdd = new AnnotationNode(e.getType());
        toAdd.setSourcePosition(aliasAnnotationUsage);
        ret.add(toAdd);
    }
    return ret;
}
 
Example 7
Source File: ExpressionUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * The attribute values of annotations must be primitive, String or Enum constants.
 * In various places, such constants can be seen during type resolution but won't be
 * readily accessible in later phases, e.g. they might be embedded into constructor code.
 * This method transforms constants that would appear in annotations early so they aren't lost.
 * Subsequent processing determines whether they are valid, this method simply retains
 * the constant value as a constant expression.
 *
 * @param exp the original expression
 * @return the converted expression
 */
public static Expression transformInlineConstants(final Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) exp;
        if (pe.getObjectExpression() instanceof ClassExpression) {
            ClassExpression ce = (ClassExpression) pe.getObjectExpression();
            ClassNode type = ce.getType();
            FieldNode field = ClassNodeUtils.getField(type, pe.getPropertyAsString());
            if (type.isEnum() && field != null && field.isEnum()) return exp;
            Expression constant = findConstant(field);
            if (constant != null) return constant;
        }
    } else if (exp instanceof BinaryExpression) {
        BinaryExpression be = (BinaryExpression) exp;
        be.setLeftExpression(transformInlineConstants(be.getLeftExpression()));
        be.setRightExpression(transformInlineConstants(be.getRightExpression()));
        return be;
    } else if (exp instanceof ListExpression) {
        ListExpression origList = (ListExpression) exp;
        ListExpression newList = new ListExpression();
        boolean changed = false;
        for (Expression e : origList.getExpressions()) {
            Expression transformed = transformInlineConstants(e);
            newList.addExpression(transformed);
            if (transformed != e) changed = true;
        }
        if (changed) {
            newList.setSourcePosition(origList);
            return newList;
        }
        return origList;
    }

    return exp;
}
 
Example 8
Source File: VerifierCodeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visitListExpression(ListExpression expression) {
    for (Expression element : expression.getExpressions()) {
        if (element instanceof MapEntryExpression) {
            throw new RuntimeParserException("No map entry allowed at this place", element);
        }
    }
    super.visitListExpression(expression);
}
 
Example 9
Source File: StaticTypesTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void addTypeCheckingExtensions(StaticTypeCheckingVisitor visitor, Expression extensions) {
    if (extensions instanceof ConstantExpression) {
        visitor.addTypeCheckingExtension(new GroovyTypeCheckingExtensionSupport(
                visitor,
                extensions.getText(),
                compilationUnit
        ));
    } else if (extensions instanceof ListExpression) {
        ListExpression list = (ListExpression) extensions;
        for (Expression ext : list.getExpressions()) {
            addTypeCheckingExtensions(visitor, ext);
        }
    }
}
 
Example 10
Source File: NewifyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkClassLevelClashes(ListExpression list) {
    @SuppressWarnings("unchecked")
    List<ClassExpression> classes = (List) list.getExpressions();
    for (ClassExpression ce : classes) {
        final String name = ce.getType().getNameWithoutPackage();
        if (findClassWithMatchingBasename(name)) {
            addError("Error during @" + MY_NAME + " processing. Class '" + name + "' can't appear at " +
                    "method/constructor/field level if it already appears at the class level.", ce);
        }
    }
}
 
Example 11
Source File: NewifyASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkDuplicateNameClashes(ListExpression list) {
    final Set<String> seen = new HashSet<String>();
    @SuppressWarnings("unchecked")
    List<ClassExpression> classes = (List) list.getExpressions();
    for (ClassExpression ce : classes) {
        final String name = ce.getType().getNameWithoutPackage();
        if (seen.contains(name)) {
            addError("Duplicate name '" + name + "' found during @" + MY_NAME + " processing.", ce);
        }
        seen.add(name);
    }
}
 
Example 12
Source File: PackageScopeASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<groovy.transform.PackageScopeTarget> determineTargets(Expression expr) {
    List<groovy.transform.PackageScopeTarget> list = new ArrayList<groovy.transform.PackageScopeTarget>();
    if (expr instanceof PropertyExpression) {
        list.add(extractTarget((PropertyExpression) expr));
    } else if (expr instanceof ListExpression) {
        final ListExpression expressionList = (ListExpression) expr;
        final List<Expression> expressions = expressionList.getExpressions();
        for (Expression ex : expressions) {
            if (ex instanceof PropertyExpression) {
                list.add(extractTarget((PropertyExpression) ex));
            }
        }
    }
    return list;
}
 
Example 13
Source File: ListExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private List<Expression> transformArguments(final ListExpression expr) {
    List<Expression> expressions = expr.getExpressions();
    List<Expression> transformedArgs = new LinkedList<Expression>();
    for (Expression expression : expressions) {
        transformedArgs.add(transformer.transform(expression));
    }
    return transformedArgs;
}
 
Example 14
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<ClassNode> getTypeList(ListExpression listExpression) {
    List<ClassNode> list = new ArrayList<>();
    for (Expression itemExpr : listExpression.getExpressions()) {
        if (itemExpr instanceof ClassExpression) {
            ClassNode cn = itemExpr.getType();
            if (cn != null) list.add(cn);
        }
    }
    return list;
}
 
Example 15
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<String> getValueStringList(ListExpression listExpression) {
    List<String> list = new ArrayList<>();
    for (Expression itemExpr : listExpression.getExpressions()) {
        if (itemExpr instanceof ConstantExpression) {
            Object value = ((ConstantExpression) itemExpr).getValue();
            if (value != null) list.add(value.toString());
        }
    }
    return list;
}
 
Example 16
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkAnnotationMemberValue(final Expression newValue) {
    if (newValue instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) newValue;
        if (!(pe.getObjectExpression() instanceof ClassExpression)) {
            addError("unable to find class '" + pe.getText() + "' for annotation attribute constant", pe.getObjectExpression());
        }
    } else if (newValue instanceof ListExpression) {
        ListExpression le = (ListExpression) newValue;
        for (Expression e : le.getExpressions()) {
            checkAnnotationMemberValue(e);
        }
    }
}
 
Example 17
Source File: MixinASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotationNode node = (AnnotationNode) nodes[0];
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    if (!MY_TYPE.equals(node.getClassNode()))
        return;

    final Expression expr = node.getMember("value");
    if (expr == null) {
        return;
    }

    Expression useClasses = null;
    if (expr instanceof ClassExpression) {
        useClasses = expr;
    } else if (expr instanceof ListExpression) {
        ListExpression listExpression = (ListExpression) expr;
        for (Expression ex : listExpression.getExpressions()) {
            if (!(ex instanceof ClassExpression))
                return;
        }
        useClasses = expr;
    }

    if (useClasses == null)
        return;

    if (parent instanceof ClassNode) {
        ClassNode annotatedClass = (ClassNode) parent;

        final Parameter[] noparams = Parameter.EMPTY_ARRAY;
        MethodNode clinit = annotatedClass.getDeclaredMethod("<clinit>", noparams);
        if (clinit == null) {
            clinit = annotatedClass.addMethod("<clinit>", ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, noparams, null, new BlockStatement());
            clinit.setSynthetic(true);
        }

        final BlockStatement code = (BlockStatement) clinit.getCode();
        code.addStatement(
                stmt(callX(propX(classX(annotatedClass), "metaClass"), "mixin", useClasses))
        );
    }
}
 
Example 18
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void visitListExpression(String attrName, ListExpression listExpr, ClassNode elementType) {
    for (Expression expression : listExpr.getExpressions()) {
        visitExpression(attrName, expression, elementType);
    }
}
 
Example 19
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private String getAnnotationValue(Object memberValue) {
    String val = "null";
    if (memberValue instanceof ListExpression) {
        StringBuilder sb = new StringBuilder("{");
        boolean first = true;
        ListExpression le = (ListExpression) memberValue;
        for (Expression e : le.getExpressions()) {
            if (first) first = false;
            else sb.append(",");
            sb.append(getAnnotationValue(e));
        }
        sb.append("}");
        val = sb.toString();
    } else if (memberValue instanceof ConstantExpression) {
        ConstantExpression ce = (ConstantExpression) memberValue;
        Object constValue = ce.getValue();
        if (constValue instanceof AnnotationNode) {
            Writer writer = new StringBuilderWriter();
            PrintWriter out = new PrintWriter(writer);
            printAnnotation(out, (AnnotationNode) constValue);
            val = writer.toString();
        } else if (constValue instanceof Number || constValue instanceof Boolean)
            val = constValue.toString();
        else
            val = "\"" + escapeSpecialChars(constValue.toString()) + "\"";
    } else if (memberValue instanceof PropertyExpression) {
        // assume must be static class field or enum value or class that Java can resolve
        val = ((Expression) memberValue).getText();
    } else if (memberValue instanceof VariableExpression) {
        val = ((Expression) memberValue).getText();
        //check for an alias
        ImportNode alias = currentModule.getStaticImports().get(val);
        if (alias != null)
            val = alias.getClassName() + "." + alias.getFieldName();
    } else if (memberValue instanceof ClosureExpression) {
        // annotation closure; replaced with this specific class literal to cover the
        // case where annotation type uses Class<? extends Closure> for the closure's type
        val = "groovy.lang.Closure.class";
    } else if (memberValue instanceof ClassExpression) {
        val = ((Expression) memberValue).getText() + ".class";
    }
    return val;
}
 
Example 20
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void printMethod(PrintWriter out, ClassNode clazz, MethodNode methodNode) {
    if (methodNode.getName().equals("<clinit>")) return;
    if (methodNode.isPrivate() || !Utilities.isJavaIdentifier(methodNode.getName())) return;
    if (methodNode.isSynthetic() && methodNode.getName().equals("$getStaticMetaClass")) return;

    printAnnotations(out, methodNode);
    if (!isInterfaceOrTrait(clazz)) {
        int modifiers = methodNode.getModifiers();
        if (isDefaultTraitImpl(methodNode)) {
            modifiers ^= Opcodes.ACC_ABSTRACT;
        }
        printModifiers(out, modifiers & ~(clazz.isEnum() ? Opcodes.ACC_ABSTRACT : 0));
    }

    printGenericsBounds(out, methodNode.getGenericsTypes());
    out.print(" ");
    printType(out, methodNode.getReturnType());
    out.print(" ");
    out.print(methodNode.getName());

    printParams(out, methodNode);

    ClassNode[] exceptions = methodNode.getExceptions();
    printExceptions(out, exceptions);

    if (Traits.isTrait(clazz)) {
        out.println(";");
    } else if (isAbstract(methodNode) && !clazz.isEnum()) {
        if (clazz.isAnnotationDefinition() && methodNode.hasAnnotationDefault()) {
            Statement fs = methodNode.getFirstStatement();
            if (fs instanceof ExpressionStatement) {
                ExpressionStatement es = (ExpressionStatement) fs;
                Expression re = es.getExpression();
                out.print(" default ");
                ClassNode rt = methodNode.getReturnType();
                boolean classReturn = ClassHelper.CLASS_Type.equals(rt) || (rt.isArray() && ClassHelper.CLASS_Type.equals(rt.getComponentType()));
                if (re instanceof ListExpression) {
                    out.print("{ ");
                    ListExpression le = (ListExpression) re;
                    boolean first = true;
                    for (Expression expression : le.getExpressions()) {
                        if (first) first = false;
                        else out.print(", ");
                        printValue(out, expression, classReturn);
                    }
                    out.print(" }");
                } else {
                    printValue(out, re, classReturn);
                }
            }
        }
        out.println(";");
    } else {
        out.print(" { ");
        ClassNode retType = methodNode.getReturnType();
        printReturn(out, retType);
        out.println("}");
    }
}