microcad_lang/syntax/statement/
if_statement.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! If statement syntax elements.
5
6use crate::{src_ref::*, syntax::*};
7
8/// If statement.
9#[derive(Clone)]
10pub struct IfStatement {
11    /// If condition.
12    pub cond: Expression,
13    /// Body if `true`.
14    pub body: Body,
15    /// Body if `false`.
16    pub body_else: Option<Body>,
17    /// Next if statement: `else if x == 1`.
18    pub next_if: Option<Box<IfStatement>>,
19    /// Source code reference.
20    pub src_ref: SrcRef,
21}
22
23impl SrcReferrer for IfStatement {
24    fn src_ref(&self) -> SrcRef {
25        self.src_ref.clone()
26    }
27}
28
29impl std::fmt::Display for IfStatement {
30    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
31        writeln!(f, "if {cond} {body}", cond = self.cond, body = self.body)?;
32        if let Some(next) = &self.next_if {
33            writeln!(f, "else {next}")?;
34        }
35        if let Some(body) = &self.body_else {
36            writeln!(f, "else {body}")?;
37        }
38        Ok(())
39    }
40}
41
42impl std::fmt::Debug for IfStatement {
43    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
44        writeln!(
45            f,
46            "if {cond:?} {body:?}",
47            cond = self.cond,
48            body = self.body
49        )?;
50        if let Some(next) = &self.next_if {
51            writeln!(f, "else {next:?}")?;
52        }
53        if let Some(body) = &self.body_else {
54            writeln!(f, "else {body:?}")?;
55        }
56        Ok(())
57    }
58}
59
60impl TreeDisplay for IfStatement {
61    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
62        writeln!(f, "{:depth$}IfStatement:", "")?;
63        depth.indent();
64        writeln!(f, "{:depth$}Condition:", "")?;
65        self.cond.tree_print(f, depth.indented())?;
66        writeln!(f, "{:depth$}If:", "")?;
67        self.body.tree_print(f, depth.indented())?;
68        if let Some(body_else) = &self.body_else {
69            writeln!(f, "{:depth$}Else:", "")?;
70            body_else.tree_print(f, depth.indented())?;
71        }
72        Ok(())
73    }
74}