1818
1919import static com .google .errorprone .BugPattern .SeverityLevel .ERROR ;
2020import static com .google .errorprone .matchers .Description .NO_MATCH ;
21+ import static com .google .errorprone .util .ASTHelpers .getStartPosition ;
2122
22- import com .google .common .base .Strings ;
2323import com .google .errorprone .BugPattern ;
2424import com .google .errorprone .VisitorState ;
2525import com .google .errorprone .bugpatterns .BugChecker .BinaryTreeMatcher ;
@@ -37,21 +37,31 @@ public Description matchBinary(BinaryTree tree, VisitorState state) {
3737 if (!tree .getKind ().equals (Tree .Kind .XOR )) {
3838 return NO_MATCH ;
3939 }
40- Integer lhs = ASTHelpers .constValue (tree .getLeftOperand (), Integer .class );
40+ Tree lhsTree = tree .getLeftOperand ();
41+ while (lhsTree instanceof BinaryTree ) {
42+ lhsTree = ((BinaryTree ) lhsTree ).getRightOperand ();
43+ }
44+ Number lhs = ASTHelpers .constValue (lhsTree , Number .class );
4145 if (lhs == null ) {
4246 return NO_MATCH ;
4347 }
48+ if (lhs .longValue () != lhs .intValue ()) {
49+ return NO_MATCH ;
50+ }
4451 switch (lhs .intValue ()) {
4552 case 2 :
4653 case 10 :
4754 break ;
4855 default :
4956 return NO_MATCH ;
5057 }
51- Integer rhs = ASTHelpers .constValue (tree .getRightOperand (), Integer .class );
58+ Number rhs = ASTHelpers .constValue (tree .getRightOperand (), Number .class );
5259 if (rhs == null ) {
5360 return NO_MATCH ;
5461 }
62+ if (rhs .longValue () != rhs .intValue ()) {
63+ return NO_MATCH ;
64+ }
5565 if (state .getSourceForNode (tree .getRightOperand ()).startsWith ("0" )) {
5666 // hex and octal literals
5767 return NO_MATCH ;
@@ -62,16 +72,24 @@ public Description matchBinary(BinaryTree tree, VisitorState state) {
6272 String .format (
6373 "The ^ operator is binary XOR, not a power operator, so '%s' will always"
6474 + " evaluate to %d." ,
65- state .getSourceForNode (tree ), lhs ^ rhs ));
75+ state .getSourceForNode (tree ), lhs .intValue () ^ rhs .intValue ()));
76+ String suffix = lhs instanceof Long ? "L" : "" ;
77+ int start = getStartPosition (lhsTree );
78+ int end = state .getEndPosition (tree );
6679 switch (lhs .intValue ()) {
6780 case 2 :
68- if (rhs <= 31 ) {
69- description .addFix (SuggestedFix .replace (tree , String .format ("1 << %d" , rhs )));
81+ if (rhs .intValue () <= (lhs instanceof Long ? 63 : 31 )) {
82+ String replacement = String .format ("1%s << %d" , suffix , rhs );
83+ if (start != getStartPosition (tree )) {
84+ replacement = "(" + replacement + ")" ;
85+ }
86+ description .addFix (SuggestedFix .replace (start , end , replacement ));
7087 }
7188 break ;
7289 case 10 :
73- if (rhs <= 9 ) {
74- description .addFix (SuggestedFix .replace (tree , "1" + Strings .repeat ("0" , rhs )));
90+ if (rhs .intValue () <= (lhs instanceof Long ? 18 : 9 )) {
91+ description .addFix (
92+ SuggestedFix .replace (start , end , "1" + "0" .repeat (rhs .intValue ()) + suffix ));
7593 }
7694 break ;
7795 default :
0 commit comments