Search in sources :

Example 41 with ListExpression

use of org.codehaus.groovy.ast.expr.ListExpression in project groovy-core by groovy.

the class Java5 method configureAnnotationFromDefinition.

public static void configureAnnotationFromDefinition(AnnotationNode definition, AnnotationNode root) {
    ClassNode type = definition.getClassNode();
    if ("java.lang.annotation.Retention".equals(type.getName())) {
        Expression exp = definition.getMember("value");
        if (!(exp instanceof PropertyExpression))
            return;
        PropertyExpression pe = (PropertyExpression) exp;
        String name = pe.getPropertyAsString();
        RetentionPolicy policy = RetentionPolicy.valueOf(name);
        setRetentionPolicy(policy, root);
    } else if ("java.lang.annotation.Target".equals(type.getName())) {
        Expression exp = definition.getMember("value");
        if (!(exp instanceof ListExpression))
            return;
        ListExpression le = (ListExpression) exp;
        int bitmap = 0;
        for (Expression e : le.getExpressions()) {
            if (!(e instanceof PropertyExpression))
                return;
            PropertyExpression element = (PropertyExpression) e;
            String name = element.getPropertyAsString();
            ElementType value = ElementType.valueOf(name);
            bitmap |= getElementCode(value);
        }
        root.setAllowedTargets(bitmap);
    }
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) ElementType(java.lang.annotation.ElementType) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) RetentionPolicy(java.lang.annotation.RetentionPolicy)

Example 42 with ListExpression

use of org.codehaus.groovy.ast.expr.ListExpression in project groovy-core by groovy.

the class JavaStubGenerator method getAnnotationValue.

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) {
            StringWriter writer = new StringWriter();
            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 || memberValue instanceof VariableExpression) {
        // assume must be static class field or enum value or class that Java can resolve
        val = ((Expression) memberValue).getText();
    } 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;
}
Also used : ListExpression(org.codehaus.groovy.ast.expr.ListExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) StringWriter(java.io.StringWriter) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ConstructorCallExpression(org.codehaus.groovy.ast.expr.ConstructorCallExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) PrintWriter(java.io.PrintWriter)

Example 43 with ListExpression

use of org.codehaus.groovy.ast.expr.ListExpression in project groovy by apache.

the class GrabAnnotationTransformation method visit.

public void visit(ASTNode[] nodes, SourceUnit source) {
    sourceUnit = source;
    loader = null;
    initContextClassLoader = false;
    ModuleNode mn = (ModuleNode) nodes[0];
    allowShortGrab = true;
    allowShortGrabExcludes = true;
    allowShortGrabConfig = true;
    allowShortGrapes = true;
    allowShortGrabResolver = true;
    grabAliases = new HashSet<String>();
    grabExcludeAliases = new HashSet<String>();
    grabConfigAliases = new HashSet<String>();
    grapesAliases = new HashSet<String>();
    grabResolverAliases = new HashSet<String>();
    for (ImportNode im : mn.getImports()) {
        String alias = im.getAlias();
        String className = im.getClassName();
        if ((className.endsWith(GRAB_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAB_CLASS_NAME.equals(alias))) {
            allowShortGrab = false;
        } else if (GRAB_CLASS_NAME.equals(className)) {
            grabAliases.add(im.getAlias());
        }
        if ((className.endsWith(GRAPES_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRAPES_CLASS_NAME.equals(alias))) {
            allowShortGrapes = false;
        } else if (GRAPES_CLASS_NAME.equals(className)) {
            grapesAliases.add(im.getAlias());
        }
        if ((className.endsWith(GRABRESOLVER_DOT_NAME) && ((alias == null) || (alias.length() == 0))) || (GRABRESOLVER_CLASS_NAME.equals(alias))) {
            allowShortGrabResolver = false;
        } else if (GRABRESOLVER_CLASS_NAME.equals(className)) {
            grabResolverAliases.add(im.getAlias());
        }
    }
    List<Map<String, Object>> grabMaps = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> grabMapsInit = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> grabExcludeMaps = new ArrayList<Map<String, Object>>();
    for (ClassNode classNode : sourceUnit.getAST().getClasses()) {
        grabAnnotations = new ArrayList<AnnotationNode>();
        grabExcludeAnnotations = new ArrayList<AnnotationNode>();
        grabConfigAnnotations = new ArrayList<AnnotationNode>();
        grapesAnnotations = new ArrayList<AnnotationNode>();
        grabResolverAnnotations = new ArrayList<AnnotationNode>();
        visitClass(classNode);
        ClassNode grapeClassNode = ClassHelper.make(Grape.class);
        List<Statement> grabResolverInitializers = new ArrayList<Statement>();
        if (!grapesAnnotations.isEmpty()) {
            for (AnnotationNode node : grapesAnnotations) {
                Expression init = node.getMember("initClass");
                Expression value = node.getMember("value");
                if (value instanceof ListExpression) {
                    for (Object o : ((ListExpression) value).getExpressions()) {
                        if (o instanceof ConstantExpression) {
                            extractGrab(init, (ConstantExpression) o);
                        }
                    }
                } else if (value instanceof ConstantExpression) {
                    extractGrab(init, (ConstantExpression) value);
                }
            // don't worry if it's not a ListExpression, or AnnotationConstant, etc.
            // the rest of GroovyC will flag it as a syntax error later, so we don't
            // need to raise the error ourselves
            }
        }
        if (!grabResolverAnnotations.isEmpty()) {
            grabResolverAnnotationLoop: for (AnnotationNode node : grabResolverAnnotations) {
                Map<String, Object> grabResolverMap = new HashMap<String, Object>();
                String sval = getMemberStringValue(node, "value");
                if (sval != null && sval.length() > 0) {
                    for (String s : GRABRESOLVER_REQUIRED) {
                        String mval = getMemberStringValue(node, s);
                        if (mval != null && mval.isEmpty())
                            mval = null;
                        if (mval != null) {
                            addError("The attribute \"" + s + "\" conflicts with attribute 'value' in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                            continue grabResolverAnnotationLoop;
                        }
                    }
                    grabResolverMap.put("name", sval);
                    grabResolverMap.put("root", sval);
                } else {
                    for (String s : GRABRESOLVER_REQUIRED) {
                        String mval = getMemberStringValue(node, s);
                        if (mval != null && mval.isEmpty())
                            mval = null;
                        Expression member = node.getMember(s);
                        if (member == null || mval == null) {
                            addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                            continue grabResolverAnnotationLoop;
                        } else if (mval == null) {
                            addError("Attribute \"" + s + "\" has value " + member.getText() + " but should be an inline constant String in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                            continue grabResolverAnnotationLoop;
                        }
                        grabResolverMap.put(s, mval);
                    }
                }
                // If no scheme is specified for the repository root,
                // then turn it into a URI relative to that of the source file.
                String root = (String) grabResolverMap.get("root");
                if (root != null && !root.contains(":")) {
                    URI sourceURI = null;
                    // and those are not hierarchical we can't use them for making an absolute URI.
                    if (!(getSourceUnit().getSource() instanceof StringReaderSource)) {
                        // Otherwise let's trust the source to know where it is from.
                        // And actually InputStreamReaderSource doesn't know what to do and so returns null.
                        sourceURI = getSourceUnit().getSource().getURI();
                    }
                    // then let's use the current working directory, since the repo can be relative to that.
                    if (sourceURI == null) {
                        sourceURI = new File(".").toURI();
                    }
                    try {
                        URI rootURI = sourceURI.resolve(new URI(root));
                        grabResolverMap.put("root", rootURI.toString());
                    } catch (URISyntaxException e) {
                    // We'll be silent here.
                    // If the URI scheme is unknown or not hierarchical, then we just can't help them and shouldn't cause any trouble either.
                    // addError("Attribute \"root\" has value '" + root + "' which can't be turned into a valid URI relative to it's source '" + getSourceUnit().getName() + "' @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                    }
                }
                Grape.addResolver(grabResolverMap);
                addGrabResolverAsStaticInitIfNeeded(grapeClassNode, node, grabResolverInitializers, grabResolverMap);
            }
        }
        if (!grabConfigAnnotations.isEmpty()) {
            for (AnnotationNode node : grabConfigAnnotations) {
                checkForClassLoader(node);
                checkForInitContextClassLoader(node);
                checkForAutoDownload(node);
                checkForSystemProperties(node);
                checkForDisableChecksums(node);
            }
            addInitContextClassLoaderIfNeeded(classNode);
        }
        if (!grabExcludeAnnotations.isEmpty()) {
            grabExcludeAnnotationLoop: for (AnnotationNode node : grabExcludeAnnotations) {
                Map<String, Object> grabExcludeMap = new HashMap<String, Object>();
                checkForConvenienceForm(node, true);
                for (String s : GRABEXCLUDE_REQUIRED) {
                    Expression member = node.getMember(s);
                    if (member == null) {
                        addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                        continue grabExcludeAnnotationLoop;
                    } else if (member != null && !(member instanceof ConstantExpression)) {
                        addError("Attribute \"" + s + "\" has value " + member.getText() + " but should be an inline constant in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                        continue grabExcludeAnnotationLoop;
                    }
                    grabExcludeMap.put(s, ((ConstantExpression) member).getValue());
                }
                grabExcludeMaps.add(grabExcludeMap);
            }
        }
        if (!grabAnnotations.isEmpty()) {
            grabAnnotationLoop: for (AnnotationNode node : grabAnnotations) {
                Map<String, Object> grabMap = new HashMap<String, Object>();
                checkForConvenienceForm(node, false);
                for (String s : GRAB_ALL) {
                    Expression member = node.getMember(s);
                    String mval = getMemberStringValue(node, s);
                    if (mval != null && mval.isEmpty())
                        member = null;
                    if (member == null && !GRAB_OPTIONAL.contains(s)) {
                        addError("The missing attribute \"" + s + "\" is required in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                        continue grabAnnotationLoop;
                    } else if (member != null && !(member instanceof ConstantExpression)) {
                        addError("Attribute \"" + s + "\" has value " + member.getText() + " but should be an inline constant in @" + node.getClassNode().getNameWithoutPackage() + " annotations", node);
                        continue grabAnnotationLoop;
                    }
                    if (node.getMember(s) != null) {
                        grabMap.put(s, ((ConstantExpression) member).getValue());
                    }
                }
                grabMaps.add(grabMap);
                if ((node.getMember("initClass") == null) || (node.getMember("initClass") == ConstantExpression.TRUE)) {
                    grabMapsInit.add(grabMap);
                }
            }
            callGrabAsStaticInitIfNeeded(classNode, grapeClassNode, grabMapsInit, grabExcludeMaps);
        }
        if (!grabResolverInitializers.isEmpty()) {
            classNode.addStaticInitializerStatements(grabResolverInitializers, true);
        }
    }
    if (!grabMaps.isEmpty()) {
        Map<String, Object> basicArgs = new HashMap<String, Object>();
        basicArgs.put("classLoader", loader != null ? loader : sourceUnit.getClassLoader());
        if (!grabExcludeMaps.isEmpty())
            basicArgs.put("excludes", grabExcludeMaps);
        if (autoDownload != null)
            basicArgs.put(AUTO_DOWNLOAD_SETTING, autoDownload);
        if (disableChecksums != null)
            basicArgs.put(DISABLE_CHECKSUMS_SETTING, disableChecksums);
        if (systemProperties != null)
            basicArgs.put(SYSTEM_PROPERTIES_SETTING, systemProperties);
        try {
            Grape.grab(basicArgs, grabMaps.toArray(new Map[grabMaps.size()]));
            // grab may have added more transformations through new URLs added to classpath, so do one more scan
            if (compilationUnit != null) {
                ASTTransformationVisitor.addGlobalTransformsAfterGrab(compilationUnit.getASTTransformationsContext());
            }
        } catch (RuntimeException re) {
            // Decided against syntax exception since this is not a syntax error.
            // The down side is we lose line number information for the offending
            // @Grab annotation.
            source.addException(re);
        }
    }
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) HashMap(java.util.HashMap) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement) Statement(org.codehaus.groovy.ast.stmt.Statement) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) StringReaderSource(org.codehaus.groovy.control.io.StringReaderSource) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) MapExpression(org.codehaus.groovy.ast.expr.MapExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) StaticMethodCallExpression(org.codehaus.groovy.ast.expr.StaticMethodCallExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ImportNode(org.codehaus.groovy.ast.ImportNode) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) ModuleNode(org.codehaus.groovy.ast.ModuleNode)

Example 44 with ListExpression

use of org.codehaus.groovy.ast.expr.ListExpression in project groovy by apache.

the class AnnotationVisitor method transformInlineConstants.

private Expression transformInlineConstants(Expression exp) {
    if (exp instanceof PropertyExpression) {
        PropertyExpression pe = (PropertyExpression) exp;
        if (pe.getObjectExpression() instanceof ClassExpression) {
            ClassExpression ce = (ClassExpression) pe.getObjectExpression();
            ClassNode type = ce.getType();
            if (type.isEnum() || !type.isResolved())
                return exp;
            try {
                Field field = type.getTypeClass().getField(pe.getPropertyAsString());
                if (field != null && Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) {
                    return new ConstantExpression(field.get(null));
                }
            } catch (Exception e) {
            // ignore, leave property expression in place and we'll report later
            }
        }
    } else if (exp instanceof ListExpression) {
        ListExpression le = (ListExpression) exp;
        ListExpression result = new ListExpression();
        for (Expression e : le.getExpressions()) {
            result.addExpression(transformInlineConstants(e));
        }
        return result;
    }
    return exp;
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) Field(java.lang.reflect.Field) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) AnnotationConstantExpression(org.codehaus.groovy.ast.expr.AnnotationConstantExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) AnnotationConstantExpression(org.codehaus.groovy.ast.expr.AnnotationConstantExpression) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) SyntaxException(org.codehaus.groovy.syntax.SyntaxException)

Example 45 with ListExpression

use of org.codehaus.groovy.ast.expr.ListExpression in project groovy by apache.

the class AnnotationVisitor method visitExpression.

protected void visitExpression(String attrName, Expression attrExp, ClassNode attrType) {
    if (attrType.isArray()) {
        // check needed as @Test(attr = {"elem"}) passes through the parser
        if (attrExp instanceof ListExpression) {
            ListExpression le = (ListExpression) attrExp;
            visitListExpression(attrName, le, attrType.getComponentType());
        } else if (attrExp instanceof ClosureExpression) {
            addError("Annotation list attributes must use Groovy notation [el1, el2]", attrExp);
        } else {
            // treat like a singleton list as per Java
            ListExpression listExp = new ListExpression();
            listExp.addExpression(attrExp);
            if (annotation != null) {
                annotation.setMember(attrName, listExp);
            }
            visitExpression(attrName, listExp, attrType);
        }
    } else if (ClassHelper.isPrimitiveType(attrType)) {
        visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.getWrapper(attrType));
    } else if (ClassHelper.STRING_TYPE.equals(attrType)) {
        visitConstantExpression(attrName, getConstantExpression(attrExp, attrType), ClassHelper.STRING_TYPE);
    } else if (ClassHelper.CLASS_Type.equals(attrType)) {
        if (!(attrExp instanceof ClassExpression || attrExp instanceof ClosureExpression)) {
            addError("Only classes and closures can be used for attribute '" + attrName + "'", attrExp);
        }
    } else if (attrType.isDerivedFrom(ClassHelper.Enum_Type)) {
        if (attrExp instanceof PropertyExpression) {
            visitEnumExpression(attrName, (PropertyExpression) attrExp, attrType);
        } else {
            addError("Expected enum value for attribute " + attrName, attrExp);
        }
    } else if (isValidAnnotationClass(attrType)) {
        if (attrExp instanceof AnnotationConstantExpression) {
            visitAnnotationExpression(attrName, (AnnotationConstantExpression) attrExp, attrType);
        } else {
            addError("Expected annotation of type '" + attrType.getName() + "' for attribute " + attrName, attrExp);
        }
    } else {
        addError("Unexpected type " + attrType.getName(), attrExp);
    }
}
Also used : AnnotationConstantExpression(org.codehaus.groovy.ast.expr.AnnotationConstantExpression) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression)

Aggregations

ListExpression (org.codehaus.groovy.ast.expr.ListExpression)60 Expression (org.codehaus.groovy.ast.expr.Expression)44 ConstantExpression (org.codehaus.groovy.ast.expr.ConstantExpression)41 ClassExpression (org.codehaus.groovy.ast.expr.ClassExpression)37 VariableExpression (org.codehaus.groovy.ast.expr.VariableExpression)27 ClassNode (org.codehaus.groovy.ast.ClassNode)25 ArgumentListExpression (org.codehaus.groovy.ast.expr.ArgumentListExpression)19 ArrayList (java.util.ArrayList)16 MethodCallExpression (org.codehaus.groovy.ast.expr.MethodCallExpression)15 PropertyExpression (org.codehaus.groovy.ast.expr.PropertyExpression)15 ConstructorCallExpression (org.codehaus.groovy.ast.expr.ConstructorCallExpression)14 ArrayExpression (org.codehaus.groovy.ast.expr.ArrayExpression)12 MapExpression (org.codehaus.groovy.ast.expr.MapExpression)12 ClosureExpression (org.codehaus.groovy.ast.expr.ClosureExpression)11 FieldNode (org.codehaus.groovy.ast.FieldNode)7 BinaryExpression (org.codehaus.groovy.ast.expr.BinaryExpression)7 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)6 DeclarationExpression (org.codehaus.groovy.ast.expr.DeclarationExpression)6 AnnotationConstantExpression (org.codehaus.groovy.ast.expr.AnnotationConstantExpression)5 MapEntryExpression (org.codehaus.groovy.ast.expr.MapEntryExpression)5