Skip to content

Commit

Permalink
Codegen Primitives in record comonent patterns to be enabled with nul…
Browse files Browse the repository at this point in the history
…l check before calling accessor(#3361)

Before generating an invoke of accessor of a record component, do a null check if primitive conversions are involved.
  • Loading branch information
mpalat authored Nov 29, 2024
1 parent 8eb06ef commit 352a0aa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ original record instance as receiver - leaving the stack drained.
labels.add(exceptionLabel);

TypeBinding componentType = p.accessorMethod.returnType;
checkForPrimitiveType(currentScope, p, componentType);
if (TypeBinding.notEquals(p.accessorMethod.original().returnType.erasure(),
componentType.erasure()))
codeStream.checkcast(componentType); // lastComponent ? [C] : [R, C]
Expand Down Expand Up @@ -291,6 +292,18 @@ original record instance as receiver - leaving the stack drained.
}
}

private void checkForPrimitiveType(BlockScope currentScope, Pattern p, TypeBinding componentType) {
if (p.isTotalTypeNode && !componentType.isPrimitiveType() && p instanceof TypePattern tp) {
TypeBinding providedType = tp.resolvedType;
if (providedType != null && providedType.isPrimitiveType()) {
PrimitiveConversionRoute route = Pattern.findPrimitiveConversionRoute(componentType, providedType, currentScope);
if (route != PrimitiveConversionRoute.NO_CONVERSION_ROUTE) {
p.isTotalTypeNode = false;
}
}
}
}

@Override
public void traverse(ASTVisitor visitor, BlockScope scope) {
if (visitor.visit(this, scope)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class PrimitiveInPatternsTest extends AbstractRegressionTest9 {
static {
// TESTS_NUMBERS = new int [] { 1 };
// TESTS_RANGE = new int[] { 1, -1 };
// TESTS_NAMES = new String[] { "testIssue2936" };
// TESTS_NAMES = new String[] { "testIssuePrimitivesWithNull" };
}
private String extraLibPath;
public static Class<?> testClass() {
Expand Down Expand Up @@ -7331,6 +7331,24 @@ public static void main(String[] args) {
"43.0");
}

public void testIssuePrimitivesWithNull() {
runConformTest(new String[] {
"X.java",
"""
public class X {
record R(Integer i) {}
public static int foo(R r) {
if (r instanceof R(int i)) { return i; }
return -1;
}
public static void main(String argv[]) {
System.out.println(foo(new R(null)));
}
}
"""
},
"-1");
}
public void _testSpec00X() {
runNegativeTest(new String[] {
"X.java",
Expand Down

0 comments on commit 352a0aa

Please sign in to comment.