1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
//! This module contains the `Display` trait implementations for the AST nodes.
//!
//! The `Display` trait is used to convert an AST node to a string representation. This
//! is useful for debugging and testing the code.
use std::fmt::{Display, Formatter, Result};

use lexer::token::TokenKind;

use crate::expression::*;
use crate::literal::Literal;
use crate::statement::{
    FunctionDeclaration, RepeatForever, RepeatNTimes, RepeatUntil, Return, Set, Statement,
};
use crate::{Program, StatementList};

impl Display for Program {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "{}", format_semi_seperated(&self.statements))
    }
}

impl Display for StatementList {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "{}", format_semi_seperated(&self.statements))
    }
}

impl Display for Statement {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        match self {
            Statement::Set(Set { ident, expr, .. }) => {
                write!(f, "{} {} = {}", TokenKind::Set, ident.name, expr)
            }
            Statement::Return(Return { value, .. }) => {
                write!(f, "{} {}", TokenKind::Return, value)
            }
            Statement::Expression(expr) => write!(f, "{}", expr),
            Statement::FunctionDeclaration(FunctionDeclaration {
                name,
                parameters,
                body,
                ..
            }) => {
                write!(
                    f,
                    "{} {name}({}){}{}",
                    TokenKind::DefineFunction,
                    format_comma_seperated(&parameters),
                    format_stmt_list(body),
                    TokenKind::End
                )
            }
            Statement::RepeatNTimes(RepeatNTimes { n, body, .. }) => {
                write!(
                    f,
                    "{} {n} {}{}{}",
                    TokenKind::Repeat,
                    TokenKind::Times,
                    format_stmt_list(body),
                    TokenKind::End
                )
            }
            Statement::RepeatUntil(RepeatUntil {
                condition, body, ..
            }) => {
                write!(
                    f,
                    "{} {} {condition}{}{}",
                    TokenKind::Repeat,
                    TokenKind::Until,
                    format_stmt_list(body),
                    TokenKind::End
                )
            }
            Statement::RepeatForever(RepeatForever { body, .. }) => {
                write!(
                    f,
                    "{} {}{}{}",
                    TokenKind::Repeat,
                    TokenKind::Forever,
                    format_stmt_list(body),
                    TokenKind::End
                )
            }
            Statement::Display(display) => {
                write!(
                    f,
                    "{} {}",
                    TokenKind::Display,
                    format_comma_seperated(&display.expressions)
                )
            }
        }
    }
}

impl Display for Expression {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        match self {
            Expression::Identifier(ident) => write!(f, "{}", ident),
            Expression::Literal(l) => write!(f, "{}", l),
            Expression::Unary(Unary {
                operator, operand, ..
            }) => match operator {
                TokenKind::Not => write!(f, "({} {})", operator, operand),
                _ => write!(f, "({}{})", operator, operand),
            },
            Expression::Binary(Binary {
                operator,
                left,
                right,
                ..
            }) => write!(f, "({} {} {})", left, operator, right),
            Expression::FunctionCall(FunctionCall {
                callee, arguments, ..
            }) => write!(f, "{}({})", callee, format_comma_seperated(arguments)),
            Expression::Index(Index { object, index, .. }) => write!(f, "{}[{}]", object, index),
            Expression::Selection(Selection {
                condition,
                conditional,
                else_conditional,
                ..
            }) => {
                let formatted_conditional = match conditional.statements.is_empty() {
                    true => "".to_string(),
                    false => format!(" {}", conditional),
                };

                let formatted_else_conditional = match else_conditional {
                    Some(else_conditional) => match else_conditional.statements.is_empty() {
                        true => format!(" {}", TokenKind::Otherwise),
                        false => format!(" {} {else_conditional}", TokenKind::Otherwise),
                    },
                    None => "".to_string(),
                };

                write!(
                    f,
                    "{} {condition} {}{formatted_conditional}{formatted_else_conditional} {}",
                    TokenKind::If,
                    TokenKind::Then,
                    TokenKind::End,
                )
            }
            Expression::Array(Array { elements, .. }) => {
                write!(f, "[{}]", format_comma_seperated(&elements))
            }
        }
    }
}

impl Display for Identifier {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "{}", self.name)
    }
}

impl Display for Literal {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        match self {
            Literal::Integer { value, .. } => write!(f, "{}", value),
            Literal::Boolean { value, .. } => write!(f, "{}", value),
            Literal::Float { value, .. } => write!(f, "{}", value),
            Literal::String { value, .. } => write!(f, "\"{}\"", value),
        }
    }
}

/// Formats a list of statements into a string representation.
fn format_stmt_list(list: &StatementList) -> String {
    // Some formatting to make the output more readable.
    // If the body is empty, insert a single space between in place of the body.
    // Otherwise, insert the body with a single space before and after it.
    match list.statements.is_empty() {
        true => " ".to_string(),
        false => format!(" {} ", list),
    }
}

/// Formats a list of items into a semi-colon separated string representation.
fn format_semi_seperated<T: ToString>(items: &Vec<T>) -> String {
    return items
        .iter()
        .map(|item| item.to_string())
        .collect::<Vec<String>>()
        .join("; ");
}

/// Formats a list of items into a comma separated string representation.
fn format_comma_seperated<T: ToString>(items: &Vec<T>) -> String {
    return items
        .iter()
        .map(|item| item.to_string())
        .collect::<Vec<String>>()
        .join(", ");
}