code_gen/rust/control/
match_statement.rs

1use crate::rust::{MatchCase, Var};
2use crate::{CodeBuffer, Expression, Literal, Statement};
3
4/// A `match` statement.
5pub struct MatchStatement {
6    assignment: Option<Var>,
7    expression: Box<dyn Expression>,
8    match_cases: Vec<MatchCase>,
9}
10
11impl<E: 'static + Expression> From<E> for MatchStatement {
12    fn from(expression: E) -> Self {
13        Self {
14            assignment: None,
15            expression: Box::new(expression),
16            match_cases: Vec::default(),
17        }
18    }
19}
20
21impl From<&str> for MatchStatement {
22    fn from(literal: &str) -> Self {
23        Self::from(Literal::from(literal))
24    }
25}
26
27impl From<String> for MatchStatement {
28    fn from(literal: String) -> Self {
29        Self::from(Literal::from(literal))
30    }
31}
32
33impl MatchStatement {
34    //! Assignment
35
36    /// Gets the optional variable name assignment.
37    pub fn assignment(&self) -> Option<&Var> {
38        self.assignment.as_ref()
39    }
40
41    /// Sets the variable name `assignment`.
42    pub fn set_assignment<V>(&mut self, assignment: V)
43    where
44        V: Into<Var>,
45    {
46        self.assignment = Some(assignment.into());
47    }
48
49    /// Sets the variable name `assignment`.
50    pub fn with_assignment<V>(mut self, assignment: V) -> Self
51    where
52        V: Into<Var>,
53    {
54        self.set_assignment(assignment);
55        self
56    }
57}
58
59impl MatchStatement {
60    //! Cases
61
62    /// Adds the match `case`.
63    pub fn add_match_case(&mut self, case: MatchCase) {
64        self.match_cases.push(case);
65    }
66
67    /// Adds the match `case`.
68    pub fn with_match_case(mut self, case: MatchCase) -> Self {
69        self.add_match_case(case);
70        self
71    }
72}
73
74impl Statement for MatchStatement {
75    fn write(&self, b: &mut CodeBuffer, level: usize) {
76        b.indent(level);
77        if let Some(assignment) = &self.assignment {
78            b.write("let ");
79            assignment.write(b);
80            b.write(" = ");
81        }
82        b.write("match ");
83        self.expression.write(b);
84        b.write(" {");
85        b.end_line();
86        for match_case in &self.match_cases {
87            match_case.write(b, level + 1);
88        }
89        if self.assignment.is_some() {
90            b.line(level, "};");
91        } else {
92            b.line(level, "}")
93        }
94    }
95}