Skip to main content

microcad_lang_base/
tree_display.rs

1// Copyright © 2025-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Display trait for tree like output
5
6/// Trait for displaying a tree
7pub trait TreeDisplay {
8    /// Write item into `f` and use `{:depth$}` syntax in front of your single line
9    /// output to get proper indention.
10    fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result;
11}
12
13/// Indention size
14const INDENT: usize = 2;
15
16/// Indention depth counter
17#[derive(derive_more::Deref, Clone, Copy)]
18pub struct TreeState {
19    /// Current depth.
20    #[deref]
21    pub depth: usize,
22    /// Print in debug mode
23    pub debug: bool,
24}
25
26impl TreeState {
27    /// Create new tree state for std::fmt::Display
28    pub fn new_display() -> Self {
29        Self {
30            depth: 0,
31            debug: false,
32        }
33    }
34
35    /// Create new tree state for std::fmt::Debug
36    pub fn new_debug(depth: usize) -> Self {
37        Self { depth, debug: true }
38    }
39    /// Change indention one step deeper
40    pub fn indent(&mut self) {
41        self.depth += INDENT
42    }
43
44    /// Return a indention which is one step deeper
45    pub fn indented(&self) -> Self {
46        Self {
47            depth: self.depth + INDENT,
48            debug: self.debug,
49        }
50    }
51}
52
53/// print syntax via std::fmt::Display
54pub struct FormatTree<'a, T: TreeDisplay>(pub &'a T);
55
56impl<T: TreeDisplay> std::fmt::Display for FormatTree<'_, T> {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        self.0.tree_print(
59            f,
60            TreeState {
61                depth: 2,
62                debug: false,
63            },
64        )
65    }
66}
67
68impl<T: TreeDisplay> std::fmt::Debug for FormatTree<'_, T> {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        self.0.tree_print(
71            f,
72            TreeState {
73                depth: 2,
74                debug: true,
75            },
76        )
77    }
78}