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;