Skip to main content

gql_parser/
print.rs

1//! Deterministic tree rendering built on the public AST visitor.
2//!
3//! All stored fields are printed, including defaults, absent options, and empty
4//! lists. Field labels distinguish otherwise similar children such as a filter
5//! predicate and a result expression. Strings are quoted and escaped so each
6//! tree node occupies one physical line. This is a diagnostic format, not a
7//! serialization protocol: deliberate AST/schema changes can change the output.
8
9use std::convert::Infallible;
10use std::ops::ControlFlow;
11
12use crate::ast::Program;
13use crate::visit::{AstNode, Field, Scalar, Visitor};
14
15/// Format a complete program as a tree, ending with a newline.
16///
17/// ```
18/// use gql_parser::{format_ast, parse};
19/// let ast = parse("RETURN 1 + 2 * 3 AS value").unwrap();
20/// let tree = format_ast(&ast);
21/// assert!(tree.starts_with("Program\n"));
22/// assert!(tree.contains("op: BinaryOp::Mul"));
23/// ```
24pub fn format_ast(program: &Program) -> String {
25    let mut printer = AstTreePrinter::new();
26    let ControlFlow::Continue(()) = printer.visit_program(program);
27    printer.finish()
28}
29
30#[derive(Debug)]
31struct Tree {
32    label: String,
33    children: Vec<Tree>,
34}
35
36/// A visitor that renders programs or individual AST subtrees.
37///
38/// Visit one or more roots, then consume the printer with [`Self::finish`].
39/// Node order is deterministic and follows the visitor's structural order.
40///
41/// ```
42/// use std::ops::ControlFlow;
43/// use gql_parser::{AstTreePrinter, Expr};
44/// use gql_parser::visit::Visitor;
45/// let mut printer = AstTreePrinter::new();
46/// let ControlFlow::Continue(()) = printer.visit_expr(&Expr::Wildcard);
47/// assert_eq!(printer.finish(), "Expr::Wildcard\n");
48/// ```
49#[derive(Debug, Default)]
50pub struct AstTreePrinter {
51    roots: Vec<Tree>,
52    stack: Vec<Tree>,
53}
54
55impl AstTreePrinter {
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// Finish rendering. An unused printer returns an empty string.
61    ///
62    /// # Panics
63    /// Panics if entry/exit hooks were manually called without balancing them.
64    /// Normal typed `visit_*` calls always balance the hooks.
65    pub fn finish(self) -> String {
66        assert!(self.stack.is_empty(), "unfinished AST traversal");
67        let mut output = String::new();
68        for root in &self.roots {
69            output.push_str(&root.label);
70            output.push('\n');
71            // Rendering uses an explicit stack rather than recursing a second
72            // time through deeply nested expression trees.
73            let mut pending = Vec::new();
74            for (index, child) in root.children.iter().enumerate().rev() {
75                pending.push((child, String::new(), index + 1 == root.children.len()));
76            }
77            while let Some((tree, prefix, last)) = pending.pop() {
78                output.push_str(&prefix);
79                output.push_str(if last { "└── " } else { "├── " });
80                output.push_str(&tree.label);
81                output.push('\n');
82                let child_prefix = prefix + if last { "    " } else { "│   " };
83                for (index, child) in tree.children.iter().enumerate().rev() {
84                    pending.push((
85                        child,
86                        child_prefix.clone(),
87                        index + 1 == tree.children.len(),
88                    ));
89                }
90            }
91        }
92        output
93    }
94
95    fn push(&mut self, label: String) {
96        self.stack.push(Tree {
97            label,
98            children: Vec::new(),
99        });
100    }
101
102    fn append(&mut self, tree: Tree) {
103        if let Some(parent) = self.stack.last_mut() {
104            parent.children.push(tree);
105        } else {
106            self.roots.push(tree);
107        }
108    }
109
110    fn pop(&mut self, field: bool) {
111        let mut tree = self.stack.pop().expect("balanced AST traversal");
112        if field && tree.children.len() == 1 {
113            let child = tree.children.pop().expect("one child");
114            tree.label.push_str(": ");
115            tree.label.push_str(&child.label);
116            tree.children = child.children;
117        }
118        self.append(tree);
119    }
120}
121
122impl<'ast> Visitor<'ast> for AstTreePrinter {
123    type Break = Infallible;
124
125    fn enter_node(&mut self, node: AstNode<'ast>) -> ControlFlow<Self::Break> {
126        self.push(node.kind().to_owned());
127        ControlFlow::Continue(())
128    }
129
130    fn leave_node(&mut self, _node: AstNode<'ast>) -> ControlFlow<Self::Break> {
131        self.pop(false);
132        ControlFlow::Continue(())
133    }
134
135    fn enter_field(&mut self, field: Field) -> ControlFlow<Self::Break> {
136        self.push(field.to_string());
137        ControlFlow::Continue(())
138    }
139
140    fn leave_field(&mut self, _field: Field) -> ControlFlow<Self::Break> {
141        self.pop(true);
142        ControlFlow::Continue(())
143    }
144
145    fn enter_list(&mut self, len: usize) -> ControlFlow<Self::Break> {
146        self.push(if len == 0 {
147            "[]".to_owned()
148        } else {
149            format!("List (len={len})")
150        });
151        ControlFlow::Continue(())
152    }
153
154    fn leave_list(&mut self) -> ControlFlow<Self::Break> {
155        self.pop(false);
156        ControlFlow::Continue(())
157    }
158
159    fn visit_scalar(&mut self, value: Scalar<'ast>) -> ControlFlow<Self::Break> {
160        self.append(Tree {
161            label: value.to_string(),
162            children: Vec::new(),
163        });
164        ControlFlow::Continue(())
165    }
166}