1use std::convert::Infallible;
10use std::ops::ControlFlow;
11
12use crate::ast::Program;
13use crate::visit::{AstNode, Field, Scalar, Visitor};
14
15pub 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#[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 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 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}