1 /*
2 * SPDX-FileCopyrightText: Copyright (c) 2011-2025 Yegor Bugayenko
3 * SPDX-License-Identifier: MIT
4 */
5 package com.qulice.checkstyle;
6
7 import com.puppycrawl.tools.checkstyle.api.DetailAST;
8
9 /**
10 * Utility class that checks the existence
11 * of tokens of specific type in the AST node subtree.
12 *
13 * Some checks used branchContains() method in DetailAST
14 * which recursively searched node subtree for the child of a given type.
15 * However, this method was deprecated in upstream due to unintended too
16 * deep scanning. It is recommended to write traversal implementation
17 * for your needs by yourself to avoid unexpected side effects. So here follows it's
18 * simple implementation.
19 *
20 * @since 1.0
21 */
22 class BranchContains {
23 /**
24 * Node, represented by this object.
25 */
26 private final DetailAST node;
27
28 /**
29 * Creates a decorator which is able to search in the node's subtree.
30 * @param node Node which will be represented by the new BranchContains instance.
31 */
32 BranchContains(final DetailAST node) {
33 this.node = node;
34 }
35
36 /**
37 * Checks if there is a node of type `type` in this node subtree.
38 * The root node itself may also match, i.e.
39 * `new BranchContains(node).contains(node.getType())` is always true
40 * @param type Desired type
41 * @return Whether node of given type exists somewhere in the subtree
42 */
43 boolean check(final int type) {
44 return this.node.getType() == type
45 || new ChildStream(this.node)
46 .children()
47 .anyMatch(child -> new BranchContains(child).check(type));
48 }
49 }