poetic 0.3.1

library to parse and interpret poetic source code
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use crate::instruction::Instruction;
use split_digits::SplitDigitIterator;
use std::{cmp::Ordering, fmt::Display};

#[derive(Debug, Clone, PartialEq)]
pub enum ParseError {
    UnknownInstruction(u8),
    NeedsArgument(u8),
    MissingIf,
    MissingEif,
}

impl Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::UnknownInstruction(instruction) => {
                write!(f, "Unknown instruction: {}", instruction)
            }
            ParseError::NeedsArgument(instruction) => {
                match Parser::get_instruction_name(instruction) {
                    Some(instruction_name) => {
                        write!(f, "{} Instruction needs an argument", instruction_name)
                    }
                    // should never happen
                    None => {
                        write!(
                            f,
                            "Unknown instruction \"{}\" needs an argument",
                            instruction
                        )
                    }
                }
            }
            ParseError::MissingIf => write!(f, "Missing IF"),
            ParseError::MissingEif => write!(f, "Missing EIF"),
        }
    }
}

pub struct Parser {}

impl Parser {
    fn split_digits(d: usize) -> Vec<u8> {
        SplitDigitIterator::new(d).collect()
    }

    /// Any character that is not an alphabetic character or apostrophe is ignored, and treated as whitespace
    fn transform_char(c: char) -> String {
        match c {
            'a'..='z' | 'A'..='Z' => c.to_string(),
            '\'' => "".to_string(),
            _ => " ".to_string(),
        }
    }

    pub fn parse_intermediate(source: &str) -> Vec<u8> {
        let mut result = Vec::new();

        source
            .chars()
            .map(Parser::transform_char)
            .collect::<String>()
            .split_whitespace()
            .map(|w| w.len())
            .for_each(|d| match d.cmp(&10) {
                Ordering::Less => result.push(d as u8),
                Ordering::Equal => result.push(0),
                Ordering::Greater => result.append(&mut Parser::split_digits(d)),
            });

        result
    }

    fn argument_conversion(argument: u8) -> u8 {
        if argument == 0 {
            return 10;
        }

        argument
    }

    fn check_if_eif_mismatch(instructions: &[Instruction]) -> Option<ParseError> {
        // check for matching if/eif
        let mut i = 0;
        while i < instructions.len() {
            match instructions[i] {
                Instruction::IF => {
                    let mut instruction_pointer = i;

                    let mut nested = 1;
                    while nested != 0 {
                        instruction_pointer += 1;
                        if instruction_pointer >= instructions.len() {
                            return Some(ParseError::MissingEif);
                        }

                        let nested_instruction = instructions[instruction_pointer];
                        match nested_instruction {
                            Instruction::IF => {
                                nested += 1;
                            }
                            Instruction::EIF => {
                                nested -= 1;
                            }
                            _ => {}
                        }
                    }
                }
                Instruction::EIF => {
                    let mut instruction_pointer = i;

                    let mut nested = -1;
                    while nested != 0 {
                        if instruction_pointer == 0 {
                            return Some(ParseError::MissingIf);
                        }

                        instruction_pointer -= 1;

                        let nested_instruction = instructions[instruction_pointer];
                        match nested_instruction {
                            Instruction::IF => {
                                nested += 1;
                            }
                            Instruction::EIF => {
                                nested -= 1;
                            }
                            _ => {}
                        }
                    }
                }
                _ => {}
            }

            i += 1;
        }

        None
    }

    fn get_instruction_name(instruction: &u8) -> Option<&'static str> {
        match instruction {
            0 => Some("END"),
            1 => Some("IF"),
            2 => Some("EIF"),
            3 => Some("INC"),
            4 => Some("DEC"),
            5 => Some("FWD"),
            6 => Some("BAK"),
            7 => Some("OUT"),
            8 => Some("IN"),
            9 => Some("RND"),
            10 => Some("END"),
            _ => None,
        }
    }

    pub fn parse_instructions(intermediate: &[u8]) -> Result<Vec<Instruction>, ParseError> {
        let mut result = Vec::new();
        let mut iter = intermediate.iter();
        while let Some(arg) = iter.next() {
            let instruction = match arg {
                0 => Ok(Instruction::END),
                1 => Ok(Instruction::IF),
                2 => Ok(Instruction::EIF),
                3 => iter
                    .next()
                    .map(|x| Instruction::INC(Parser::argument_conversion(*x)))
                    .ok_or(ParseError::NeedsArgument(3)),
                4 => iter
                    .next()
                    .map(|x| Instruction::DEC(Parser::argument_conversion(*x)))
                    .ok_or(ParseError::NeedsArgument(4)),
                5 => iter
                    .next()
                    .map(|x| Instruction::FWD(Parser::argument_conversion(*x)))
                    .ok_or(ParseError::NeedsArgument(5)),
                6 => iter
                    .next()
                    .map(|x| Instruction::BAK(Parser::argument_conversion(*x)))
                    .ok_or(ParseError::NeedsArgument(6)),
                7 => Ok(Instruction::OUT),
                8 => Ok(Instruction::IN),
                9 => Ok(Instruction::RND),
                10 => Ok(Instruction::END),
                _ => Err(ParseError::UnknownInstruction(*arg)),
            }?;

            result.push(instruction);
        }

        Parser::check_if_eif_mismatch(&result).map_or(Ok(result), Err)
    }

    pub fn parse(source: &str) -> Result<Vec<Instruction>, ParseError> {
        let intermediate = Self::parse_intermediate(source);
        Self::parse_instructions(&intermediate)
    }
}

#[cfg(test)]
mod test {
    use super::Parser;
    use crate::{instruction::Instruction, parser::ParseError};

    #[test]
    fn test_intermediate_len() {
        // parse correct length
        for i in 1..10 {
            let intermediate = Parser::parse_intermediate(&str::repeat("a", i));
            assert_eq!(intermediate[0], i as u8);
        }
    }

    #[test]
    fn test_intermediate_10_as_0() {
        // parse 10 as 0
        let intermediate = Parser::parse_intermediate(&str::repeat("a", 10));
        assert_eq!(intermediate[0], 0);
    }

    #[test]
    fn test_intermediate_11_as_1_1() {
        // parse 11 as 1 and 1
        let intermediate = Parser::parse_intermediate(&str::repeat("a", 11));
        assert_eq!(intermediate[0], 1);
        assert_eq!(intermediate[1], 1);
    }

    #[test]
    fn test_intermediate_12345_as_1_2_3_4_5() {
        // parse 12345 as 1,2,3,4,5
        let intermediate = Parser::parse_intermediate(&str::repeat("a", 12345));
        assert_eq!(intermediate[0], 1);
        assert_eq!(intermediate[1], 2);
        assert_eq!(intermediate[2], 3);
        assert_eq!(intermediate[3], 4);
        assert_eq!(intermediate[4], 5);
    }

    #[test]
    fn test_intermediate_ignore_apostrophe() {
        // parse 1 as 1 ignoring apostrophe
        let intermediate = Parser::parse_intermediate("'a'");
        assert_eq!(intermediate[0], 1);
    }

    #[test]
    fn test_intermediate_non_alpha_as_whitespace() {
        // parse 1 as 1
        let intermediate = Parser::parse_intermediate("1a");
        assert_eq!(intermediate[0], 1);

        let intermediate = Parser::parse_intermediate("1a1a");
        assert_eq!(intermediate[0], 1);
        assert_eq!(intermediate[1], 1);
    }

    #[test]
    fn test_intermediate_28_as_2_8() {
        // parse 10 as 0
        let intermediate = Parser::parse_intermediate(&str::repeat("a", 28));
        assert_eq!(intermediate[0], 2);
        assert_eq!(intermediate[1], 8);
    }

    #[test]
    fn test_parse_argument_0_as_10() {
        // len 30 -> 3,0 -> 3 = INC with arg 0 should be parsed as 10
        let intermediate = Parser::parse_intermediate(&str::repeat("a", 30));
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::INC(10));
    }

    #[test]
    fn test_instruction_if_eif() {
        let intermediate = vec![1, 2];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        let instructions = instructions.unwrap();
        assert_eq!(instructions[0], Instruction::IF);
        assert_eq!(instructions[1], Instruction::EIF);
    }

    #[test]
    fn test_instruction_missing_eif() {
        let intermediate = vec![1];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_err());
        assert_eq!(instructions.unwrap_err(), ParseError::MissingEif);
    }

    #[test]
    fn test_instruction_missing_if() {
        let intermediate = vec![2];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_err());
        assert_eq!(instructions.unwrap_err(), ParseError::MissingIf);
    }

    #[test]
    fn test_instruction_inc() {
        let intermediate = vec![3, 1];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::INC(1));
    }

    #[test]
    fn test_instruction_inc_needs_arg() {
        // INC Instruction needs an argument
        let intermediate = vec![3];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_err());
        assert_eq!(instructions.unwrap_err(), ParseError::NeedsArgument(3));
    }

    #[test]
    fn test_instruction_dec() {
        let intermediate = vec![4, 1];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::DEC(1));
    }

    #[test]
    fn test_instruction_dec_needs_arg() {
        // DEC Instruction needs an argument
        let intermediate = vec![4];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_err());
        assert_eq!(instructions.unwrap_err(), ParseError::NeedsArgument(4));
    }

    #[test]
    fn test_instruction_fwd() {
        let intermediate = vec![5, 1];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::FWD(1));
    }

    #[test]
    fn test_instruction_fwd_needs_arg() {
        // FWD Instruction needs an argument
        let intermediate = vec![5];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_err());
        assert_eq!(instructions.unwrap_err(), ParseError::NeedsArgument(5));
    }

    #[test]
    fn test_instruction_bak() {
        let intermediate = vec![6, 1];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::BAK(1));
    }

    #[test]
    fn test_instruction_bak_needs_arg() {
        // BAK Instruction needs an argument
        let intermediate = vec![6];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_err());
        assert_eq!(instructions.unwrap_err(), ParseError::NeedsArgument(6));
    }

    #[test]
    fn test_instruction_out() {
        let intermediate = vec![7];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::OUT);
    }

    #[test]
    fn test_instruction_in() {
        let intermediate = vec![8];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::IN);
    }

    #[test]
    fn test_instruction_rnd() {
        let intermediate = vec![9];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::RND);
    }

    #[test]
    fn test_instruction_end10() {
        let intermediate = vec![10];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::END);
    }

    #[test]
    fn test_instruction_end0() {
        let intermediate = vec![0];
        let instructions = Parser::parse_instructions(&intermediate);
        assert!(instructions.is_ok());
        assert_eq!(instructions.unwrap()[0], Instruction::END);
    }

    #[test]
    fn test_parser_split_digits() {
        let digits = Parser::split_digits(568764567);
        assert_eq!(digits, vec![5, 6, 8, 7, 6, 4, 5, 6, 7]);
    }

    #[test]
    fn test_parser_transform_char() {
        let tests = vec![('a', "a"), ('9', " "), ('\'', ""), ('F', "F")];

        for test in tests {
            let result = Parser::transform_char(test.0);
            assert_eq!(result, test.1);
        }
    }
}