Skip to content

Commit

Permalink
Add a space between unary minus and negative literals
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 365063449
  • Loading branch information
cushon authored and google-java-format Team committed Mar 25, 2021
1 parent 189c381 commit 6da736d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1599,18 +1599,22 @@ public Void visitMemberSelect(MemberSelectTree node, Void unused) {
public Void visitLiteral(LiteralTree node, Void unused) {
sync(node);
String sourceForNode = getSourceForNode(node, getCurrentPath());
// A negative numeric literal -n is usually represented as unary minus on n,
// but that doesn't work for integer or long MIN_VALUE. The parser works
// around that by representing it directly as a signed literal (with no
// unary minus), but the lexer still expects two tokens.
if (sourceForNode.startsWith("-")) {
if (isUnaryMinusLiteral(sourceForNode)) {
token("-");
sourceForNode = sourceForNode.substring(1).trim();
}
token(sourceForNode);
return null;
}

// A negative numeric literal -n is usually represented as unary minus on n,
// but that doesn't work for integer or long MIN_VALUE. The parser works
// around that by representing it directly as a signed literal (with no
// unary minus), but the lexer still expects two tokens.
private static boolean isUnaryMinusLiteral(String literalTreeSource) {
return literalTreeSource.startsWith("-");
}

private void visitPackage(
ExpressionTree packageName, List<? extends AnnotationTree> packageAnnotations) {
if (!packageAnnotations.isEmpty()) {
Expand Down Expand Up @@ -1696,10 +1700,10 @@ private boolean ambiguousUnaryOperator(UnaryTree node, String operatorName) {
default:
return false;
}
if (!(node.getExpression() instanceof UnaryTree)) {
JCTree.Tag tag = unaryTag(node.getExpression());
if (tag == null) {
return false;
}
JCTree.Tag tag = ((JCTree) node.getExpression()).getTag();
if (tag.isPostUnaryOp()) {
return false;
}
Expand All @@ -1709,6 +1713,17 @@ private boolean ambiguousUnaryOperator(UnaryTree node, String operatorName) {
return true;
}

private JCTree.Tag unaryTag(ExpressionTree expression) {
if (expression instanceof UnaryTree) {
return ((JCTree) expression).getTag();
}
if (expression instanceof LiteralTree
&& isUnaryMinusLiteral(getSourceForNode(expression, getCurrentPath()))) {
return JCTree.Tag.MINUS;
}
return null;
}

@Override
public Void visitPrimitiveType(PrimitiveTypeTree node, Void unused) {
sync(node);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class B183431894 {
int a = - -1;
int d = + +1;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class B183431894 {
int a = - -1;
int d = + +1;
}

0 comments on commit 6da736d

Please sign in to comment.