Skip to content

Commit

Permalink
Disallow @Var on effectively final variables
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 348082885
  • Loading branch information
cushon authored and Error Prone Team committed Dec 17, 2020
1 parent a9e478a commit b61a7df
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;

import com.google.errorprone.BugPattern;
Expand All @@ -32,6 +33,7 @@
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree;
Expand All @@ -57,6 +59,14 @@ public Description matchVariable(VariableTree tree, VisitorState state) {
return Description.NO_MATCH;
}
if (ASTHelpers.hasAnnotation(sym, Var.class, state)) {
if ((sym.flags() & Flags.EFFECTIVELY_FINAL) != 0) {
return buildDescription(tree)
.setMessage("@Var variable is never modified")
.addFix(
SuggestedFix.delete(
getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "Var")))
.build();
}
return Description.NO_MATCH;
}
if (!ASTHelpers.getGeneratedBy(state).isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,4 +371,22 @@ public void notSuppressedByUnrelatedSuppressWarningsAnnotation() {
"}")
.doTest();
}

@Test
public void effectivelyFinal() {
compilationHelper
.addSourceLines(
"Test.java",
"import com.google.errorprone.annotations.Var;",
"class Test {",
" int f(",
" // BUG: Diagnostic contains: @Var variable is never modified",
" @Var int x,",
" @Var int y) {",
" y++;",
" return x + y;",
" }",
"}")
.doTest();
}
}

0 comments on commit b61a7df

Please sign in to comment.