Skip to content

Commit ab4e7bd

Browse files
graememorganError Prone Team
authored andcommitted
Improve diagnostic message for unused parameters that are reassigned.
PiperOrigin-RevId: 864792550
1 parent 0aaf576 commit ab4e7bd

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -267,14 +267,21 @@ public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState s
267267
if (suggestUnderscore(state, isEverUsed, unusedSymbol, specs, allUsageSites)) {
268268
fixes.add(SuggestedFixes.renameVariable((VariableTree) unused, "_", state));
269269
}
270+
String message;
271+
if (!isEverUsed.contains(symbol)) {
272+
message =
273+
String.format("The %s '%s' is never read.", describeVariable(symbol), symbol.name);
274+
} else if (unused instanceof VariableTree && symbol.getKind() == ElementKind.PARAMETER) {
275+
message = String.format("The parameter '%s' is reassigned before being read.", symbol.name);
276+
} else {
277+
message =
278+
String.format(
279+
"This assignment to the %s '%s' is never read.",
280+
describeVariable(symbol), symbol.name);
281+
}
270282
state.reportMatch(
271283
buildDescription(unused)
272-
.setMessage(
273-
String.format(
274-
"%s %s '%s' is never read.",
275-
isEverUsed.contains(symbol) ? "This assignment to the" : "The",
276-
describeVariable(symbol),
277-
symbol.name))
284+
.setMessage(message)
278285
.addAllFixes(
279286
fixes.build().stream()
280287
.map(f -> SuggestedFix.merge(makeFirstAssignmentDeclaration, f))

core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,6 +1324,23 @@ public int test() {
13241324
.doTest();
13251325
}
13261326

1327+
@Test
1328+
public void unusedParameterImplicitAssignment() {
1329+
helper
1330+
.addSourceLines(
1331+
"Test.java",
1332+
"""
1333+
class Test {
1334+
// BUG: Diagnostic contains: The parameter 'a' is reassigned before being read
1335+
private int test(int a) {
1336+
a = 1;
1337+
return a;
1338+
}
1339+
}
1340+
""")
1341+
.doTest();
1342+
}
1343+
13271344
@Test
13281345
public void unusedAssignment_nulledOut_noWarning() {
13291346
helper

0 commit comments

Comments
 (0)