Search in sources :

Example 6 with ImportNode

use of org.codehaus.groovy.ast.ImportNode in project gradle by gradle.

the class SubsetScriptTransformer method call.

public void call(SourceUnit source) throws CompilationFailedException {
    AstUtils.filterAndTransformStatements(source, transformer);
    // Filter imported classes which are not available yet
    Iterator<ImportNode> iter = source.getAST().getImports().iterator();
    while (iter.hasNext()) {
        ImportNode importedClass = iter.next();
        if (!AstUtils.isVisible(source, importedClass.getClassName())) {
            try {
                Field field = ModuleNode.class.getDeclaredField("imports");
                field.setAccessible(true);
                Map value = (Map) field.get(source.getAST());
                value.remove(importedClass.getAlias());
            } catch (Exception e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }
        }
    }
    iter = source.getAST().getStaticImports().values().iterator();
    while (iter.hasNext()) {
        ImportNode importedClass = iter.next();
        if (!AstUtils.isVisible(source, importedClass.getClassName())) {
            iter.remove();
        }
    }
    iter = source.getAST().getStaticStarImports().values().iterator();
    while (iter.hasNext()) {
        ImportNode importedClass = iter.next();
        if (!AstUtils.isVisible(source, importedClass.getClassName())) {
            iter.remove();
        }
    }
    ClassNode scriptClass = AstUtils.getScriptClass(source);
    // Remove all the classes other than the main class
    Iterator<ClassNode> classes = source.getAST().getClasses().iterator();
    while (classes.hasNext()) {
        ClassNode classNode = classes.next();
        if (classNode != scriptClass) {
            classes.remove();
        }
    }
    // Remove all the methods from the main class
    if (scriptClass != null) {
        for (MethodNode methodNode : new ArrayList<MethodNode>(scriptClass.getMethods())) {
            if (!methodNode.getName().equals("run")) {
                AstUtils.removeMethod(scriptClass, methodNode);
            }
        }
    }
    source.getAST().getMethods().clear();
}
Also used : Field(java.lang.reflect.Field) ClassNode(org.codehaus.groovy.ast.ClassNode) MethodNode(org.codehaus.groovy.ast.MethodNode) ArrayList(java.util.ArrayList) ImportNode(org.codehaus.groovy.ast.ImportNode) Map(java.util.Map) UncheckedException(org.gradle.internal.UncheckedException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException)

Example 7 with ImportNode

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

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);
                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);
        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) Statement(org.codehaus.groovy.ast.stmt.Statement) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) 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) StaticMethodCallExpression(org.codehaus.groovy.ast.expr.StaticMethodCallExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) Expression(org.codehaus.groovy.ast.expr.Expression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) ImportNode(org.codehaus.groovy.ast.ImportNode) File(java.io.File) ModuleNode(org.codehaus.groovy.ast.ModuleNode)

Example 8 with ImportNode

use of org.codehaus.groovy.ast.ImportNode in project groovy by apache.

the class AntlrParserPlugin method importDef.

protected void importDef(AST importNode) {
    try {
        // GROOVY-6094
        output.putNodeMetaData(ImportNode.class, ImportNode.class);
        boolean isStatic = importNode.getType() == STATIC_IMPORT;
        List<AnnotationNode> annotations = new ArrayList<AnnotationNode>();
        AST node = importNode.getFirstChild();
        if (isType(ANNOTATIONS, node)) {
            processAnnotations(annotations, node);
            node = node.getNextSibling();
        }
        String alias = null;
        if (isType(LITERAL_as, node)) {
            //import is like "import Foo as Bar"
            node = node.getFirstChild();
            AST aliasNode = node.getNextSibling();
            alias = identifier(aliasNode);
        }
        if (node.getNumberOfChildren() == 0) {
            String name = identifier(node);
            // import is like  "import Foo"
            ClassNode type = ClassHelper.make(name);
            configureAST(type, importNode);
            addImport(type, name, alias, annotations);
            return;
        }
        AST packageNode = node.getFirstChild();
        String packageName = qualifiedName(packageNode);
        AST nameNode = packageNode.getNextSibling();
        if (isType(STAR, nameNode)) {
            if (isStatic) {
                // import is like "import static foo.Bar.*"
                // packageName is actually a className in this case
                ClassNode type = ClassHelper.make(packageName);
                configureAST(type, importNode);
                addStaticStarImport(type, packageName, annotations);
            } else {
                // import is like "import foo.*"
                addStarImport(packageName, annotations);
            }
            if (alias != null)
                throw new GroovyBugError("imports like 'import foo.* as Bar' are not " + "supported and should be caught by the grammar");
        } else {
            String name = identifier(nameNode);
            if (isStatic) {
                // import is like "import static foo.Bar.method"
                // packageName is really class name in this case
                ClassNode type = ClassHelper.make(packageName);
                configureAST(type, importNode);
                addStaticImport(type, name, alias, annotations);
            } else {
                // import is like "import foo.Bar"
                ClassNode type = ClassHelper.make(packageName + "." + name);
                configureAST(type, importNode);
                addImport(type, name, alias, annotations);
            }
        }
    } finally {
        // we're using node metadata here in order to fix GROOVY-6094
        // without breaking external APIs
        Object node = output.getNodeMetaData(ImportNode.class);
        if (node != null && node != ImportNode.class) {
            configureAST((ImportNode) node, importNode);
        }
        output.removeNodeMetaData(ImportNode.class);
    }
}
Also used : EnumConstantClassNode(org.codehaus.groovy.ast.EnumConstantClassNode) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) ClassNode(org.codehaus.groovy.ast.ClassNode) AST(antlr.collections.AST) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) ArrayList(java.util.ArrayList) GroovyBugError(org.codehaus.groovy.GroovyBugError) ImportNode(org.codehaus.groovy.ast.ImportNode)

Example 9 with ImportNode

use of org.codehaus.groovy.ast.ImportNode in project groovy by apache.

the class StaticImportVisitor method findStaticFieldOrPropAccessorImportFromModule.

private Expression findStaticFieldOrPropAccessorImportFromModule(String name) {
    ModuleNode module = currentClass.getModule();
    if (module == null)
        return null;
    Map<String, ImportNode> importNodes = module.getStaticImports();
    Expression expression;
    String accessorName = getAccessorName(name);
    // when resolving prop reference
    if (importNodes.containsKey(accessorName)) {
        expression = findStaticProperty(importNodes, accessorName);
        if (expression != null)
            return expression;
    }
    if (accessorName.startsWith("get")) {
        accessorName = "is" + accessorName.substring(3);
        if (importNodes.containsKey(accessorName)) {
            expression = findStaticProperty(importNodes, accessorName);
            if (expression != null)
                return expression;
        }
    }
    // when resolving prop or field reference
    if (importNodes.containsKey(name)) {
        ImportNode importNode = importNodes.get(name);
        expression = findStaticPropertyAccessor(importNode.getType(), importNode.getFieldName());
        if (expression != null)
            return expression;
        expression = findStaticField(importNode.getType(), importNode.getFieldName());
        if (expression != null)
            return expression;
    }
    // when resolving prop or field reference
    for (ImportNode importNode : module.getStaticStarImports().values()) {
        ClassNode node = importNode.getType();
        expression = findStaticPropertyAccessor(node, name);
        if (expression != null)
            return expression;
        expression = findStaticField(node, name);
        if (expression != null)
            return expression;
    }
    return null;
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) StaticMethodCallExpression(org.codehaus.groovy.ast.expr.StaticMethodCallExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) NamedArgumentListExpression(org.codehaus.groovy.ast.expr.NamedArgumentListExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) EmptyExpression(org.codehaus.groovy.ast.expr.EmptyExpression) 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) AnnotationConstantExpression(org.codehaus.groovy.ast.expr.AnnotationConstantExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) TupleExpression(org.codehaus.groovy.ast.expr.TupleExpression) BinaryExpression(org.codehaus.groovy.ast.expr.BinaryExpression) MapEntryExpression(org.codehaus.groovy.ast.expr.MapEntryExpression) ImportNode(org.codehaus.groovy.ast.ImportNode) ModuleNode(org.codehaus.groovy.ast.ModuleNode)

Example 10 with ImportNode

use of org.codehaus.groovy.ast.ImportNode 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)

Aggregations

ImportNode (org.codehaus.groovy.ast.ImportNode)11 ClassNode (org.codehaus.groovy.ast.ClassNode)10 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)6 ModuleNode (org.codehaus.groovy.ast.ModuleNode)6 ConstantExpression (org.codehaus.groovy.ast.expr.ConstantExpression)6 Expression (org.codehaus.groovy.ast.expr.Expression)6 ListExpression (org.codehaus.groovy.ast.expr.ListExpression)6 StaticMethodCallExpression (org.codehaus.groovy.ast.expr.StaticMethodCallExpression)6 ArgumentListExpression (org.codehaus.groovy.ast.expr.ArgumentListExpression)5 MethodCallExpression (org.codehaus.groovy.ast.expr.MethodCallExpression)5 VariableExpression (org.codehaus.groovy.ast.expr.VariableExpression)5 ArrayList (java.util.ArrayList)4 AnnotationConstantExpression (org.codehaus.groovy.ast.expr.AnnotationConstantExpression)4 BinaryExpression (org.codehaus.groovy.ast.expr.BinaryExpression)4 ClassExpression (org.codehaus.groovy.ast.expr.ClassExpression)4 ClosureExpression (org.codehaus.groovy.ast.expr.ClosureExpression)4 ConstructorCallExpression (org.codehaus.groovy.ast.expr.ConstructorCallExpression)4 EmptyExpression (org.codehaus.groovy.ast.expr.EmptyExpression)4 MapEntryExpression (org.codehaus.groovy.ast.expr.MapEntryExpression)4 NamedArgumentListExpression (org.codehaus.groovy.ast.expr.NamedArgumentListExpression)4