code_gen/rust/control/
match_statement.rs1use crate::rust::{MatchCase, Var};
2use crate::{CodeBuffer, Expression, Literal, Statement};
3
4pub 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 pub fn assignment(&self) -> Option<&Var> {
38 self.assignment.as_ref()
39 }
40
41 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 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 pub fn add_match_case(&mut self, case: MatchCase) {
64 self.match_cases.push(case);
65 }
66
67 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}