Skip to content

Commit

Permalink
GROOVY-11207: constant inlining: static field variable reference
Browse files Browse the repository at this point in the history
  • Loading branch information
eric-milles committed Oct 25, 2023
1 parent 0ec63a5 commit 745e3cd
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/main/java/org/apache/groovy/ast/tools/ExpressionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -231,16 +231,21 @@ public static Expression transformInlineConstants(final Expression exp) {
if (pe.getObjectExpression() instanceof ClassExpression) {
ClassNode clazz = pe.getObjectExpression().getType();
FieldNode field = ClassNodeUtils.getField(clazz, pe.getPropertyAsString());
if (field != null && !field.isEnum() && field.isFinal() && field.isStatic() && field.hasInitialExpression()) {
Expression value = transformInlineConstants(field.getInitialValueExpression()); // GROOVY-10750
if (field != null && !field.isEnum() && field.isFinal() && field.isStatic()) {
Expression value = transformInlineConstants(field.getInitialValueExpression(), field.getType()); // GROOVY-10750, GROOVY-10068
if (value instanceof ConstantExpression) {
value = new ConstantExpression(((ConstantExpression) value).getValue());
// GROOVY-10068, et al.: retain field's type
if (!value.getType().equals(field.getType())
&& ClassHelper.isNumberType(field.getType()))
value.setType(field.getType());
// TODO: Boolean, Character, String
return configure(exp, (ConstantExpression) value);
return configure(exp, new ConstantExpression(((ConstantExpression) value).getValue()));
}
}
}
} else if (exp instanceof VariableExpression) {
VariableExpression ve = (VariableExpression) exp;
if (ve.getAccessedVariable() instanceof FieldNode) {
FieldNode field = (FieldNode) ve.getAccessedVariable();
if (!field.isEnum() && field.isFinal() && field.isStatic()) {
Expression value = transformInlineConstants(field.getInitialValueExpression(), field.getType()); // GROOVY-11207, GROOVY-10068
if (value instanceof ConstantExpression) {
return configure(exp, new ConstantExpression(((ConstantExpression) value).getValue()));
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions src/test/gls/annotations/AnnotationTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,27 @@ final class AnnotationTest {
'''
}

// GROOVY-11207
@Test
void testAttributeValueConstants11() {
assertScript shell, '''
@Retention(RUNTIME)
@interface Foo {
String value()
}
@groovy.transform.CompileStatic
class Bar {
public static final String BASE = 'base'
@Foo('all your ' + BASE)
def baz() {
}
}
def foo = Bar.getMethod('baz').getAnnotation(Foo)
assert foo.value() == 'all your base'
'''
}

@Test
void testRuntimeRetentionAtAllLevels() {
assertScript shell, '''
Expand Down

0 comments on commit 745e3cd

Please sign in to comment.