Skip to content

Commit

Permalink
Use a single-letter name for primitives so there's a hope of it compi…
Browse files Browse the repository at this point in the history
…ling.

PiperOrigin-RevId: 700375854
  • Loading branch information
graememorgan authored and Error Prone Team committed Nov 26, 2024
1 parent c59a1c9 commit 7ee554f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.SourceVersion.supportsPatternMatchingInstanceof;

import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
Expand All @@ -41,6 +42,7 @@
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import org.jspecify.annotations.Nullable;

/** A BugPattern; see the summary. */
Expand All @@ -66,7 +68,16 @@ public Description matchInstanceOf(InstanceOfTree instanceOfTree, VisitorState s
if (!allCasts.isEmpty()) {
// This is a gamble as to an appropriate name. We could make sure it doesn't clash with
// anything in scope, but that's effort.
var name = lowerFirstLetter(targetType.tsym.getSimpleName().toString());
String name;
var unboxed = state.getTypes().unboxedType(targetType);
if (targetType.isPrimitive() || (unboxed != null && unboxed.getTag() != TypeTag.NONE)) {
name =
String.valueOf(
Ascii.toLowerCase(targetType.tsym.getSimpleName().toString().charAt(0)));
} else {
name = lowerFirstLetter(targetType.tsym.getSimpleName().toString());
}

return describeMatch(
instanceOfTree,
SuggestedFix.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,36 @@ void test(Object o) {
.doTest();
}

@Test
public void primitiveType_shortNameChosen() {
helper
.addInputLines(
"Test.java",
"""
class Test {
void test(Object o) {
if (o instanceof Long) {
test((Long) o);
test(((Long) o).hashCode());
}
}
}
""")
.addOutputLines(
"Test.java",
"""
class Test {
void test(Object o) {
if (o instanceof Long l) {
test(l);
test(l.hashCode());
}
}
}
""")
.doTest();
}

@Test
public void genericWithUpperBoundedWildcard() {
helper
Expand Down

0 comments on commit 7ee554f

Please sign in to comment.