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
pub mod instruction;
pub mod operand;

use crate::{instruction::Instruction, instruction::InstructionParseError};
use std::{collections::HashMap, str::FromStr};
use thiserror::Error;

use super::operand::CellAddress;

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RamCode {
    pub instructions: Vec<Instruction>,
    pub jump_table: HashMap<String, CellAddress>,
}

#[derive(Error, Debug, PartialEq, Eq)]
pub enum CodeParseError {
    #[error("Expected EOL, found `{0}`")]
    UnexpectedArgument(String),
    #[error(transparent)]
    InstructionParseError(#[from] InstructionParseError),
}

macro_rules! return_if_comment {
    ($e:expr) => {
        if $e.starts_with('#') {
            return Ok(());
        }
    };
}

const LABEL_END: char = ':';

impl RamCode {
    pub fn new() -> RamCode {
        RamCode {
            instructions: Vec::new(),
            jump_table: HashMap::new(),
        }
    }

    pub fn push_line(&mut self, line: &str) -> Result<(), CodeParseError> {
        let mut slices = line.split_whitespace().filter(|s| !s.is_empty());

        let mut slice = match slices.next() {
            None => return Ok(()),
            Some(val) => val,
        };

        return_if_comment!(slice);

        if slice.ends_with(LABEL_END) {
            self.jump_table.insert(
                slice.trim_end_matches(':').to_owned(),
                self.instructions.len(),
            );

            slice = match slices.next() {
                Some(val) => val,
                None => return Ok(()),
            }
        }

        return_if_comment!(slice);

        let argument = slices.next();

        let instruction = Instruction::try_from((slice, argument))?;
        self.add_instruction(instruction);

        let rest = slices.next();

        if let Some(v) = rest {
            return_if_comment!(v);
            return Err(CodeParseError::UnexpectedArgument(v.to_string()));
        }

        Ok(())
    }

    pub fn add_instruction(&mut self, instruction: Instruction) {
        self.instructions.push(instruction)
    }
}

impl FromStr for RamCode {
    type Err = CodeParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut code = RamCode::new();
        let lines = s.lines().filter(|line| !line.is_empty());
        for line in lines {
            code.push_line(line)?;
        }
        Ok(code)
    }
}