Skip to main content

example1/
example1.rs

1use std::fmt;
2
3use syntree::Builder;
4use syntree_layout::{Layouter, Result, Visualize};
5
6#[derive(Copy, Clone, Debug)]
7struct MyNodeData(i32);
8
9// You need to implement syntree_layout::Visualize for your nodes data type if you want your own
10// node representation.
11impl Visualize for MyNodeData {
12    fn visualize(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        write!(f, "Id({})", self.0)
14    }
15
16    fn emphasize(&self) -> bool {
17        // This simply emphasizes only the leaf nodes.
18        // It only works for this example.
19        self.0 > 1
20    }
21}
22
23impl fmt::Display for MyNodeData {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(f, "{}", self.0)
26    }
27}
28
29fn main() -> Result<()> {
30    //      0
31    //     / \
32    //    1   2
33    //   / \
34    //  3   4
35    let mut tree = Builder::new();
36
37    tree.open(MyNodeData(0)).unwrap();
38    tree.open(MyNodeData(1)).unwrap();
39    tree.token(MyNodeData(3), 1).unwrap();
40    tree.token(MyNodeData(4), 1).unwrap();
41    tree.close().unwrap();
42    tree.token(MyNodeData(2), 1).unwrap();
43    tree.close().unwrap();
44
45    let tree = tree.build().unwrap();
46    Layouter::new(&tree)
47        .with_file_path("examples/example1_vis.svg")
48        .embed_with_visualize()?
49        .write()?;
50
51    Layouter::new(&tree)
52        .with_file_path("examples/example1_deb.svg")
53        .embed_with_debug()?
54        .write()?;
55
56    Layouter::new(&tree)
57        .with_file_path("examples/example1_dis.svg")
58        .embed()?
59        .write()
60}