Website Summary Files Commits Branches @commit @diff @stats
path: root / assembler / src / parser / code_gen.rs
blob: 92bf1d1e2b856f2a3cb53f310cf53560ca455018 (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
use crate::Word;
use super::{ Program, Address };

impl Program {
    /* Intermediate code generation */

    pub(crate) fn remove_definition_addresses(&mut self) {
        for instr in &mut self.instructions {
            for arg in &mut instr.args {
                if let Address::Definitions(name) = arg {
                    *arg = self.definitions[name].clone();
                }
            }
        }
        self.definitions.clear();
    }

    pub(crate) fn collapse_instructions(&mut self) {
        let mut collapsed = Vec::new();

        for instr in &mut self.instructions {
            collapsed.extend(instr.collapse(collapsed.len()));
        }

        self.instructions = collapsed;
    }

    /* Machine code generation */

    pub(crate) fn instructions_to_constants(&mut self, absolute_start: usize) {
        let constlen = self.constants.len();

        for instr in &mut self.instructions {
            for arg in &mut instr.args {
                self.constants.push(match arg {
                    Address::Memory(num) => *num,
                    Address::Constants(num) => absolute_start + *num,
                    Address::Instruction(num) => constlen + absolute_start + *num * 3,
                    _ => unreachable!("Definition addresses should've already been removed!"),
                } as Word);
            }
        }
        self.instructions.clear();
    }

    pub(crate) fn to_bytes(self, absolute_start: usize) -> Vec<u8> {
        let mut res = Vec::new();
        res.resize(absolute_start, Default::default());
        res.extend(self.constants);
        res
            .into_iter()
            .map(|x| x.to_be_bytes())
            .flatten()
            .collect()
    }
}