code_gen/statement/
with_statements.rs1use crate::{CodeBuffer, EmptyLine, Expression, ExpressionStatement, Literal, Semi, Statement};
2
3pub trait WithStatements: Sized {
5 fn statements(&self) -> &[Box<dyn Statement>];
7
8 fn add_boxed_statement(&mut self, statement: Box<dyn Statement>);
10
11 fn with_boxed_statement(mut self, statement: Box<dyn Statement>) -> Self {
13 self.add_boxed_statement(statement);
14 self
15 }
16
17 fn add_statement<S>(&mut self, statement: S)
19 where
20 S: 'static + Statement,
21 {
22 self.add_boxed_statement(Box::new(statement));
23 }
24
25 fn with_statement<S>(self, statement: S) -> Self
27 where
28 S: 'static + Statement,
29 {
30 self.with_boxed_statement(Box::new(statement))
31 }
32
33 fn add_literal<L>(&mut self, literal: L)
35 where
36 L: Into<Literal>,
37 {
38 self.add_expression_statement(literal.into());
39 }
40
41 fn with_literal<L>(self, literal: L) -> Self
43 where
44 L: Into<Literal>,
45 {
46 self.with_expression_statement(literal.into())
47 }
48
49 fn add_semi<L>(&mut self, literal: L)
51 where
52 L: Into<Literal>,
53 {
54 self.add_statement(Semi::from(literal.into()))
55 }
56
57 fn with_semi<L>(self, literal: L) -> Self
59 where
60 L: Into<Literal>,
61 {
62 self.with_statement(Semi::from(literal.into()))
63 }
64
65 fn add_expression_statement<E>(&mut self, expression: E)
67 where
68 E: 'static + Expression,
69 {
70 self.add_statement(ExpressionStatement::from(expression));
71 }
72
73 fn with_expression_statement<E>(self, expression: E) -> Self
75 where
76 E: 'static + Expression,
77 {
78 self.with_statement(ExpressionStatement::from(expression))
79 }
80
81 fn add_empty_line(&mut self) {
83 self.add_statement(EmptyLine::default());
84 }
85
86 fn with_empty_line(self) -> Self {
88 self.with_statement(EmptyLine::default())
89 }
90
91 fn write_statements(&self, b: &mut CodeBuffer, level: usize) {
93 for statement in self.statements() {
94 statement.write(b, level);
95 }
96 }
97
98 fn write_curly_statement_block(&self, b: &mut CodeBuffer, level: usize) {
100 b.write("{");
101 if self.statements().is_empty() {
102 b.write("}");
103 } else {
104 b.end_line();
105 self.write_statements(b, level + 1);
106 b.indent(level);
107 b.write("}");
108 }
109 }
110}