Skip to content

Commit

Permalink
Improve validation of arguments to getSourceForNode
Browse files Browse the repository at this point in the history
to e.g. be more helpful when crashing on lombok-generated AST nodes.

PiperOrigin-RevId: 352500370
  • Loading branch information
cushon authored and Error Prone Team committed Jan 19, 2021
1 parent 4cd70d1 commit d847960
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions check_api/src/main/java/com/google/errorprone/VisitorState.java
Expand Up @@ -538,17 +538,21 @@ public CharSequence getSourceCode() {
* This returns exactly what is in the source code, whereas .toString() pretty-prints the node
* from its AST representation.
*
* @return the source code that represents the node.
* @return the source code that represents the node, or {@code null} if the source code is
* unavailable (e.g. for generated or desugared AST nodes)
*/
@Nullable
public String getSourceForNode(Tree tree) {
JCTree node = (JCTree) tree;
int start = node.getStartPosition();
int end = getEndPosition(node);
if (end < 0) {
int start = ((JCTree) tree).getStartPosition();
int end = getEndPosition(tree);
CharSequence source = getSourceCode();
if (end == -1) {
return null;
}
return getSourceCode().subSequence(start, end).toString();
checkArgument(start >= 0, "invalid start position (%s) for: %s", start, tree);
checkArgument(start < end, "invalid source positions (%s, %s) for: %s", start, end, tree);
checkArgument(end < source.length(), "invalid end position (%s) for: %s", end, tree);
return source.subSequence(start, end).toString();
}

/**
Expand Down

0 comments on commit d847960

Please sign in to comment.