From d847960c17f21a6f50e3607ffd94ef9131548068 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Mon, 18 Jan 2021 23:02:29 -0800 Subject: [PATCH] Improve validation of arguments to `getSourceForNode` to e.g. be more helpful when crashing on lombok-generated AST nodes. PiperOrigin-RevId: 352500370 --- .../java/com/google/errorprone/VisitorState.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/check_api/src/main/java/com/google/errorprone/VisitorState.java b/check_api/src/main/java/com/google/errorprone/VisitorState.java index be6349b0c8d..0b915babd53 100644 --- a/check_api/src/main/java/com/google/errorprone/VisitorState.java +++ b/check_api/src/main/java/com/google/errorprone/VisitorState.java @@ -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(); } /**