Search in sources :

Example 36 with CompilerConfiguration

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

the class ClassicGroovyTestGeneratorHelper method evaluate.

/** evaluate the source text against the classic AST with the JSR parser implementation*/
public Object evaluate(String theSrcText, String testName) throws Exception {
    // fail early with a direct message if possible')
    parse(theSrcText, testName);
    GroovyShell groovy = new GroovyShell(new CompilerConfiguration());
    return groovy.run(theSrcText, "main", new ArrayList());
}
Also used : CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) ArrayList(java.util.ArrayList) GroovyShell(groovy.lang.GroovyShell)

Example 37 with CompilerConfiguration

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

the class WriterController method init.

public void init(AsmClassGenerator asmClassGenerator, GeneratorContext gcon, ClassVisitor cv, ClassNode cn) {
    CompilerConfiguration config = cn.getCompileUnit().getConfig();
    Map<String, Boolean> optOptions = config.getOptimizationOptions();
    boolean invokedynamic = false;
    if (optOptions.isEmpty()) {
    // IGNORE
    } else if (Boolean.FALSE.equals(optOptions.get("all"))) {
        optimizeForInt = false;
    // set other optimizations options to false here
    } else {
        if (Boolean.TRUE.equals(optOptions.get(CompilerConfiguration.INVOKEDYNAMIC)))
            invokedynamic = true;
        if (Boolean.FALSE.equals(optOptions.get("int")))
            optimizeForInt = false;
        if (invokedynamic)
            optimizeForInt = false;
    // set other optimizations options to false here
    }
    this.classNode = cn;
    this.outermostClass = null;
    this.internalClassName = BytecodeHelper.getClassInternalName(classNode);
    bytecodeVersion = chooseBytecodeVersion(invokedynamic, config.getTargetBytecode());
    if (invokedynamic) {
        try {
            this.invocationWriter = (InvocationWriter) indyWriter.newInstance(this);
            this.callSiteWriter = (CallSiteWriter) indyCallSiteWriter.newInstance(this);
            this.binaryExpHelper = (BinaryExpressionHelper) indyBinHelper.newInstance(this);
        } catch (Exception e) {
            throw new GroovyRuntimeException("Cannot use invokedynamic, indy module was excluded from this build.");
        }
    } else {
        this.callSiteWriter = new CallSiteWriter(this);
        this.invocationWriter = new InvocationWriter(this);
        this.binaryExpHelper = new BinaryExpressionHelper(this);
    }
    this.unaryExpressionHelper = new UnaryExpressionHelper(this);
    if (optimizeForInt) {
        this.fastPathBinaryExpHelper = new BinaryExpressionMultiTypeDispatcher(this);
        // todo: replace with a real fast path unary expression helper when available
        this.fastPathUnaryExpressionHelper = new UnaryExpressionHelper(this);
    } else {
        this.fastPathBinaryExpHelper = this.binaryExpHelper;
        this.fastPathUnaryExpressionHelper = new UnaryExpressionHelper(this);
    }
    this.operandStack = new OperandStack(this);
    this.assertionWriter = new AssertionWriter(this);
    this.closureWriter = new ClosureWriter(this);
    this.internalBaseClassName = BytecodeHelper.getClassInternalName(classNode.getSuperClass());
    this.acg = asmClassGenerator;
    this.sourceUnit = acg.getSourceUnit();
    this.context = gcon;
    this.compileStack = new CompileStack(this);
    this.cv = cv;
    if (optimizeForInt) {
        this.statementWriter = new OptimizingStatementWriter(this);
    } else {
        this.statementWriter = new StatementWriter(this);
    }
    this.typeChooser = new StatementMetaTypeChooser();
}
Also used : GroovyRuntimeException(groovy.lang.GroovyRuntimeException) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

Example 38 with CompilerConfiguration

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

the class GroovyShellTest method testScriptWithCustomBodyMethod.

/**
     * Test for GROOVY-6615
     * @throws Exception
     */
public void testScriptWithCustomBodyMethod() throws Exception {
    Binding context = new Binding();
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(BaseScriptCustomBodyMethod.class.getName());
    GroovyShell shell = new GroovyShell(context, config);
    Object result = shell.evaluate("'I like ' + cheese");
    assertEquals("I like Cheddar", result);
}
Also used : CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

Example 39 with CompilerConfiguration

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

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 40 with CompilerConfiguration

use of org.codehaus.groovy.control.CompilerConfiguration in project cas by apereo.

the class CoreAuthenticationUtils method newCredentialSelectionPredicate.

/**
 * Gets credential selection predicate.
 *
 * @param selectionCriteria the selection criteria
 * @return the credential selection predicate
 */
public static Predicate<Credential> newCredentialSelectionPredicate(final String selectionCriteria) {
    try {
        if (StringUtils.isBlank(selectionCriteria)) {
            return credential -> true;
        }
        if (selectionCriteria.endsWith(".groovy")) {
            final ResourceLoader loader = new DefaultResourceLoader();
            final Resource resource = loader.getResource(selectionCriteria);
            if (resource != null) {
                final String script = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
                final GroovyClassLoader classLoader = new GroovyClassLoader(Beans.class.getClassLoader(), new CompilerConfiguration(), true);
                final Class<Predicate> clz = classLoader.parseClass(script);
                return clz.getDeclaredConstructor().newInstance();
            }
        }
        final Class predicateClazz = ClassUtils.getClass(selectionCriteria);
        return (Predicate<org.apereo.cas.authentication.Credential>) predicateClazz.getDeclaredConstructor().newInstance();
    } catch (final Exception e) {
        final Predicate<String> predicate = Pattern.compile(selectionCriteria).asPredicate();
        return credential -> predicate.test(credential.getId());
    }
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) ResourceLoader(org.springframework.core.io.ResourceLoader) Predicate(java.util.function.Predicate) Beans(org.apereo.cas.configuration.support.Beans) Multimap(com.google.common.collect.Multimap) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) StringUtils(org.apache.commons.lang3.StringUtils) StandardCharsets(java.nio.charset.StandardCharsets) UtilityClass(lombok.experimental.UtilityClass) IOUtils(org.apache.commons.io.IOUtils) ClassUtils(org.apache.commons.lang3.ClassUtils) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) Pattern(java.util.regex.Pattern) Splitter(com.google.common.base.Splitter) GroovyClassLoader(groovy.lang.GroovyClassLoader) Resource(org.springframework.core.io.Resource) ResourceLoader(org.springframework.core.io.ResourceLoader) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Resource(org.springframework.core.io.Resource) Predicate(java.util.function.Predicate) GroovyClassLoader(groovy.lang.GroovyClassLoader) Beans(org.apereo.cas.configuration.support.Beans) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) UtilityClass(lombok.experimental.UtilityClass) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader)

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