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
|
mod code_gen;
mod syntax;
mod semantic;
mod instruction;
use std::{
collections::HashMap,
fmt::{ Display, Formatter, Result },
};
use crate::Word;
#[derive(Debug, Default)]
pub(crate) struct Program {
definitions: HashMap<String, Address>,
constants: Vec<Word>,
instructions: Vec<Instruction>,
}
impl Display for Program {
fn fmt(&self, f: &mut Formatter) -> Result {
writeln!(f, "-- Definitions --")?;
for (name, loc) in self.definitions.iter() {
writeln!(f, "{} := {:?}", name, loc)?;
}
writeln!(f, "-- Constants --")?;
for (i, cnst) in self.constants.iter().enumerate() {
writeln!(f, "{: >8}: {} ", i, cnst)?;
}
writeln!(f, "-- Instructions --")?;
for (i, instr) in self.instructions.iter().enumerate() {
write!(f, "{: >8}: {} ", i, instr.name)?;
for arg in &instr.args {
write!(f, "{:?}, ", arg)?;
}
writeln!(f, "")?;
}
Ok(())
}
}
#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub(crate) enum Address {
Memory(usize),
Constants(usize),
Instruction(usize),
Definitions(String),
#[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>,
}
|