1use std::{collections::HashMap, default, fmt, fs, str};
2
3use cfd16_lib::prelude::*;
4
5use crate::error::{AssemErrorKind, AssemblerError};
6use crate::text::*;
7
8type SymbolTable = HashMap<String, Argument>;
9
10fn parse_string(textitem: &mut dyn Iterator<Item = &str>) -> String {
11 let mut value;
12
13 let mut arg = match textitem.next() {
14 Some(a) if a.starts_with('"') => a,
15 _ => panic!("arg must be str"),
16 };
17
18 value = arg.replace('"', "");
19
20 while !arg.ends_with('"') {
21 arg = match textitem.next() {
22 Some(a) => a,
23 _ => panic!("arg must be str"),
24 };
25
26 value = format!("{value} {}", arg.replace('"', ""))
27 }
28
29 return value;
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum BinFormat {
35 Elf,
39
40 Raw,
43}
44
45impl default::Default for BinFormat {
46 fn default() -> Self {
47 Self::Raw
48 }
49}
50
51impl fmt::Display for BinFormat {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 match self {
54 BinFormat::Elf => write!(f, "elf"),
55 BinFormat::Raw => write!(f, "bin"),
56 }
57 }
58}
59
60impl str::FromStr for BinFormat {
61 type Err = AssemblerError;
62
63 fn from_str(s: &str) -> Result<Self, Self::Err> {
64 match s {
65 "bin" => Ok(BinFormat::Raw),
66 "elf" => Ok(BinFormat::Elf),
67 _ => Err(AssemblerError::new(
68 None,
69 AssemErrorKind::NoSuchBinaryFormat,
70 )),
71 }
72 }
73}
74
75#[derive(Debug, Clone)]
76pub(crate) struct Program {
77 format: BinFormat,
78 sections: Vec<TextSection>,
79 symbols: SymbolTable,
80}
81
82impl fmt::Display for Program {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 let mut output = String::new();
85 let mut symbols = String::new();
86
87 for section in &self.sections {
88 output = format!("{output}\n{section}");
89 }
90
91 for (symbol, argument) in &self.symbols {
92 symbols = format!("{}\t{} => {}\n", symbols, symbol, argument);
93 }
94
95 write!(
96 f,
97 "Instrs:\n{}\n\nFormat: {}\n\nSymbols:\n{}",
98 output, self.format, symbols
99 )
100 }
101}
102
103impl Program {
104 pub(crate) fn from_source(source: String, format: BinFormat) -> Result<Self, AssemblerError> {
105 let source = Program::preprocess(source)?;
106 let mut prog = Program::new(format);
107
108 prog.parse(&source)?;
109
110 Ok(prog)
111 }
112
113 pub(crate) fn new(format: BinFormat) -> Self {
114 Self {
115 format,
116 sections: vec![],
117 symbols: HashMap::new(),
118 }
119 }
120
121 fn as_mut_text_items(&mut self) -> Vec<&mut TextItem> {
122 self.sections
123 .iter_mut()
124 .map(|s| s.items.iter_mut())
125 .flatten()
126 .collect()
127 }
128
129 pub(crate) fn add(&mut self, item: TextItem) {
130 match self.sections.iter_mut().last() {
131 Some(ref mut s) => s.items.push(item),
132 None => {
133 let mut s = TextSection::new(Mode::User, SecKind::Text);
134 s.items.push(item);
135 self.sections.push(s)
136 }
137 }
138 }
139
140 pub(crate) fn advance(&mut self, mode: Mode, kind: SecKind) {
141 self.sections.push(TextSection::new(mode, kind));
142 }
143
144 pub(crate) fn preprocess(source: String) -> Result<String, AssemblerError> {
145 let mut last_label: Option<String> = None;
146 let mut mappings: Vec<(String, String, String)> = vec![];
147
148 for (n, line) in source.lines().enumerate() {
150 if line.contains(':') {
151 let split: Vec<&str> = line.split(':').collect();
152
153 let mut label = String::from(split[0]);
154
155 match (label.starts_with('.'), last_label.as_ref()) {
156 (true, None) => {
157 return Err(AssemblerError::new(
158 Some(n),
159 AssemErrorKind::NoLabelBeforeDotLabel(label),
160 ));
161 }
162
163 (true, Some(l)) => {
164 let prev = label.clone();
165 label = format!("{}{}", l.clone(), label);
166 mappings.push((l.clone(), prev, label.clone()));
167 }
168 _ => {
169 last_label = Some(label.clone());
170 }
171 }
172 }
173 }
174
175 let mut output = String::new();
176 let mut last_label: Option<&str> = None;
177
178 for line in source.lines() {
180 let mut line = line;
181
182 if line.contains(';') {
183 line = line.split(';').nth(0).unwrap();
184 }
185
186 if line.contains(':') {
187 if let Some(label) = line.split(':').next() {
188 if !label.starts_with('.') {
189 last_label = Some(label);
190 }
191 }
192 }
193
194 let mut line = String::from(line);
195
196 for (parent, needle, replacement) in &mappings {
197 if last_label != Some(parent) {
198 break;
199 }
200
201 line = line.replace(needle, replacement);
202 }
203
204 output = format!("{output}{line}\n")
205 }
206
207 Ok(output)
208 }
209
210 pub(crate) fn parse(&mut self, source: &str) -> Result<(), AssemblerError> {
211 let mut address = 0;
212
213 for (i, line) in source.lines().enumerate() {
214 self.parse_line(&mut address, (i, line))?;
215 }
216
217 Ok(())
218 }
219
220 fn parse_line(
221 &mut self,
222 address: &mut isize,
223 line: (usize, &str),
224 ) -> Result<(), AssemblerError> {
225 let (linenum, mut line) = line;
226
227 if line.contains(':') {
231 let mut splitline = line.split(':');
232 let label = match splitline.next() {
233 Some(l) => l,
234 None => {
235 return Err(AssemblerError::new(
236 Some(linenum),
237 AssemErrorKind::InvalidLabel,
238 ))
239 }
240 };
241
242 self.symbols
243 .insert(label.trim().into(), Argument::Imm(*address & 0xffff));
244
245 let instr_left = splitline.collect::<Vec<&str>>();
246 if instr_left.len() > 1 {
247 return Err(AssemblerError::new(
248 Some(linenum),
249 AssemErrorKind::InvalidLabel,
250 ));
251 }
252
253 line = instr_left[0];
254 }
255
256 let line = line.replace(",", " ").replace("(", " ").replace(")", " ");
258
259 let mut textitem = line
260 .split(';')
261 .nth(0)
262 .expect("Shouldn't happen") .split(' ')
264 .filter(|s| !s.is_empty())
265 .peekable();
266
267 if let Some(mnem) = textitem.next() {
268 if mnem.starts_with('.') {
269 match mnem.to_lowercase().as_str() {
270 ".space" => {
271 let arg = match textitem.next() {
272 Some(a) => a,
273 None => {
274 return Err(AssemblerError::new(
275 Some(linenum),
276 AssemErrorKind::InvalidArgument(
277 "No argument provided to '.space'".into(),
278 ),
279 ));
280 }
281 };
282
283 let value = match Argument::parse_int(arg) {
284 Ok(v) => v,
285 Err(_) => {
286 return Err(AssemblerError::new(
287 Some(linenum),
288 AssemErrorKind::InvalidArgument("Could not parse argument provided to '.space' as an integer.".into()),
289 ));
290 }
291 };
292
293 self.add(TextItem::new(
294 TextItemKind::Dir(Directive::Space(value as usize)),
295 address,
296 linenum,
297 ));
298 }
299
300 ".word" => {
301 let arg = match textitem.next() {
302 Some(a) => a,
303 None => {
304 return Err(AssemblerError::new(
305 Some(linenum),
306 AssemErrorKind::InvalidArgument(
307 "No argument provided to '.word'".into(),
308 ),
309 ));
310 }
311 };
312
313 let value = match Argument::parse_int(arg) {
314 Ok(v) => v,
315 Err(_) => {
316 return Err(AssemblerError::new(
317 Some(linenum),
318 AssemErrorKind::InvalidArgument("Could not parse argument provided to '.word' as an integer.".into()),
319 ));
320 }
321 };
322
323 self.add(TextItem::new(
324 TextItemKind::Dir(Directive::Word(value as u16)),
325 address,
326 linenum,
327 ));
328 }
329
330 ".org" => {
331 let arg = match textitem.next() {
332 Some(a) => a,
333 None => {
334 return Err(AssemblerError::new(
335 Some(linenum),
336 AssemErrorKind::InvalidArgument(
337 "No argument provided to '.word'".into(),
338 ),
339 ));
340 }
341 };
342
343 let value = match Argument::parse_int(arg) {
344 Ok(v) => v,
345 Err(_) => {
346 return Err(AssemblerError::new(
347 Some(linenum),
348 AssemErrorKind::InvalidArgument("Could not parse argument provided to '.word' as an integer.".into()),
349 ));
350 }
351 };
352
353 *address = value
354 }
355
356 ".global" => {
357 self.add(TextItem::new(
358 TextItemKind::Dir(Directive::Global(textitem.next().unwrap().into())),
359 address,
360 linenum,
361 ));
362 }
363
364 ".extern" => {
365 self.add(TextItem::new(
366 TextItemKind::Dir(Directive::Extern(textitem.next().unwrap().into())),
367 address,
368 linenum,
369 ));
370 }
371
372 ".kernel.text" => self.advance(Mode::Kernel, SecKind::Text),
373 ".kernel.data" => self.advance(Mode::Kernel, SecKind::Data),
374 ".user.text" | ".text" => self.advance(Mode::User, SecKind::Text),
375 ".user.data" | ".data" => self.advance(Mode::User, SecKind::Data),
376
377 ".equ" => {
378 let symbol = textitem.next().unwrap();
379 let value = match Argument::parse(textitem.next().unwrap()) {
380 Some(v) => v,
381 None => {
382 return Err(AssemblerError::new(
383 Some(linenum),
384 AssemErrorKind::InvalidArgument(
385 "'.equ' should be provided with a valid second argument."
386 .into(),
387 ),
388 ));
389 }
390 };
391
392 if symbol.starts_with('.') {
395 return Err(AssemblerError::new(
396 Some(linenum),
397 AssemErrorKind::InvalidLabel,
398 ));
399 }
400
401 self.symbols.insert(symbol.into(), value);
402 }
403
404 ".mov" => {
405 let regval = textitem.next().unwrap();
406 let register = Argument::parse(regval);
407
408 if let Some(Argument::Reg(_)) = register {
409 } else {
410 return Err(AssemblerError::new(
411 Some(linenum),
412 AssemErrorKind::InvalidArgument(regval.into()),
413 ));
414 }
415
416 let value = match Argument::parse(textitem.next().unwrap()) {
417 Some(Argument::Imm(i)) => {
418 let [top, bottom] = (i as u16).to_be_bytes();
419 (Argument::Imm(bottom as isize), Argument::Imm(top as isize))
420 }
421
422 Some(Argument::Label(l)) => {
423 let prefixed = format!("={}", l);
424 (Argument::Label(prefixed.clone()), Argument::Label(prefixed))
425 }
426
427 _ => todo!(),
428 };
429
430 self.add(TextItem::new(
431 TextItemKind::Instr(
432 InstructionBuilder::new(OpCode::Mov)
433 .argument(register.as_ref().unwrap().clone())
434 .argument(value.0),
435 ),
436 address,
437 linenum,
438 ));
439
440 self.add(TextItem::new(
441 TextItemKind::Instr(
442 InstructionBuilder::new(OpCode::Movt)
443 .argument(register.as_ref().unwrap().clone())
444 .argument(value.1),
445 ),
446 address,
447 linenum,
448 ));
449 }
450
451 ".nop" => {
452 self.add(TextItem::new(
453 TextItemKind::Instr(InstructionBuilder::default()),
454 address,
455 linenum,
456 ));
457 }
458
459 ".ascii" => {
460 let value = parse_string(&mut textitem);
461 self.add(TextItem::new(TextItemKind::String(value), address, linenum));
462 }
463
464 ".include" => {
465 let value = parse_string(&mut textitem);
466 let source = match fs::read_to_string(value) {
467 Ok(s) => s,
468 Err(_) => {
469 return Err(AssemblerError::new(
470 Some(linenum),
471 AssemErrorKind::IncludePathInvalid,
472 ))
473 }
474 };
475
476 let subprog = match Program::from_source(source, self.format) {
477 Ok(t) => t,
478 Err(e) => return Err(AssemblerError::included(linenum, e)),
479 };
480
481 for ti in &subprog.sections[0].items {
484 self.add(TextItem::new(ti.kind.clone(), address, linenum));
485 }
486 }
487
488 _ => {
489 return Err(AssemblerError::new(
490 Some(linenum),
491 AssemErrorKind::InvalidMnemonic(mnem.into()),
492 ))
493 }
494 }
495 } else {
496 let (op, sbit, cond) = match OpCode::parse(mnem) {
497 Some(t) => t,
498 None => {
499 return Err(AssemblerError::new(
500 Some(linenum),
501 AssemErrorKind::InvalidMnemonic(mnem.into()),
502 ))
503 }
504 };
505
506 let mut instr = InstructionBuilder::new(op).condition(cond);
507
508 if sbit {
509 instr = instr.update()
510 }
511
512 while let Some(a) = textitem.next() {
513 if let Some(arg) = Argument::parse(a) {
514 instr = instr.argument(arg);
515 } else {
516 return Err(AssemblerError::new(
517 Some(linenum),
518 AssemErrorKind::InvalidArgument(a.into()),
519 ));
520 }
521 }
522
523 if matches!(op, OpCode::Str | OpCode::Stb) {
525 instr.args.reverse();
526 }
527
528 self.add(TextItem::new(TextItemKind::Instr(instr), address, linenum));
529 }
530 }
531
532 Ok(())
533 }
534
535 pub(crate) fn resolve_symbols(&mut self) -> Result<(), AssemblerError> {
536 for (symbol, value) in self.symbols.clone() {
537 for textitem in self.as_mut_text_items() {
538 let mut symbol = symbol.clone();
539 let mut value = value.clone();
540 match textitem.kind {
541 TextItemKind::Instr(ref mut i) => {
542 match i {
543 InstructionBuilder {
544 opcode: OpCode::Br, ..
545 } => {
546 value.apply(|v| {
548 let newv = (*v - textitem.address as isize) / 2 - 2;
549 *v = newv;
550 });
551 }
552
553 InstructionBuilder {
554 opcode: OpCode::Mov,
555 args: a,
556 ..
557 } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
558 let [_, Argument::Label(l)] = a.as_slice() else {
559 unreachable!()
560 };
561
562 if l.starts_with('=') {
563 symbol = format!("={}", symbol);
564 value.apply(|v| {
565 *v = ((*v as u16) & 0xff) as isize;
566 })
567 }
568 }
569
570 InstructionBuilder {
571 opcode: OpCode::Movt,
572 args: a,
573 ..
574 } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
575 let [_, Argument::Label(l)] = a.as_slice() else {
576 unreachable!()
577 };
578
579 if l.starts_with('=') {
580 symbol = format!("={}", symbol);
581 value.apply(|v| {
582 *v = ((*v as u16) >> 8) as isize;
583 })
584 }
585 }
586
587 _ => {}
588 }
589
590 i.replace(&symbol, value);
591 }
592 _ => {}
593 }
594 }
595 }
596
597 Ok(())
598 }
599
600 pub(crate) fn encode(self) -> Result<Vec<u8>, AssemblerError> {
602 let mut program = vec![];
603
604 if self.format == BinFormat::Elf {
605 return Err(AssemblerError::new(
606 None,
607 AssemErrorKind::ElfNotYetSupported,
608 ));
609 }
610
611 let mut sections: Vec<TextSection> = self
613 .sections
614 .into_iter()
615 .filter(|s| !s.items.is_empty())
616 .collect();
617
618 sections.sort_by(|a, b| a.items[0].address.cmp(&b.items[0].address));
619
620 let mut progcounter = 0x000000;
622 for section in sections {
623 let numzeroes = section.items[0].address - progcounter;
624
625 for _ in 0..numzeroes {
626 program.push(0x00);
627 }
628
629 progcounter += numzeroes;
630
631 for instr in section.items {
632 match instr.kind {
633 TextItemKind::Instr(i) => {
634 if progcounter % 2 != 0 {
635 return Err(AssemblerError::new(
636 Some(instr.line),
637 AssemErrorKind::UnalignedInstruction,
638 ));
639 }
640
641 let built = match i.build() {
643 Ok(b) => b,
644 Err(e) => {
645 return Err(AssemblerError::new(
646 Some(instr.line),
647 AssemErrorKind::InvalidInstruction(e),
648 ))
649 }
650 };
651
652 if !built.executable(section.mode) {
653 return Err(AssemblerError::new(
654 Some(instr.line),
655 AssemErrorKind::NonExecableInstr,
656 ));
657 }
658
659 let [first, second] = built.encode().to_le_bytes();
660 program.push(first);
661 program.push(second);
662
663 progcounter += 2;
664 }
665
666 TextItemKind::Dir(Directive::Word(w)) => {
667 let [first, second] = w.to_le_bytes();
668 program.push(first);
669 program.push(second);
670
671 progcounter += 2;
672 }
673
674 TextItemKind::Dir(Directive::Space(s)) => {
675 for _ in 0..s {
676 program.push(0x00);
677 }
678
679 progcounter += s;
680 }
681
682 TextItemKind::String(s) => {
683 let strsize = s.len();
685 if !s.is_ascii() {
686 return Err(AssemblerError::new(
687 Some(instr.line),
688 AssemErrorKind::StringNotAscii,
689 ));
690 }
691
692 let encoding = s.into_bytes();
693
694 for c in encoding {
695 program.push(c);
696 }
697
698 program.push(0x00);
699 progcounter += strsize + 1;
700 }
701
702 _ => {}
703 }
704 }
705 }
706
707 Ok(program)
708 }
709}