From f50d4aee6586807d4aa5393e49906b0bb61cdc3c Mon Sep 17 00:00:00 2001 From: Sam Snyder Date: Fri, 11 Oct 2024 12:29:34 -0700 Subject: [PATCH] Apply cursor ancestry validation to more visit calls. --- .../src/main/java/org/openrewrite/TreeVisitor.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/rewrite-core/src/main/java/org/openrewrite/TreeVisitor.java b/rewrite-core/src/main/java/org/openrewrite/TreeVisitor.java index 0b44518c975..0658cd42cc3 100644 --- a/rewrite-core/src/main/java/org/openrewrite/TreeVisitor.java +++ b/rewrite-core/src/main/java/org/openrewrite/TreeVisitor.java @@ -146,6 +146,12 @@ public final Cursor updateCursor(T currentValue) { } public @Nullable T visit(@Nullable Tree tree, P p, Cursor parent) { + if (parent.getValue() instanceof Tree && ((Tree) parent.getValue()).isScope(tree)) { + throw new IllegalArgumentException( + "The `parent` cursor must not point to the same `tree` as the tree to be visited. " + + "This usually indicates that you have used getCursor() where getCursor().getParent() is appropriate." + ); + } this.cursor = parent; return visit(tree, p); } @@ -165,12 +171,7 @@ public final Cursor updateCursor(T currentValue) { return t; } - public T visitNonNull(Tree tree, P p, Cursor parent) { - if (parent.getValue() instanceof Tree && ((Tree) parent.getValue()).isScope(tree)) { - throw new IllegalArgumentException( - "The `parent` cursor must not point to the same `tree` as the tree to be visited" - ); - } + public @NonNull T visitNonNull(Tree tree, P p, Cursor parent) { T t = visit(tree, p, parent); assert t != null; return t;