Search in sources :

Example 21 with CompilerConfiguration

use of org.codehaus.groovy.control.CompilerConfiguration in project grails-core by grails.

the class GroovyPagesTemplateEngine method initGroovyClassLoader.

private GroovyClassLoader initGroovyClassLoader(ClassLoader parent) {
    CompilerConfiguration compConfig = new CompilerConfiguration();
    compConfig.setSourceEncoding(GroovyPageParser.GROOVY_SOURCE_CHAR_ENCODING);
    return new GroovyPageClassLoader(parent, compConfig);
}
Also used : CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

Example 22 with CompilerConfiguration

use of org.codehaus.groovy.control.CompilerConfiguration in project groovy-core by groovy.

the class GroovyTypeCheckingExtensionSupport method setup.

@Override
public void setup() {
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass("org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport.TypeCheckingDSL");
    ImportCustomizer ic = new ImportCustomizer();
    ic.addStarImports("org.codehaus.groovy.ast.expr");
    ic.addStaticStars("org.codehaus.groovy.ast.ClassHelper");
    ic.addStaticStars("org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport");
    config.addCompilationCustomizers(ic);
    final GroovyClassLoader transformLoader = compilationUnit != null ? compilationUnit.getTransformLoader() : typeCheckingVisitor.getSourceUnit().getClassLoader();
    // since Groovy 2.2, it is possible to use FQCN for type checking extension scripts
    TypeCheckingDSL script = null;
    try {
        Class<?> clazz = transformLoader.loadClass(scriptPath, false, true);
        if (TypeCheckingDSL.class.isAssignableFrom(clazz)) {
            script = (TypeCheckingDSL) clazz.newInstance();
        } else if (TypeCheckingExtension.class.isAssignableFrom(clazz)) {
            // since 2.4, we can also register precompiled type checking extensions which are not scripts
            try {
                Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(StaticTypeCheckingVisitor.class);
                TypeCheckingExtension extension = (TypeCheckingExtension) declaredConstructor.newInstance(typeCheckingVisitor);
                typeCheckingVisitor.addTypeCheckingExtension(extension);
                extension.setup();
                return;
            } catch (InstantiationException e) {
                addLoadingError(config);
            } catch (IllegalAccessException e) {
                addLoadingError(config);
            } catch (NoSuchMethodException e) {
                context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' could not be loaded because it doesn't have a constructor accepting StaticTypeCheckingVisitor.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
            } catch (InvocationTargetException e) {
                addLoadingError(config);
            }
        }
    } catch (ClassNotFoundException e) {
    // silent
    } catch (InstantiationException e) {
        addLoadingError(config);
    } catch (IllegalAccessException e) {
        addLoadingError(config);
    }
    if (script == null) {
        ClassLoader cl = typeCheckingVisitor.getSourceUnit().getClassLoader();
        // cast to prevent incorrect @since 1.7 warning
        InputStream is = ((ClassLoader) transformLoader).getResourceAsStream(scriptPath);
        if (is == null) {
            // fallback to the source unit classloader
            is = cl.getResourceAsStream(scriptPath);
        }
        if (is == null) {
            // fallback to the compiler classloader
            cl = GroovyTypeCheckingExtensionSupport.class.getClassLoader();
            is = cl.getResourceAsStream(scriptPath);
        }
        if (is == null) {
            // if the input stream is still null, we've not found the extension
            context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' was not found on the classpath.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
        }
        try {
            GroovyShell shell = new GroovyShell(transformLoader, new Binding(), config);
            script = (TypeCheckingDSL) shell.parse(new InputStreamReader(is, typeCheckingVisitor.getSourceUnit().getConfiguration().getSourceEncoding()));
        } catch (CompilationFailedException e) {
            throw new GroovyBugError("An unexpected error was thrown during custom type checking", e);
        } catch (UnsupportedEncodingException e) {
            throw new GroovyBugError("Unsupported encoding found in compiler configuration", e);
        }
    }
    if (script != null) {
        script.extension = this;
        script.run();
        List<Closure> list = eventHandlers.get("setup");
        if (list != null) {
            for (Closure closure : list) {
                safeCall(closure);
            }
        }
    }
}
Also used : Closure(groovy.lang.Closure) GroovyBugError(org.codehaus.groovy.GroovyBugError) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) GroovyClassLoader(groovy.lang.GroovyClassLoader) ImportCustomizer(org.codehaus.groovy.control.customizers.ImportCustomizer) Binding(groovy.lang.Binding) InputStreamReader(java.io.InputStreamReader) Constructor(java.lang.reflect.Constructor) InputStream(java.io.InputStream) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GroovyShell(groovy.lang.GroovyShell)

Example 23 with CompilerConfiguration

use of org.codehaus.groovy.control.CompilerConfiguration in project groovy-core by groovy.

the class StaticTypeCheckingSupport method evaluateExpression.

/**
     * A helper method that can be used to evaluate expressions as found in annotation
     * parameters. For example, it will evaluate a constant, be it referenced directly as
     * an integer or as a reference to a field.
     *
     * If this method throws an exception, then the expression cannot be evaluated on its own.
     *
     * @param expr the expression to be evaluated
     * @param config the compiler configuration
     * @return the result of the expression
     */
public static Object evaluateExpression(Expression expr, CompilerConfiguration config) {
    String className = "Expression$" + UUID.randomUUID().toString().replace('-', '$');
    ClassNode node = new ClassNode(className, Opcodes.ACC_PUBLIC, ClassHelper.OBJECT_TYPE);
    ReturnStatement code = new ReturnStatement(expr);
    node.addMethod(new MethodNode("eval", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, ClassHelper.OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, code));
    CompilerConfiguration copyConf = new CompilerConfiguration(config);
    CompilationUnit cu = new CompilationUnit(copyConf);
    cu.addClassNode(node);
    cu.compile(Phases.CLASS_GENERATION);
    @SuppressWarnings("unchecked") List<GroovyClass> classes = (List<GroovyClass>) cu.getClasses();
    Class aClass = cu.getClassLoader().defineClass(className, classes.get(0).getBytes());
    try {
        return aClass.getMethod("eval").invoke(null);
    } catch (IllegalAccessException e) {
        throw new GroovyBugError(e);
    } catch (InvocationTargetException e) {
        throw new GroovyBugError(e);
    } catch (NoSuchMethodException e) {
        throw new GroovyBugError(e);
    }
}
Also used : CompilationUnit(org.codehaus.groovy.control.CompilationUnit) GroovyClass(org.codehaus.groovy.tools.GroovyClass) GroovyBugError(org.codehaus.groovy.GroovyBugError) InvocationTargetException(java.lang.reflect.InvocationTargetException) ReturnStatement(org.codehaus.groovy.ast.stmt.ReturnStatement) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) GroovyClass(org.codehaus.groovy.tools.GroovyClass)

Example 24 with CompilerConfiguration

use of org.codehaus.groovy.control.CompilerConfiguration in project groovy-core by groovy.

the class ProxyGeneratorAdapter method adjustSuperClass.

private Class adjustSuperClass(Class superClass, final Class[] interfaces) {
    boolean isSuperClassAnInterface = superClass.isInterface();
    if (!isSuperClassAnInterface) {
        return superClass;
    }
    Class result = Object.class;
    Set<ClassNode> traits = new LinkedHashSet<ClassNode>();
    // check if it's a trait
    collectTraits(superClass, traits);
    if (interfaces != null) {
        for (Class anInterface : interfaces) {
            collectTraits(anInterface, traits);
        }
    }
    if (!traits.isEmpty()) {
        String name = superClass.getName() + "$TraitAdapter";
        ClassNode cn = new ClassNode(name, ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE, traits.toArray(new ClassNode[traits.size()]), null);
        CompilationUnit cu = new CompilationUnit(loader);
        CompilerConfiguration config = new CompilerConfiguration();
        SourceUnit su = new SourceUnit(name + "wrapper", "", config, loader, new ErrorCollector(config));
        cu.addSource(su);
        cu.compile(Phases.CONVERSION);
        su.getAST().addClass(cn);
        cu.compile(Phases.CLASS_GENERATION);
        @SuppressWarnings("unchecked") List<GroovyClass> classes = (List<GroovyClass>) cu.getClasses();
        for (GroovyClass groovyClass : classes) {
            if (groovyClass.getName().equals(name)) {
                return loader.defineClass(name, groovyClass.getBytes());
            }
        }
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) CompilationUnit(org.codehaus.groovy.control.CompilationUnit) ClassNode(org.codehaus.groovy.ast.ClassNode) GroovyClass(org.codehaus.groovy.tools.GroovyClass) ErrorCollector(org.codehaus.groovy.control.ErrorCollector) SourceUnit(org.codehaus.groovy.control.SourceUnit) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) GroovyClass(org.codehaus.groovy.tools.GroovyClass) GroovyObject(groovy.lang.GroovyObject) ArrayList(java.util.ArrayList) List(java.util.List)

Example 25 with CompilerConfiguration

use of org.codehaus.groovy.control.CompilerConfiguration in project gradle by gradle.

the class DefaultScriptCompilationHandler method createBaseCompilerConfiguration.

private CompilerConfiguration createBaseCompilerConfiguration(Class<? extends Script> scriptBaseClass) {
    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.setScriptBaseClass(scriptBaseClass.getName());
    return configuration;
}
Also used : CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

Aggregations

CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)42 GroovyShell (groovy.lang.GroovyShell)14 Binding (groovy.lang.Binding)10 File (java.io.File)10 ImportCustomizer (org.codehaus.groovy.control.customizers.ImportCustomizer)9 CompilationUnit (org.codehaus.groovy.control.CompilationUnit)8 GroovyClassLoader (groovy.lang.GroovyClassLoader)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 HashMap (java.util.HashMap)4 GroovyBugError (org.codehaus.groovy.GroovyBugError)4 ClassNode (org.codehaus.groovy.ast.ClassNode)4 GroovyClass (org.codehaus.groovy.tools.GroovyClass)4 Map (java.util.Map)3 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)3 SimpleMessage (org.codehaus.groovy.control.messages.SimpleMessage)3 Closure (groovy.lang.Closure)2 GroovyObject (groovy.lang.GroovyObject)2 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)2