Skip to main content

big_code_analysis/
find.rs

1// Per-language metric and AST modules deliberately consume the macro-
2// generated tree-sitter token enums via `use crate::*` and `use Foo::*`
3// inside match expressions — explicit imports would list dozens of
4// variants per arm and obscure the per-language token sets that are the
5// point of these files. Allowed at the module level rather than per
6// function so the per-language impl blocks stay readable.
7#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
8
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use crate::node::Node;
13
14use crate::error::MetricsError;
15use crate::output::dump::*;
16use crate::traits::*;
17
18// Hidden from rustdoc because the signature exposes `ParserTrait`,
19// which is `#[doc(hidden)]` per issue #256. The CLI's `Find` callback
20// remains the documented surface for this functionality.
21#[doc(hidden)]
22/// Finds the types of nodes specified in the input slice.
23///
24/// "No matches" is represented by `Ok(Vec::new())` rather than an
25/// error — it is a normal outcome, not a failure mode. The
26/// [`Result`] return type is for forward compatibility with the
27/// other entry points; today no [`MetricsError`] variant is produced
28/// by `find`, but future strict-parsing modes may surface
29/// [`MetricsError::ParseHasErrors`] here.
30///
31/// # Errors
32///
33/// Currently infallible; the [`Result`] wrapper aligns the signature
34/// with [`crate::metrics`] and [`crate::operands_and_operators`] so
35/// callers can use the `?` operator uniformly.
36pub fn find<'a, T: ParserTrait>(
37    parser: &'a T,
38    filters: &[String],
39) -> Result<Vec<Node<'a>>, MetricsError> {
40    let filters = parser.get_filters(filters);
41    let node = parser.get_root();
42    let mut cursor = node.cursor();
43    let mut stack = Vec::new();
44    let mut good = Vec::new();
45    let mut children = Vec::new();
46
47    stack.push(node);
48
49    while let Some(node) = stack.pop() {
50        if filters.any(&node) {
51            good.push(node);
52        }
53        cursor.reset(&node);
54        if cursor.goto_first_child() {
55            loop {
56                children.push(cursor.node());
57                if !cursor.goto_next_sibling() {
58                    break;
59                }
60            }
61            for child in children.drain(..).rev() {
62                stack.push(child);
63            }
64        }
65    }
66    Ok(good)
67}
68
69/// Configuration options for finding different
70/// types of nodes in a code.
71#[derive(Debug)]
72pub struct FindCfg {
73    /// Path to the file containing the code
74    pub path: PathBuf,
75    /// Types of nodes to find
76    pub filters: Arc<[String]>,
77    /// The first line of code considered in the search
78    ///
79    /// If `None`, the search starts from the
80    /// first line of code in a file
81    pub line_start: Option<usize>,
82    /// The end line of code considered in the search
83    ///
84    /// If `None`, the search ends at the
85    /// last line of code in a file
86    pub line_end: Option<usize>,
87}
88
89/// Type tag identifying the node-find action; carries no data.
90pub struct Find {
91    _guard: (),
92}
93
94impl Callback for Find {
95    type Res = std::io::Result<()>;
96    type Cfg = FindCfg;
97
98    fn call<T: ParserTrait>(cfg: Self::Cfg, parser: &T) -> Self::Res {
99        if let Ok(good) = find(parser, &cfg.filters)
100            && !good.is_empty()
101        {
102            println!("In file {}", cfg.path.display());
103            for node in good {
104                dump_node(parser.get_code(), &node, 1, cfg.line_start, cfg.line_end)?;
105            }
106            println!();
107        }
108        Ok(())
109    }
110}