ridx_syntax/tree_dump.rs
1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! A compact text form of a tree for tests and debugging: `Fn(Name ParamList(Param(IdentPat PathType)) BlockExpr)`.
12
13use crate::tree::{NodeId, SyntaxTree};
14
15impl SyntaxTree<'_> {
16 /// The subtree of `id` as nested kinds; `with_text` appends the source of nodes without children.
17 pub fn dump(&self, id: NodeId, with_text: bool) -> String {
18 let mut out = String::new();
19 self.dump_into(id, with_text, &mut out);
20 out
21 }
22
23 fn dump_into(&self, id: NodeId, with_text: bool, out: &mut String) {
24 out.push_str(&format!("{:?}", self.kind(id)));
25 let mut kids = self.children(id).peekable();
26 if kids.peek().is_some() {
27 out.push('(');
28 let mut first = true;
29 for c in kids {
30 if !first {
31 out.push(' ');
32 }
33 first = false;
34 self.dump_into(c, with_text, out);
35 }
36 out.push(')');
37 } else if with_text {
38 out.push_str(&format!("{:?}", self.text(id)));
39 }
40 }
41
42 /// The `Error` nodes of the tree.
43 pub fn errors(&self) -> impl Iterator<Item = NodeId> + '_ {
44 self.descendants(self.root()).filter(|&n| self.kind(n) == crate::SyntaxKind::Error)
45 }
46}