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
use std::{ops::BitOrAssign, str::FromStr};
use crate::{vm::instruction::VmInstruction, VmTranslator};
#[repr(u16)]
#[derive(Clone, Hash, Eq, PartialEq, Debug)]
pub enum AsmInstruction {
A(u16),
C(Dest, Comp, Jump),
Label(String),
Symbol(String),
}
impl AsmInstruction {
pub fn parse(code: &str) -> Vec<AsmInstruction> {
VmTranslator::default().translate(VmInstruction::parse(code))
}
}
impl Default for AsmInstruction {
fn default() -> Self {
Self::A(0)
}
}
impl From<&AsmInstruction> for u16 {
fn from(inst: &AsmInstruction) -> Self {
match inst {
AsmInstruction::A(value) => value & 0b0111_1111_1111_1111,
AsmInstruction::C(dest, comp, jump) => {
0b1110_0000_0000_0000 | *dest as u16 | *comp as u16 | *jump as u16
}
AsmInstruction::Label(label) => {
panic!("Can not convert label to machine instruction: {}", label)
}
AsmInstruction::Symbol(symbol) => {
panic!("Can not convert symbol to machine instruction: {}", symbol)
}
}
}
}
#[repr(u16)]
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum Dest {
Null = 0 << 3,
M = 1 << 3,
D = 2 << 3,
DM = 3 << 3,
A = 4 << 3,
AM = 5 << 3,
AD = 6 << 3,
AMD = 7 << 3,
}
impl From<Dest> for u16 {
fn from(dest: Dest) -> Self {
unsafe { std::mem::transmute(dest) }
}
}
impl From<u16> for Dest {
fn from(n: u16) -> Self {
unsafe { std::mem::transmute(n & 0b0000_0000_0011_1000) }
}
}
impl BitOrAssign for Dest {
fn bitor_assign(&mut self, rhs: Self) {
*self = Dest::from(u16::from(*self) | u16::from(rhs));
}
}
impl FromStr for Dest {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut dest = Dest::Null;
if s.contains('M') {
dest |= Dest::M;
}
if s.contains('D') {
dest |= Dest::D;
}
if s.contains('A') {
dest |= Dest::A;
}
Ok(dest)
}
}
#[repr(u16)]
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum Comp {
Zero = 0b0_1010_10 << 6,
One = 0b0_1111_11 << 6,
MinusOne = 0b0_1110_10 << 6,
D = 0b0_0011_00 << 6,
A = 0b0_1100_00 << 6,
M = 0b1_1100_00 << 6,
NotD = 0b0_0011_01 << 6,
NotA = 0b0_1100_01 << 6,
NotM = 0b1_1100_01 << 6,
MinusD = 0b0_0011_11 << 6,
MinusA = 0b0_1100_11 << 6,
MinusM = 0b1_1100_11 << 6,
DPlusOne = 0b0_0111_11 << 6,
APlusOne = 0b0_1101_11 << 6,
MPlusOne = 0b1_1101_11 << 6,
DMinusOne = 0b0_0011_10 << 6,
AMinusOne = 0b0_1100_10 << 6,
MMinusOne = 0b1_1100_10 << 6,
DPlusA = 0b0_0000_10 << 6,
DPlusM = 0b1_0000_10 << 6,
DMinusA = 0b0_0100_11 << 6,
DMinusM = 0b1_0100_11 << 6,
AMinusD = 0b0_0001_11 << 6,
MMinusD = 0b1_0001_11 << 6,
DAndA = 0b0_0000_00 << 6,
DAndM = 0b1_0000_00 << 6,
DOrA = 0b0_0101_01 << 6,
DOrM = 0b1_0101_01 << 6,
}
impl From<u16> for Comp {
fn from(n: u16) -> Self {
unsafe { std::mem::transmute(n & 0b0001_1111_1100_0000) }
}
}
impl FromStr for Comp {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"0" => Ok(Comp::Zero),
"1" => Ok(Comp::One),
"-1" => Ok(Comp::MinusOne),
"D" => Ok(Comp::D),
"A" => Ok(Comp::A),
"M" => Ok(Comp::M),
"!D" => Ok(Comp::NotD),
"!A" => Ok(Comp::NotA),
"!M" => Ok(Comp::NotM),
"-D" => Ok(Comp::MinusD),
"-A" => Ok(Comp::MinusA),
"-M" => Ok(Comp::MinusM),
"D+1" => Ok(Comp::DPlusOne),
"A+1" => Ok(Comp::APlusOne),
"M+1" => Ok(Comp::MPlusOne),
"D-1" => Ok(Comp::DMinusOne),
"A-1" => Ok(Comp::AMinusOne),
"M-1" => Ok(Comp::MMinusOne),
"D+A" => Ok(Comp::DPlusA),
"D+M" => Ok(Comp::DPlusM),
"D-A" => Ok(Comp::DMinusA),
"D-M" => Ok(Comp::DMinusM),
"A-D" => Ok(Comp::AMinusD),
"M-D" => Ok(Comp::MMinusD),
"D&A" => Ok(Comp::DAndA),
"D&M" => Ok(Comp::DAndM),
"D|A" => Ok(Comp::DOrA),
"D|M" => Ok(Comp::DOrM),
_ => Err(format!("Invalid comp string `{}`", s)),
}
}
}
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum Jump {
No = 0,
Gt = 1,
Eq = 2,
Ge = 3,
Lt = 4,
Ne = 5,
Le = 6,
Jump = 7,
}
impl From<u16> for Jump {
fn from(n: u16) -> Self {
unsafe { std::mem::transmute(n as u8 & 0b0000_0111) }
}
}
impl FromStr for Jump {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"" => Ok(Jump::No),
"JGT" => Ok(Jump::Gt),
"JEQ" => Ok(Jump::Eq),
"JGE" => Ok(Jump::Ge),
"JLT" => Ok(Jump::Lt),
"JNE" => Ok(Jump::Ne),
"JLE" => Ok(Jump::Le),
"JMP" => Ok(Jump::Jump),
_ => Err(format!("Invalid jump string: `{}`", s)),
}
}
}
impl From<u16> for AsmInstruction {
fn from(i: u16) -> Self {
let is_a_instruction = (!i & 0b1000_0000_0000_0000) != 0;
let is_c_instruction = (i & 0b10_0000_0000_0000 != 0)
&& (i & 0b100_0000_0000_0000 != 0)
&& (i & 0b1000_0000_0000_0000 != 0);
if is_a_instruction {
Self::A(i)
} else if is_c_instruction {
Self::C(i.into(), i.into(), i.into())
} else {
panic!("Failed to convert {:b} to asm instruction", i);
}
}
}
impl From<i16> for AsmInstruction {
fn from(i: i16) -> Self {
Self::from(unsafe { std::mem::transmute::<i16, u16>(i) })
}
}
impl From<i32> for AsmInstruction {
fn from(i: i32) -> Self {
let words: [u16; 2] = unsafe { std::mem::transmute(i) };
Self::from(words[1])
}
}
impl std::fmt::Binary for AsmInstruction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Binary::fmt(&u16::from(self), f)
}
}
impl FromStr for AsmInstruction {
type Err = String;
fn from_str(line: &str) -> Result<Self, Self::Err> {
if let Some(symbol_with_suffix) = line.strip_prefix('(') {
if let Some(symbol) = symbol_with_suffix.strip_suffix(')') {
Ok(AsmInstruction::Label(symbol.into()))
} else {
Err("Missing `)` for label".into())
}
} else if let Some(literal_str) = line.strip_prefix('@') {
if let Ok(literal) = literal_str.parse() {
Ok(AsmInstruction::A(literal))
} else {
Ok(AsmInstruction::Symbol(literal_str.into()))
}
} else {
let (equal_index, comp_start) = if let Some(index) = line.find('=') {
(index, index + 1)
} else {
(0, 0)
};
let (semicolon_index, jump_start) = if let Some(index) = line.find(';') {
(index, index + 1)
} else {
(line.len(), line.len())
};
let dest_str = &line[0..equal_index];
let dest = dest_str.parse().unwrap();
let jump_str = &line[jump_start..];
let jump = jump_str.parse().unwrap();
let comp_str = &line[comp_start..semicolon_index];
let comp: Comp = comp_str.parse().unwrap();
Ok(AsmInstruction::C(dest, comp, jump))
}
}
}