cortex_lang/parsing/ast/
statement.rs1use crate::parsing::codegen::r#trait::SimpleCodeGen;
2
3use super::{expression::{BinaryOperator, ConditionBody, Expression, IdentExpression, OptionalIdentifier}, r#type::CortexType};
4
5#[derive(Clone)]
6pub enum Statement {
7 Expression(Expression),
8 Throw(Expression),
9 VariableDeclaration {
10 name: OptionalIdentifier,
11 is_const: bool,
12 typ: Option<CortexType>,
13 initial_value: Expression,
14 },
15 VariableAssignment {
16 name: IdentExpression,
17 value: Expression,
18 op: Option<BinaryOperator>,
19 },
20 WhileLoop(ConditionBody),
21}
22impl SimpleCodeGen for Statement {
23 fn codegen(&self, indent: usize) -> String {
24 let mut s = String::new();
25 let indent_prefix = " ".repeat(indent);
26 s.push_str(&indent_prefix);
27 let mut semicolon = true;
28 match self {
29 Self::Expression(expr) => {
30 s.push_str(&expr.codegen(indent));
31 },
32 Self::Throw(expr) => {
33 s.push_str("throw ");
34 s.push_str(&expr.codegen(indent));
35 },
36 Self::VariableDeclaration { name, is_const, typ, initial_value } => {
37 if *is_const {
38 s.push_str("const ");
39 } else {
40 s.push_str("let ");
41 }
42 s.push_str(&name.codegen(indent));
43 if let Some(given_type) = typ {
44 s.push_str(": ");
45 s.push_str(&given_type.codegen(indent));
46 }
47 s.push_str(" = ");
48 s.push_str(&initial_value.codegen(indent));
49 },
50 Self::VariableAssignment { name, value, op } => {
51 s.push_str(&name.codegen(indent));
52 s.push_str(" ");
53 if let Some(binop) = op {
54 s.push_str(&binop.codegen(indent));
55 }
56 s.push_str("= ");
57 s.push_str(&value.codegen(indent));
58 },
59 Self::WhileLoop(cond_body) => {
60 semicolon = false;
61 s.push_str("while ");
62 s.push_str(&cond_body.condition.codegen(indent));
63 s.push_str(" {\n");
64 s.push_str(&cond_body.body.codegen(indent + 1));
65 s.push_str("}");
66 },
67 }
68 if semicolon {
69 s.push_str(";");
70 }
71 s
72 }
73}