use of org.codehaus.groovy.ast.ClassHelper.STRING_TYPE 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.
* <p>
* 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(final Expression expr, final CompilerConfiguration config) {
Expression ce = expr instanceof CastExpression ? ((CastExpression) expr).getExpression() : expr;
if (ce instanceof ConstantExpression) {
if (expr.getType().equals(ce.getType()))
return ((ConstantExpression) ce).getValue();
} else if (ce instanceof ListExpression) {
if (expr.getType().isArray() && expr.getType().getComponentType().equals(STRING_TYPE))
return ((ListExpression) ce).getExpressions().stream().map(e -> evaluateExpression(e, config)).toArray(String[]::new);
}
String className = "Expression$" + UUID.randomUUID().toString().replace('-', '$');
ClassNode simpleClass = new ClassNode(className, Opcodes.ACC_PUBLIC, OBJECT_TYPE);
addGeneratedMethod(simpleClass, "eval", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, new ReturnStatement(expr));
// adjust configuration so class can be inspected by this JVM
CompilerConfiguration cc = new CompilerConfiguration(config);
// unlikely to be required by expression
cc.setPreviewFeatures(false);
cc.setTargetBytecode(CompilerConfiguration.DEFAULT.getTargetBytecode());
CompilationUnit cu = new CompilationUnit(cc);
try {
cu.addClassNode(simpleClass);
cu.compile(Phases.CLASS_GENERATION);
List<GroovyClass> classes = cu.getClasses();
Class<?> aClass = cu.getClassLoader().defineClass(className, classes.get(0).getBytes());
try {
return aClass.getMethod("eval").invoke(null);
} catch (ReflectiveOperationException e) {
throw new GroovyBugError(e);
}
} finally {
closeQuietly(cu.getClassLoader());
}
}
Aggregations