View Javadoc
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   * <p>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.</p>
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       *
32       * @param node Node which will be represented by the new BranchContains instance
33       */
34      BranchContains(final DetailAST node) {
35          this.node = node;
36      }
37  
38      /**
39       * Checks if there is a node of type `type` in this node subtree.
40       * The root node itself may also match, i.e.
41       * `new BranchContains(node).contains(node.getType())` is always true
42       *
43       * @param type Desired type
44       * @return Whether node of given type exists somewhere in the subtree
45       */
46      boolean check(final int type) {
47          return this.node.getType() == type
48              || new ChildStream(this.node)
49              .children()
50              .anyMatch(child -> new com.qulice.checkstyle.BranchContains(child).check(type));
51      }
52  }