1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::fmt::Write;

use super::context::Context;
use crate::PrintResult;

pub struct PrintState {
    indent: &'static str,
    curr_indent: u32,
    pub buffer: String,
}

impl PrintState {
    pub fn new(indent: &'static str) -> Self {
        Self {
            indent,
            curr_indent: 0,
            buffer: String::new(),
        }
    }

    /// Indent the current line.
    pub fn indent(&mut self) { self.curr_indent += 1; }

    /// Dedent the current line.
    pub fn dedent(&mut self) { self.curr_indent -= 1; }

    /// Write the current indent.
    pub fn write_indent(&mut self) -> std::fmt::Result {
        for _ in 0..self.curr_indent {
            write!(self.buffer, "{}", self.indent)?;
        }
        Ok(())
    }
}

pub trait Print {
    fn print(&self, ctx: &Context, state: &mut PrintState) -> PrintResult<()>;
}

impl<T: Print> Print for Option<T> {
    fn print(&self, ctx: &Context, state: &mut PrintState) -> PrintResult<()> {
        if let Some(inner) = self {
            inner.print(ctx, state)?;
        }
        Ok(())
    }
}