Self (final int levelsUp, final @NotNull ElementPattern<? extends ParentType> pattern) { return with(new PatternCondition<T>("withAncestor") { @Override public boolean accepts(@NotNull T t, ProcessingContext context) { ParentType element = t; for (int i=0; i<levelsUp+1;i++) { if (pattern.accepts(element, context)) return true; element = getParent(element); if (element == null) break; } return false; } }); }