use of org.codehaus.groovy.control.CompilerConfiguration in project groovy by apache.
the class GroovyShellTest method testClassLoader.
public void testClassLoader() {
Binding context = new Binding();
CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass(DerivedScript.class.getName());
GroovyShell shell = new GroovyShell(context, config);
String script = "evaluate '''\n" + "class XXXX{}\n" + "assert evaluate('XXXX') == XXXX\n" + "'''";
shell.evaluate(script);
}
use of org.codehaus.groovy.control.CompilerConfiguration in project groovy by apache.
the class GroovyMain method process.
/**
* Process the users request.
*
* @param line the parsed command line.
* @throws ParseException if invalid options are chosen
*/
private static boolean process(CommandLine line) throws ParseException, IOException {
List args = line.getArgList();
if (line.hasOption('D')) {
String[] values = line.getOptionValues('D');
for (int i = 0; i < values.length; i++) {
setSystemPropertyFrom(values[i]);
}
}
GroovyMain main = new GroovyMain();
// add the ability to parse scripts with a specified encoding
main.conf.setSourceEncoding(line.getOptionValue('c', main.conf.getSourceEncoding()));
main.isScriptFile = !line.hasOption('e');
main.debug = line.hasOption('d');
main.conf.setDebug(main.debug);
main.conf.setParameters(line.hasOption("pa"));
main.processFiles = line.hasOption('p') || line.hasOption('n');
main.autoOutput = line.hasOption('p');
main.editFiles = line.hasOption('i');
if (main.editFiles) {
main.backupExtension = line.getOptionValue('i');
}
main.autoSplit = line.hasOption('a');
String sp = line.getOptionValue('a');
if (sp != null)
main.splitPattern = sp;
if (main.isScriptFile) {
if (args.isEmpty())
throw new ParseException("neither -e or filename provided");
main.script = (String) args.remove(0);
if (main.script.endsWith(".java"))
throw new ParseException("error: cannot compile file with .java extension: " + main.script);
} else {
main.script = line.getOptionValue('e');
}
main.processSockets = line.hasOption('l');
if (main.processSockets) {
// default port to listen to
String p = line.getOptionValue('l', "1960");
main.port = Integer.parseInt(p);
}
// we use "," as default, because then split will create
// an empty array if no option is set
String disabled = line.getOptionValue("disableopt", ",");
String[] deopts = disabled.split(",");
for (String deopt_i : deopts) {
main.conf.getOptimizationOptions().put(deopt_i, false);
}
if (line.hasOption("indy")) {
CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
main.conf.getOptimizationOptions().put("indy", true);
}
if (line.hasOption("basescript")) {
main.conf.setScriptBaseClass(line.getOptionValue("basescript"));
}
if (line.hasOption("configscript")) {
String path = line.getOptionValue("configscript");
File groovyConfigurator = new File(path);
Binding binding = new Binding();
binding.setVariable("configuration", main.conf);
CompilerConfiguration configuratorConfig = new CompilerConfiguration();
ImportCustomizer customizer = new ImportCustomizer();
customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
configuratorConfig.addCompilationCustomizers(customizer);
GroovyShell shell = new GroovyShell(binding, configuratorConfig);
shell.evaluate(groovyConfigurator);
}
main.args = args;
return main.run();
}
use of org.codehaus.groovy.control.CompilerConfiguration in project groovy by apache.
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, OBJECT_TYPE);
ReturnStatement code = new ReturnStatement(expr);
node.addMethod(new MethodNode("eval", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, 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);
}
}
use of org.codehaus.groovy.control.CompilerConfiguration in project hudson-2.x by hudson.
the class BeanBuilder method parse.
/**
* Parses the bean definition groovy script by first exporting the given {@link Binding}.
*/
public void parse(InputStream script, Binding binding) {
setBinding(binding);
CompilerConfiguration cc = new CompilerConfiguration();
cc.setScriptBaseClass(ClosureScript.class.getName());
GroovyShell shell = new GroovyShell(classLoader, binding, cc);
ClosureScript s = (ClosureScript) shell.parse(script);
s.setDelegate(this);
s.run();
}
use of org.codehaus.groovy.control.CompilerConfiguration in project spring-boot by spring-projects.
the class GroovyCompiler method compile.
/**
* Compile the specified Groovy sources, applying any
* {@link CompilerAutoConfiguration}s. All classes defined in the sources will be
* returned from this method.
* @param sources the sources to compile
* @return compiled classes
* @throws CompilationFailedException in case of compilation failures
* @throws IOException in case of I/O errors
* @throws CompilationFailedException in case of compilation errors
*/
public Class<?>[] compile(String... sources) throws CompilationFailedException, IOException {
this.loader.clearCache();
List<Class<?>> classes = new ArrayList<>();
CompilerConfiguration configuration = this.loader.getConfiguration();
CompilationUnit compilationUnit = new CompilationUnit(configuration, null, this.loader);
ClassCollector collector = this.loader.createCollector(compilationUnit, null);
compilationUnit.setClassgenCallback(collector);
for (String source : sources) {
List<String> paths = ResourceUtils.getUrls(source, this.loader);
for (String path : paths) {
compilationUnit.addSource(new URL(path));
}
}
addAstTransformations(compilationUnit);
compilationUnit.compile(Phases.CLASS_GENERATION);
for (Object loadedClass : collector.getLoadedClasses()) {
classes.add((Class<?>) loadedClass);
}
ClassNode mainClassNode = MainClass.get(compilationUnit);
Class<?> mainClass = null;
for (Class<?> loadedClass : classes) {
if (mainClassNode.getName().equals(loadedClass.getName())) {
mainClass = loadedClass;
}
}
if (mainClass != null) {
classes.remove(mainClass);
classes.add(0, mainClass);
}
return classes.toArray(new Class<?>[classes.size()]);
}
Aggregations