code_gen/statement/
with_statements.rs

1use crate::{CodeBuffer, Expression, ExpressionStatement, Literal, Semi, Statement};
2
3/// An element with statements.
4pub trait WithStatements: Sized {
5    /// Gets the statements.
6    fn statements(&self) -> &[Box<dyn Statement>];
7
8    /// Adds the boxed `statement`.
9    fn add_boxed_statement(&mut self, statement: Box<dyn Statement>);
10
11    /// Adds the boxed `statement`.
12    fn with_boxed_statement(mut self, statement: Box<dyn Statement>) -> Self {
13        self.add_boxed_statement(statement);
14        self
15    }
16
17    /// Adds the `statement`.
18    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    /// Adds the `statement`.
26    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    /// Adds the `literal` statement.
34    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    /// Adds the `literal` statement.
42    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    /// Adds the semicolon ended `literal` statement.
50    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    /// Adds the semicolon ended `literal` statement.
58    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    /// Adds the `expression` as a statement.
66    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    /// Adds the `expression` as a statement.
74    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    /// Writes the statements.
82    fn write_statements(&self, b: &mut CodeBuffer, level: usize) {
83        for statement in self.statements() {
84            statement.write(b, level);
85        }
86    }
87
88    /// Writes the curly-bracketed statement block. (`level` is the outer level)
89    fn write_curly_statement_block(&self, b: &mut CodeBuffer, level: usize) {
90        b.write("{");
91        if self.statements().is_empty() {
92            b.write("}");
93        } else {
94            b.end_line();
95            self.write_statements(b, level + 1);
96            b.indent(level);
97            b.write("}");
98        }
99    }
100}