Skip to content
Permalink
Browse files
GROOVY-10497: @NamedVariant: don't replace explicit value with default
  • Loading branch information
eric-milles authored and paulk-asert committed Feb 19, 2022
1 parent 813c318 commit 7730ef0d567fb1448a757c2d4ae118f9130e90c9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
@@ -70,10 +70,12 @@
import static org.codehaus.groovy.ast.tools.GeneralUtils.getAllProperties;
import static org.codehaus.groovy.ast.tools.GeneralUtils.list2args;
import static org.codehaus.groovy.ast.tools.GeneralUtils.mapX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.notNullX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.param;
import static org.codehaus.groovy.ast.tools.GeneralUtils.plusX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.propX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt;
import static org.codehaus.groovy.ast.tools.GeneralUtils.ternaryX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;

@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
@@ -278,13 +280,17 @@ private static Expression namedParamValue(final Parameter mapParam, final String
defaultValue = defaultValueX(type);
}
if (defaultValue != null) {
value = elvisX(value, defaultValue);
if (isPrimitiveType(type)) { // handle null for primitive
value = ternaryX(notNullX(value), value, defaultValueX(type));
}
value = ternaryX(containsKey(mapParam, name), value, defaultValue);
}
return asType(value, type, coerce);
}

private static Expression containsKey(final Parameter mapParam, final String name) {
MethodCallExpression call = callX(varX(mapParam), "containsKey", constX(name));
call.setImplicitThis(false); // required for use before super ctor call
call.setMethodTarget(MAP_TYPE.getMethods("containsKey").get(0));
return call;
}
@@ -192,7 +192,7 @@ final class NamedVariantTransformTest {
'''
}

@Test // GROOVY-9158
@Test // GROOVY-9158, GROOVY-10497
void testNamedParamWithDefaultArgument() {
assertScript '''
import groovy.transform.*
@@ -226,6 +226,21 @@ final class NamedVariantTransformTest {
m()
}
'''

assertScript '''
import groovy.transform.*
@NamedVariant
def m(int one, int two = 42) {
"$one $two"
}
String result = m(one:0, two:0)
assert result == '0 0'
result = m(one:0, two:null)
assert result == '0 0'
'''
}

@Test // GROOVY-10176

0 comments on commit 7730ef0

Please sign in to comment.