Skip to content

Commit

Permalink
Format type annotation as part of the type, not part of the modifiers…
Browse files Browse the repository at this point in the history
… list

Given e.g. `@Deprecated @nullable Object foo() {}`, prefer this:

```
@deprecated
@nullable Object foo() {}
```

instead of:

```
@deprecated
@nullable
Object foo() {}
```

The implementation is complicated by the fact that the AST doesn't store source position information for modifiers, and there's no requirement that declaration annotations, modifiers, and type annotations appear in any particular order in source.

To work around this, we examine the token stream to figure out the ordering of the modifiers and annotations.

#5

Roll forward of 1a87579 without a use of a server-only Guava API.

PiperOrigin-RevId: 392785887
  • Loading branch information
cushon authored and google-java-format Team committed Aug 25, 2021
1 parent 37f716a commit 81306b9
Show file tree
Hide file tree
Showing 7 changed files with 406 additions and 68 deletions.
6 changes: 5 additions & 1 deletion core/pom.xml
Expand Up @@ -51,7 +51,11 @@
<artifactId>error_prone_annotations</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value-annotations</artifactId>
<optional>true</optional>
</dependency>

<!-- Test dependencies -->
<dependency>
Expand Down
24 changes: 24 additions & 0 deletions core/src/main/java/com/google/googlejavaformat/OpsBuilder.java
Expand Up @@ -18,6 +18,8 @@
import static java.lang.Math.min;

import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
Expand Down Expand Up @@ -281,6 +283,28 @@ public final Optional<String> peekToken(int skip) {
: Optional.empty();
}

/**
* Returns the {@link Input.Tok}s starting at the current source position, which are satisfied by
* the given predicate.
*/
public ImmutableList<Tok> peekTokens(int startPosition, Predicate<Input.Tok> predicate) {
ImmutableList<? extends Input.Token> tokens = input.getTokens();
Preconditions.checkState(
tokens.get(tokenI).getTok().getPosition() == startPosition,
"Expected the current token to be at position %s, found: %s",
startPosition,
tokens.get(tokenI));
ImmutableList.Builder<Tok> result = ImmutableList.builder();
for (int idx = tokenI; idx < tokens.size(); idx++) {
Tok tok = tokens.get(idx).getTok();
if (!predicate.apply(tok)) {
break;
}
result.add(tok);
}
return result.build();
}

/**
* Emit an optional token iff it exists on the input. This is used to emit tokens whose existence
* has been lost in the AST.
Expand Down

0 comments on commit 81306b9

Please sign in to comment.