Skip to content
Permalink
Browse files
GROOVY-10628: STC: fix inference for elvis assignment with setter target
  • Loading branch information
eric-milles committed May 19, 2022
1 parent 16f6be8 commit a976ecdee1f17f7fafc55767de2d857c44d44697
Showing 2 changed files with 38 additions and 10 deletions.
@@ -1020,10 +1020,15 @@ private boolean ensureValidSetter(final Expression expression, final Expression
}

Function<Expression, MethodNode> setterCall = right -> {
MethodCallExpression call = callX(receiver, setterInfo.name, right);
call.setImplicitThis(false);
visitMethodCallExpression(call);
return call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
typeCheckingContext.pushEnclosingBinaryExpression(null); // GROOVY-10628: LHS re-purposed
try {
MethodCallExpression call = new MethodCallExpression(receiver, setterInfo.name, right);
call.setImplicitThis(false);
visitMethodCallExpression(call);
return call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
} finally {
typeCheckingContext.popEnclosingBinaryExpression();
}
};

Function<MethodNode, ClassNode> setterType = setter -> {
@@ -1292,21 +1292,44 @@ class STCAssignmentTest extends StaticTypeCheckingTestCase {
}

// GROOVY-10419
void testElvisAssignmentAndSetter() {
void testElvisAssignmentAndSetter1() {
assertScript '''
class C {
def p
void setP(p) {
this.p = p
}
}
@groovy.transform.TypeChecked
void test(C c) {
c.p ?= 'x'
}
def c = new C()
test(c)
c.p ?= 'x'
assert c.p == 'x'
c.with {
p ?= 'y'
}
assert c.p == 'x'
'''
}

// GROOVY-10628
void testElvisAssignmentAndSetter2() {
assertScript '''
class C {
String getFoo() {
}
void setFoo(String foo) {
}
}
new C().foo ?= 'bar'
'''
}

void testElvisAssignmentMismatched() {
shouldFailWithMessages '''
class C {
Number foo
}
new C().foo ?= 'bar'
''',
'Cannot assign value of type java.io.Serializable to variable of type java.lang.Number'
}
}

0 comments on commit a976ecd

Please sign in to comment.