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
extern crate pir_8_emu;
use std::io::{BufReader, BufRead, stdout, stdin};
use std::collections::BTreeMap;
use std::process::exit;
use std::borrow::Cow;
use std::fs::File;
static DATA_REMAINING_EXPECTEDS: &[&[&str]] = &[&["1-byte number"], &["1- or 2-byte number"]];
fn main() {
let result = actual_main().err().unwrap_or(0);
exit(result);
}
fn actual_main() -> Result<(), i32> {
let mut opts = pir_8_emu::options::AssemblerOptions::parse();
let registers = opts.register_lettters
.take()
.map(|ll| pir_8_emu::isa::GeneralPurposeRegister::from_letters(&ll).unwrap())
.unwrap_or_else(pir_8_emu::isa::GeneralPurposeRegister::defaults);
let mut output = match opts.output {
Some((name, path)) => {
pir_8_emu::binutils::pir_8_as::OutputWithQueue::new(File::create(path).map_err(|err| {
eprintln!("Error: couldn't create output file \"{}\": {}", name, err);
2
})?)
}
None => pir_8_emu::binutils::pir_8_as::OutputWithQueue::new(stdout()),
};
let mut first_output = true;
let mut next_output_address = None;
let mut labels = BTreeMap::new();
for input in opts.input {
let (input, input_name): (Box<dyn BufRead>, Cow<'static, str>) = match input {
Some((name, path)) => {
(Box::new(BufReader::new(File::open(path).map_err(|err| {
eprintln!("Error: couldn't open input file \"{}\": {}", name, err);
3
})?)),
name.into())
}
None => (Box::new(BufReader::new(stdin())), "<stdin>".into()),
};
let mut data_remaining = 0;
let mut last_instruction = pir_8_emu::isa::instruction::Instruction::Reserved(0);
for (line_number, line) in input.lines().enumerate() {
let line_number = line_number + 1;
let line_orig = line.map_err(|err| {
eprintln!("Error: failed to read line {} of file {}: {}", line_number, input_name, err);
5
})?;
let line = pir_8_emu::util::remove_comment(';', &line_orig).trim_end();
if line.is_empty() {
continue;
}
let mut label_data = None;
let mut literal = None;
if let Some(directive) = pir_8_emu::binutils::pir_8_as::AssemblerDirective::from_str(line).map_err(|err| {
eprintln!("Error: failed to parse assembler directive at {}:{}:", input_name, line_number);
eprintln!("{}", line_orig);
eprintln!("{}", err);
8
})? {
if let Some(ob) = directive.obey(&mut next_output_address, &mut labels)
.map_err(|err| {
eprintln!("Error: failed to obey assembler directive at {}:{}:", input_name, line_number);
eprintln!("{}", line_orig);
eprintln!("{}", err);
8
})? {
match ob {
Ok(ll) => {
let width_err = |data_remaining, frag: pir_8_emu::binutils::pir_8_as::LabelFragment| if data_remaining != frag.len() {
eprintln!("Error: attempted to load {}-byte label data when expecting {} bytes at {}:{}:",
frag.len(),
data_remaining,
input_name,
line_number);
eprintln!("{}", line_orig);
Err(8)
} else {
Ok(())
};
match ll {
pir_8_emu::binutils::pir_8_as::LabelLoad::HaveImmediately(addr, frag) => {
width_err(data_remaining, frag)?;
label_data = Some((addr, frag));
}
pir_8_emu::binutils::pir_8_as::LabelLoad::WaitFor(lbl, offset, frag) => {
width_err(data_remaining, frag)?;
output.wait_for_label(lbl, offset, frag);
data_remaining = 0;
next_output_address = Some(next_output_address.unwrap_or(0) + frag.len() as u16);
continue;
}
}
}
Err(lit) => {
if data_remaining != 0 {
eprintln!("Error: attempted to insert literal {:?} when expecting {} bytes at {}:{}:",
lit,
data_remaining,
input_name,
line_number);
eprintln!("{}", line_orig);
return Err(8);
}
literal = Some(lit);
}
}
} else {
continue;
}
}
if first_output && next_output_address.is_some() {
for _ in 0..next_output_address.unwrap() {
output.write_all(&[0x00], &labels)
.map_err(|err| {
eprintln!("Error: failed to write origin padding: {}", err);
4
})?;
}
}
first_output = false;
if let Some(lit) = literal {
output.write_all(lit.as_bytes(), &labels)
.map_err(|err| {
eprintln!("Error: failed to write literal {}: {}", lit, err);
4
})?;
next_output_address = Some(next_output_address.unwrap_or(0) + lit.as_bytes().len() as u16);
} else if data_remaining != 0 {
let line = line.trim_start();
let data: u16 = match label_data {
Some((addr, pir_8_emu::binutils::pir_8_as::LabelFragment::Full)) => addr,
Some((addr, pir_8_emu::binutils::pir_8_as::LabelFragment::High)) => addr >> 8,
Some((addr, pir_8_emu::binutils::pir_8_as::LabelFragment::Low)) => addr & 0xFF,
None =>
pir_8_emu::util::parse_with_prefix(line).and_then(|data| pir_8_emu::util::limit_to_width(data, data_remaining * 8))
.ok_or_else(|| {
eprintln!("Error: failed to parse instruction data for {} ({} bytes remaining) at {}:{}:",
last_instruction.display(®isters),
data_remaining,
input_name,
line_number);
eprintln!("{}", line_orig);
eprintln!("{}",
pir_8_emu::isa::instruction::ParseInstructionError::UnrecognisedToken(
(line.as_ptr() as usize) - (line_orig.as_ptr() as usize),
DATA_REMAINING_EXPECTEDS[data_remaining as usize - 1]));
7
})?,
};
let data_length = data_remaining;
next_output_address = Some(next_output_address.unwrap_or(0) + data_length as u16);
data_remaining = 0;
if data_length == 1 {
output.write_all(&[data as u8], &labels)
} else {
output.write_all(&[(data >> 8) as u8, (data & 0b1111_1111) as u8], &labels)
}.map_err(|err| {
eprintln!("Error: failed to write instruction data {:#w$x} for {} from {}:{}: {}",
data,
last_instruction.display(®isters),
input_name,
line_number,
err,
w = 2 + data_length as usize * 2);
4
})?;
} else {
last_instruction = pir_8_emu::isa::instruction::Instruction::from_str(line, ®isters).map_err(|err| {
eprintln!("Error: failed to parse instruction at {}:{}:", input_name, line_number);
eprintln!("{}", line_orig);
eprintln!("{}", err);
6
})?;
data_remaining = last_instruction.data_length() as u8;
next_output_address = Some(next_output_address.unwrap_or(0) + 1);
output.write_all(&[last_instruction.into()], &labels)
.map_err(|err| {
eprintln!("Error: failed to write instruction {} from {}:{}: {}",
last_instruction.display(®isters),
input_name,
line_number,
err);
4
})?;
}
}
}
output.flush(&labels)
.map_err(|err| {
eprintln!("Failed to flush output buffer: {}", err);
4
})?;
if let Some(labels) = output.unfound_labels(&labels) {
eprintln!("Error: the following {} labels were not found:", labels.len());
for label in labels {
eprintln!(" {}", label);
}
return Err(9);
}
Ok(())
}