stackr_rs/interpreter/
stringify.rs

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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
use super::*;

struct ProgramTokens {
    tokens: Vec<String>,
    indent_count: usize,
    buffer: String,
}
impl ProgramTokens {
    pub fn new() -> Self {
        Self {
            buffer: String::new(),
            tokens: vec![],
            indent_count: 0,
        }
    }

    pub fn push(&mut self, token: String) {
        self.tokens.push(token);
    }

    fn last_char(&self) -> Option<char> {
        if self.buffer.is_empty() {
            return None;
        }
        Some(self.buffer.chars().last().unwrap())
    }

    pub fn indent(&mut self) {
        self.indent_count += 1;
    }

    pub fn dedent(&mut self) {
        if self.indent_count > 0 {
            self.indent_count -= 1;
        }
    }

    pub fn add_space(&mut self) {
        self.buffer.push(' ');
    }

    pub fn chomp(&mut self) {
        if self.tokens.is_empty() {
            return;
        }
        self.buffer.push_str(&self.tokens.remove(0));
    }

    pub fn peek(&self) -> Option<String> {
        if self.tokens.is_empty() {
            return None;
        }
        Some(self.tokens[0].clone())
    }

    pub fn add_newline(&mut self) {
        self.buffer.push('\n');
        for _ in 0..self.indent_count {
            self.buffer.push('\t');
        }
    }
}

impl<State> Interpreter<State> {
    /// Format a code file.
    pub fn format_code(code: &str, path: Option<PathBuf>) -> Result<String, Err> {
        let mut interpreter = Interpreter::new(());
        interpreter.load_program(code, path)?;
        Ok(interpreter.stringify_program())
    }

    /// Returns the program as a formatted string.
    pub fn stringify_program(&self) -> String {
        // Tokenize the program
        let mut tokens = ProgramTokens::new();
        let mut idx = 0;
        while idx < self.program.len() {
            let instruction = self.program[idx].clone();

            match instruction {
                Instruction::PushNumber(n) => tokens.push(format!("{}", n)),
                Instruction::PushString(s) => tokens.push(format!("\"{}\"", s)),
                Instruction::Address(address) => {
                    tokens.push(self.get_name(address));
                }
            }

            idx += 1;
        }

        while let Some(token) = tokens.peek() {
            match token.as_str() {
                // Function definition
                ":" => {
                    tokens.chomp();
                    tokens.add_space();
                    tokens.chomp();
                    tokens.indent();
                    tokens.add_newline();

                    // Documentation stuff
                    for _ in 0..3 {
                        tokens.chomp();
                        tokens.add_newline();
                    }
                    tokens.add_newline();
                }
                // Function definition end
                ";" => {
                    tokens.dedent();
                    tokens.add_newline();
                    tokens.chomp();
                    tokens.add_newline();
                    tokens.add_newline();
                }
                // Read mode start
                "[" => {
                    tokens.add_newline();
                    tokens.chomp();
                    tokens.indent();
                    tokens.add_newline();
                }
                // Read mode end
                "]" => {
                    tokens.dedent();
                    tokens.add_newline();
                    tokens.chomp();

                    let mut add_newline = true;
                    if let Some(token) = tokens.peek() {
                        if token == ";" {
                            add_newline = false;
                        }
                    }

                    if add_newline {
                        tokens.add_newline();
                    }
                }
                "begin" | "if" => {
                    tokens.add_newline();
                    tokens.chomp();
                    tokens.indent();
                    tokens.add_newline();
                }
                "else" => {
                    tokens.dedent();
                    tokens.add_newline();
                    tokens.chomp();
                    tokens.indent();
                    tokens.add_newline();
                }
                "loop" | "end" => {
                    tokens.dedent();
                    tokens.add_newline();
                    tokens.chomp();

                    if Some("loop".to_string()) == tokens.peek() {
                    } else {
                        tokens.add_newline();
                        tokens.add_newline();
                    }
                }
                "break" => {
                    tokens.add_newline();
                    tokens.chomp();
                }
                "." => {
                    tokens.add_space();
                    tokens.chomp();
                    tokens.add_newline();

                    if let Some(token) = tokens.peek() {
                        match token.as_str() {
                            ":" | "begin" | "if" => {
                                tokens.add_newline();
                            }
                            _ => {}
                        }
                    }
                }
                _ => {
                    if Some("begin".to_string()) == tokens.peek()
                        || Some("if".to_string()) == tokens.peek()
                    {
                        tokens.add_newline();
                    } else if Some('\n') != tokens.last_char() && Some('\t') != tokens.last_char() {
                        tokens.add_space();
                    }
                    tokens.chomp();
                }
            }
        }

        let mut buffer = tokens.buffer.trim().to_string();
        buffer.push('\n');
        buffer
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Helper function to assert that two strings are equal.
    /// Provides debugging information if the assertion fails.
    fn assert_equal(expected: &str, actual: &str) {
        println!("EXPECTED START");
        println!("{}", expected);
        println!("EXPECTED END\n");
        println!("ACTUAL START");
        println!("{}", actual);
        println!("ACTUAL END\n");
        assert_eq!(expected, actual);
    }

    #[test]
    fn stringify_with_noop_formats_nicely() {
        let code = r#"
        var 
        stuff 
        .
    
        1 stuff 
        set .
    
        stuff
        get 
        .
    
    
        : debug "" "" "" print-stack drop ;
        0 begin 1 + dup 2 == if 
                "hello" .  stuff get drop .  break
            end
    
            dup
            2 == if 
                "hello"
            else
                "world" drop end loop "world""#;

        let actual = Interpreter::<()>::format_code(code, None).unwrap();
        let expected = "var stuff .\n1 stuff set .\nstuff get .\n\n: debug\n\t\"\"\n\t\"\"\n\t\"\"\n\t\n\tprint-stack drop\n;\n\n0\nbegin\n\t1 + dup 2 ==\n\tif\n\t\t\"hello\" .\n\t\tstuff get drop .\n\t\t\n\t\tbreak\n\tend\n\t\n\tdup 2 ==\n\tif\n\t\t\"hello\"\n\telse\n\t\t\"world\" drop\n\tend\nloop\n\n\"world\"\n";

        assert_equal(expected, &actual);
    }

    #[test]
    fn stringify_program_returns_program_as_string() {
        let mut interpreter = Interpreter::new(());
        interpreter.evaluate("1 2 +", None).unwrap();
        let program = interpreter.stringify_program();

        assert_equal("1 2 +\n", &program);
    }

    #[test]
    fn stringify_complex_program_returns_program_as_string() {
        let mut interpreter = Interpreter::new(());
        let code = r#"
        : square 
            "stack modification" 
            "documentation"  "example" dup * ; : complextro "stack modification" "documentation" "example" square 3 [ dup * square ] ; 2 square
        "#;
        interpreter.evaluate(code, None).unwrap();
        let program = interpreter.stringify_program();
        let expected = ": square\n\t\"stack modification\"\n\t\"documentation\"\n\t\"example\"\n\t\n\tdup *\n;\n\n: complextro\n\t\"stack modification\"\n\t\"documentation\"\n\t\"example\"\n\t\n\tsquare 3\n\t[\n\t\tdup * square\n\t]\n;\n\n2 square\n";

        assert_equal(expected, &program);
    }

    #[test]
    fn stringify_single_loop_and_if_returns_program_as_string() {
        let mut interpreter = Interpreter::new(());

        let code = r#"
        : debug "" "" "" print-stack drop ;
        0
        begin
            1 + dup

            2 == if 
                "hello" 
                break
            end

            dup
            2 == if 
                "hello"
            else
                "world"
                drop
            end
        loop

        "world"
        
        "#;
        interpreter.evaluate(code, None).unwrap();
        let program = interpreter.stringify_program();
        let expected = ": debug\n\t\"\"\n\t\"\"\n\t\"\"\n\t\n\tprint-stack drop\n;\n\n0\nbegin\n\t1 + dup 2 ==\n\tif\n\t\t\"hello\"\n\t\tbreak\n\tend\n\t\n\tdup 2 ==\n\tif\n\t\t\"hello\"\n\telse\n\t\t\"world\" drop\n\tend\nloop\n\n\"world\"\n";

        assert_equal(expected, &program);
    }
}