xenon_codegen/
if_statement.rs1use core::fmt;
2
3use crate::{expression::Expression, statement::Statement};
4
5#[derive(Debug, Clone, Default)]
6pub struct IfStatement {
7 pub condition: Expression,
8 pub body: Box<Statement>,
9 pub else_body: Option<Box<Statement>>,
10}
11impl IfStatement {
12 pub fn new(condition: Expression, body: Statement) -> IfStatement {
13 IfStatement {
14 condition,
15 body: Box::new(body),
16 else_body: None,
17 }
18 }
19
20 pub fn is_valid(&self) -> bool {
21 if !self.condition.is_valid() {
22 return false;
23 }
24 if !self.body.is_valid() {
25 return false;
26 }
27 if let Some(b) = self.else_body.clone() {
28 if !b.is_valid() {
29 return false;
30 }
31 }
32 true
33 }
34}
35impl fmt::Display for IfStatement {
36 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 match write!(fmt, "if ({}) {}", self.condition, self.body) {
38 Ok(_) => (),
39 Err(e) => return Err(e),
40 }
41 if let Some(eb) = self.else_body.clone() {
42 match write!(fmt, "\nelse {}", eb) {
43 Ok(_) => (),
44 Err(e) => return Err(e),
45 }
46 }
47 Ok(())
48 }
49}