Website Summary Files Commits Branches @commit @diff @stats
path: root / assembler / src / parser / mod.rs
blob: 0138243ba0496944881ff9b20d05bd22e5b957f1 (plain) (blame)
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
#![allow(dead_code)]
mod code_gen;
mod syntax;
mod semantic;
mod instruction;

use std::collections::HashMap;
use crate::Word;

#[derive(Debug, Default)]
pub(crate) struct Program {
    definitions: HashMap<String, Address>,
    constants: Vec<Word>,
    instructions: Vec<Instruction>,

    absolute_start: usize,
}

impl Program {
    pub(crate) fn print(&self, start_index: usize) {
        println!("-- Definitions --");
        for (name, loc) in self.definitions.iter() {
            println!("{} := {:?}", name, loc);
        }
        println!("-- Constants --");
        for (i, cnst) in self.constants.iter().enumerate() {
            println!("{: >8}: {} ", i + start_index, cnst);
        }
        println!("-- Instructions --");
        for (i, instr) in self.instructions.iter().enumerate() {
            print!("{: >8}: {} ", i + start_index, instr.name);
            for arg in &instr.args {
                print!("{:?}, ", arg);
            }
            println!("");
        }
    }
}

#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub(crate) enum Address {
    Memory(usize),
    Constants(usize),
    Instruction(usize),
    Definitions(String),

    InstructionOffset(usize, usize), // Internal
    InstructionConstant(usize), // Internal
    #[default]
    None,
}

impl Address {
    fn take(&mut self) -> Address {
        let val = self.clone();
        *self = Address::None;
        val
    }

    fn is_memory(&self) -> bool {
        if let Address::Memory(_) = &self { true } else { false }
    }

    fn is_constant(&self) -> bool {
        if let Address::Constants(_) = &self { true } else { false }
    }

    fn is_instruction(&self) -> bool {
        if let Address::Instruction(_) = &self { true } else { false }
    }

    fn is_definition(&self) -> bool {
        if let Address::Definitions(_) = &self { true } else { false }
    }

    fn is_none(&self) -> bool {
        if let Address::None = &self { true } else { false }
    }

    fn is_location(&self) -> bool {
        self.is_memory() || self.is_instruction()
    }
}

#[derive(Debug, Default, Clone)]
pub(crate) struct Instruction {
    name: String,
    args: Vec<Address>,
}