Ignore type variable casts in ClassCastLambdaUsage check (#1449)

This commit is contained in:
Mohamed Sameh
2024-12-16 15:47:36 +01:00
committed by GitHub
parent aec56ce025
commit 8dbff50a8b
2 changed files with 15 additions and 10 deletions

View File

@@ -18,6 +18,7 @@ import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Type;
import javax.lang.model.type.TypeKind;
import tech.picnic.errorprone.utils.SourceCode;
/**
@@ -48,11 +49,14 @@ public final class ClassCastLambdaUsage extends BugChecker implements LambdaExpr
}
Type type = ASTHelpers.getType(typeCast);
if (type == null || type.isParameterized() || type.isPrimitive()) {
if (type == null
|| type.isParameterized()
|| type.isPrimitive()
|| type.getKind() == TypeKind.TYPEVAR) {
/*
* The method reference syntax does not support casting to parameterized types. Additionally,
* `Class#cast` does not support the same range of type conversions between (boxed) primitive
* types as the cast operator.
* The method reference syntax does not support casting to parameterized types, and type
* variables aren't supported either. Additionally, `Class#cast` does not support the same
* range of type conversions between (boxed) primitive types as the cast operator.
*/
// XXX: Depending on the declared type of the value being cast, in some cases we _can_ rewrite
// primitive casts. Add support for this.

View File

@@ -16,7 +16,7 @@ final class ClassCastLambdaUsageTest {
"import java.util.stream.Stream;",
"",
"class A {",
" void m() {",
" <T> void m() {",
" Number localVariable = 0;",
"",
" Stream.of(0).map(i -> i);",
@@ -32,13 +32,14 @@ final class ClassCastLambdaUsageTest {
" i -> {",
" return (Integer) i;",
" });",
" Stream.<ImmutableSet>of(ImmutableSet.of(5)).map(s -> (ImmutableSet<Number>) s);",
" Stream.of(ImmutableSet.of(6)).map(s -> (ImmutableSet<?>) s);",
" Stream.of(7).reduce((a, b) -> (Integer) a);",
" IntStream.of(8).mapToObj(i -> (char) i);",
" Stream.<ImmutableSet>of(ImmutableSet.of(6)).map(s -> (ImmutableSet<Number>) s);",
" Stream.of(ImmutableSet.of(7)).map(s -> (ImmutableSet<?>) s);",
" Stream.of(8).reduce((a, b) -> (Integer) a);",
" IntStream.of(9).mapToObj(i -> (char) i);",
" Stream.of(10).map(i -> (T) i);",
"",
" // BUG: Diagnostic contains:",
" Stream.of(8).map(i -> (Integer) i);",
" Stream.of(11).map(i -> (Integer) i);",
" }",
"}")
.doTest();