aboutsummaryrefslogtreecommitdiff
path: root/src/ast/display.rs
blob: 25b4d23bd66d553b5bb12b29aa449e0e9571c9b0 (plain)
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
use std::fmt::Display;

use super::{Expression, Statement, Value};

impl<'a> Display for Statement<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{{")?;
        let value = match self {
            Statement::Val {
                identifier,
                initializer,
            } => format!("val {} {}", identifier.lexeme, initializer),
            Statement::Var {
                identifier,
                initializer,
            } => format!("var {} {}", identifier.lexeme, initializer),
            Statement::Expression { expr } => expr.to_string(),
        };
        write!(f, "{value}")?;
        write!(f, "}}")?;

        Ok(())
    }
}

impl<'a> Display for Expression<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "(")?;
        let value = match self {
            Expression::Literal(value) => value.0.to_string(),
            Expression::Unary { expr, .. } => format!("+ {}", expr),
            Expression::Binary { lhs, rhs, .. } => format!("+ {lhs} {rhs}"),
        };
        write!(f, "{value}")?;
        write!(f, ")")?;

        Ok(())
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}