1 /*
2 * SPDX-FileCopyrightText: Copyright (c) 2011-2026 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 /**
25 * Node, represented by this object.
26 */
27 private final DetailAST node;
28
29 /**
30 * Creates a decorator which is able to search in the node's subtree.
31 * @param node Node which will be represented by the new BranchContains instance
32 */
33 BranchContains(final DetailAST node) {
34 this.node = node;
35 }
36
37 /**
38 * Checks if there is a node of type `type` in this node subtree.
39 * The root node itself may also match, i.e.
40 * `new BranchContains(node).contains(node.getType())` is always true
41 * @param type Desired type
42 * @return Whether node of given type exists somewhere in the subtree
43 */
44 boolean check(final int type) {
45 return this.node.getType() == type
46 || new ChildStream(this.node)
47 .children()
48 .anyMatch(child -> new com.qulice.checkstyle.BranchContains(child).check(type));
49 }
50 }