Skip to content

Commit cddbd9c

Browse files
committed
GROOVY-11329: Class using trait and @immutable and allProperties gives BUG! exception in phase 'canonicalization' NPE
1 parent 555ebe0 commit cddbd9c

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/main/java/groovy/transform/options/ImmutablePropertyHandler.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,10 @@ private static Statement assignFieldWithDefault(final Parameter map, final Field
234234
get.setImplicitThis(false);
235235
MethodCallExpression containsKey = callX(varX(map), "containsKey", nameArg);
236236
containsKey.setImplicitThis(false);
237-
fNode.getDeclaringClass().getField(fNode.getName()).setInitialValueExpression(null); // to avoid default initialization
237+
// avoid NPE if no declaring class - can be the case for traits
238+
if (fNode.getDeclaringClass() != null) {
239+
fNode.getDeclaringClass().getField(fNode.getName()).setInitialValueExpression(null); // to avoid default initialization
240+
}
238241
return ifElseS(containsKey, assignStmt, assignInit);
239242
}
240243

src/test/org/codehaus/groovy/transform/ImmutableTransformTest.groovy

+19
Original file line numberDiff line numberDiff line change
@@ -1063,4 +1063,23 @@ final class ImmutableTransformTest {
10631063
assert obj['data'][2L] == 'bar'
10641064
'''
10651065
}
1066+
1067+
// GROOVY-11329
1068+
@Test
1069+
void testAllPropertiesAndTrait() {
1070+
assertScript shell, '''
1071+
import groovy.transform.Immutable
1072+
1073+
trait T {
1074+
String foo
1075+
}
1076+
1077+
@Immutable(allProperties=true)
1078+
class C implements T {
1079+
String bar
1080+
}
1081+
1082+
assert new C('bar', 'foo').toString() == 'C(bar, foo)'
1083+
'''
1084+
}
10661085
}

0 commit comments

Comments
 (0)