cfd16-assembler 0.7.1

An assembler backend for the CFD-16 ISA.
Documentation
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
use std::{collections::HashMap, default, fmt, str};

use cfd16_lib::prelude::*;

use crate::error::{AssemErrorKind, AssemblerError};
use crate::text::*;

type SymbolTable = HashMap<String, Argument>;

/// Format in which the assembled format should be encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinFormat {
    /// Format which can be linked with libraries, used as
    /// a shared object, but cannot be executed directly by
    /// a processor (needs to be loaded by the OS.)
    Elf,

    /// Format which contains no extra information about
    /// the program or how to link it. Just raw machine code.
    Raw,
}

impl default::Default for BinFormat {
    fn default() -> Self {
        Self::Raw
    }
}

impl fmt::Display for BinFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BinFormat::Elf => write!(f, "elf"),
            BinFormat::Raw => write!(f, "bin"),
        }
    }
}

impl str::FromStr for BinFormat {
    type Err = AssemblerError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "bin" => Ok(BinFormat::Raw),
            "elf" => Ok(BinFormat::Elf),
            _ => Err(AssemblerError::new(
                None,
                AssemErrorKind::NoSuchBinaryFormat,
            )),
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct Program {
    format: BinFormat,
    sections: Vec<TextSection>,
    symbols: SymbolTable,
}

impl fmt::Display for Program {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut output = String::new();
        let mut symbols = String::new();

        for section in &self.sections {
            output = format!("{output}\n{section}");
        }

        for (symbol, argument) in &self.symbols {
            symbols = format!("{}\t{} => {}\n", symbols, symbol, argument);
        }

        write!(
            f,
            "Instrs:\n{}\n\nFormat: {}\n\nSymbols:\n{}",
            output, self.format, symbols
        )
    }
}

impl Program {
    pub(crate) fn new(format: BinFormat) -> Self {
        Self {
            format,
            sections: vec![],
            symbols: HashMap::new(),
        }
    }

    fn as_mut_text_items(&mut self) -> Vec<&mut TextItem> {
        self.sections
            .iter_mut()
            .map(|s| s.items.iter_mut())
            .flatten()
            .collect()
    }

    pub(crate) fn add(&mut self, item: TextItem) {
        match self.sections.iter_mut().last() {
            Some(ref mut s) => s.items.push(item),
            None => {
                let mut s = TextSection::new(Mode::User, SecKind::Text);
                s.items.push(item);
                self.sections.push(s)
            }
        }
    }

    pub(crate) fn advance(&mut self, mode: Mode, kind: SecKind) {
        self.sections.push(TextSection::new(mode, kind));
    }

    pub(crate) fn preprocess(source: String) -> Result<String, AssemblerError> {
        let mut last_label: Option<String> = None;
        let mut mappings: Vec<(String, String, String)> = vec![];

        // First pass: Resolve Dotted Labels
        for (n, line) in source.lines().enumerate() {
            if line.contains(':') {
                let split: Vec<&str> = line.split(':').collect();

                let mut label = String::from(split[0]);

                match (label.starts_with('.'), last_label.as_ref()) {
                    (true, None) => {
                        return Err(AssemblerError::new(
                            Some(n),
                            AssemErrorKind::NoLabelBeforeDotLabel(label),
                        ));
                    }

                    (true, Some(l)) => {
                        let prev = label.clone();
                        label = format!("{}{}", l.clone(), label);
                        mappings.push((l.clone(), prev, label.clone()));
                    }
                    _ => {
                        last_label = Some(label.clone());
                    }
                }
            }
        }

        let mut output = String::new();
        let mut last_label: Option<&str> = None;

        // Second pass: Replace labels in arguments
        for line in source.lines() {
            if line.contains(':') {
                if let Some(label) = line.split(':').next() {
                    if !label.starts_with('.') {
                        last_label = Some(label);
                    }
                }
            }

            let mut line = String::from(line);

            for (parent, needle, replacement) in &mappings {
                if last_label != Some(parent) {
                    break;
                }

                line = line.replace(needle, replacement);
            }

            output = format!("{output}{line}\n")
        }

        Ok(output)
    }

    pub(crate) fn parse(&mut self, source: &str) -> Result<(), AssemblerError> {
        let mut address = 0;

        for (i, line) in source.lines().enumerate() {
            self.parse_line(&mut address, (i, line))?;
        }

        Ok(())
    }

    fn parse_line(
        &mut self,
        address: &mut isize,
        line: (usize, &str),
    ) -> Result<(), AssemblerError> {
        let (linenum, mut line) = line;

        // We have some sort of label here, which we want to strip off and
        // store in `self.symbols` before moving onto the instr/directive
        // if it exists.
        if line.contains(':') {
            let mut splitline = line.split(':');
            let label = match splitline.next() {
                Some(l) => l,
                None => {
                    return Err(AssemblerError::new(
                        Some(linenum),
                        AssemErrorKind::InvalidLabel,
                    ))
                }
            };

            self.symbols
                .insert(label.trim().into(), Argument::Imm(*address & 0xffff));

            let instr_left = splitline.collect::<Vec<&str>>();
            if instr_left.len() > 1 {
                return Err(AssemblerError::new(
                    Some(linenum),
                    AssemErrorKind::InvalidLabel,
                ));
            }

            line = instr_left[0];
        }

        // Remove 'meaningless' tokens while preserving argument separation.
        let line = line.replace(",", " ").replace("(", " ").replace(")", " ");

        let mut textitem = line
            .split(';')
            .nth(0)
            .expect("Shouldn't happen") // TODO: Change and handle if necessary
            .split(' ')
            .filter(|s| !s.is_empty())
            .peekable();

        if let Some(mnem) = textitem.next() {
            if mnem.starts_with('.') {
                match mnem.to_lowercase().as_str() {
                    ".space" => {
                        let arg = match textitem.next() {
                            Some(a) => a,
                            None => {
                                return Err(AssemblerError::new(
                                    Some(linenum),
                                    AssemErrorKind::InvalidArgument(
                                        "No argument provided to '.space'".into(),
                                    ),
                                ));
                            }
                        };

                        let value = match Argument::parse_int(arg) {
                            Ok(v) => v,
                            Err(_) => {
                                return Err(AssemblerError::new(
                                    Some(linenum),
                                    AssemErrorKind::InvalidArgument("Could not parse argument provided to '.space' as an integer.".into()),
                                ));
                            }
                        };

                        self.add(TextItem::new(
                            TextItemKind::Dir(Directive::Space(value as usize)),
                            address,
                            linenum,
                        ));
                    }

                    ".word" => {
                        let arg = match textitem.next() {
                            Some(a) => a,
                            None => {
                                return Err(AssemblerError::new(
                                    Some(linenum),
                                    AssemErrorKind::InvalidArgument(
                                        "No argument provided to '.word'".into(),
                                    ),
                                ));
                            }
                        };

                        let value = match Argument::parse_int(arg) {
                            Ok(v) => v,
                            Err(_) => {
                                return Err(AssemblerError::new(
                                    Some(linenum),
                                    AssemErrorKind::InvalidArgument("Could not parse argument provided to '.word' as an integer.".into()),
                                ));
                            }
                        };

                        self.add(TextItem::new(
                            TextItemKind::Dir(Directive::Word(value as u16)),
                            address,
                            linenum,
                        ));
                    }

                    ".org" => {
                        let arg = match textitem.next() {
                            Some(a) => a,
                            None => {
                                return Err(AssemblerError::new(
                                    Some(linenum),
                                    AssemErrorKind::InvalidArgument(
                                        "No argument provided to '.word'".into(),
                                    ),
                                ));
                            }
                        };

                        let value = match Argument::parse_int(arg) {
                            Ok(v) => v,
                            Err(_) => {
                                return Err(AssemblerError::new(
                                    Some(linenum),
                                    AssemErrorKind::InvalidArgument("Could not parse argument provided to '.word' as an integer.".into()),
                                ));
                            }
                        };

                        *address = value
                    }

                    ".global" => {
                        self.add(TextItem::new(
                            TextItemKind::Dir(Directive::Global(textitem.next().unwrap().into())),
                            address,
                            linenum,
                        ));
                    }

                    ".extern" => {
                        self.add(TextItem::new(
                            TextItemKind::Dir(Directive::Extern(textitem.next().unwrap().into())),
                            address,
                            linenum,
                        ));
                    }

                    ".kernel.text" => self.advance(Mode::Kernel, SecKind::Text),
                    ".kernel.data" => self.advance(Mode::Kernel, SecKind::Data),
                    ".user.text" | ".text" => self.advance(Mode::User, SecKind::Text),
                    ".user.data" | ".data" => self.advance(Mode::User, SecKind::Data),

                    ".equ" => {
                        let symbol = textitem.next().unwrap();
                        let value = match Argument::parse(textitem.next().unwrap()) {
                            Some(v) => v,
                            None => {
                                return Err(AssemblerError::new(
                                    Some(linenum),
                                    AssemErrorKind::InvalidArgument(
                                        "'.equ' should be provided with a valid second argument."
                                            .into(),
                                    ),
                                ));
                            }
                        };

                        // NOTE: Ensure no definitions are dotted so that preprocessing
                        //       for un-dotting symbols works.
                        if symbol.starts_with('.') {
                            return Err(AssemblerError::new(
                                Some(linenum),
                                AssemErrorKind::InvalidLabel,
                            ));
                        }

                        self.symbols.insert(symbol.into(), value);
                    }

                    ".mov" => {
                        let regval = textitem.next().unwrap();
                        let register = Argument::parse(regval);

                        if let Some(Argument::Reg(_)) = register {
                        } else {
                            return Err(AssemblerError::new(
                                Some(linenum),
                                AssemErrorKind::InvalidArgument(regval.into()),
                            ));
                        }

                        let value = match Argument::parse(textitem.next().unwrap()) {
                            Some(Argument::Imm(i)) => {
                                let [top, bottom] = (i as u16).to_be_bytes();
                                (Argument::Imm(bottom as isize), Argument::Imm(top as isize))
                            }

                            Some(Argument::Label(l)) => {
                                let prefixed = format!("={}", l);
                                (Argument::Label(prefixed.clone()), Argument::Label(prefixed))
                            }

                            _ => todo!(),
                        };

                        self.add(TextItem::new(
                            TextItemKind::Instr(
                                InstructionBuilder::new(OpCode::Mov)
                                    .argument(register.as_ref().unwrap().clone())
                                    .argument(value.0),
                            ),
                            address,
                            linenum,
                        ));

                        self.add(TextItem::new(
                            TextItemKind::Instr(
                                InstructionBuilder::new(OpCode::Movt)
                                    .argument(register.as_ref().unwrap().clone())
                                    .argument(value.1),
                            ),
                            address,
                            linenum,
                        ));
                    }

                    ".nop" => {
                        self.add(TextItem::new(
                            TextItemKind::Instr(InstructionBuilder::default()),
                            address,
                            linenum,
                        ));
                    }

                    ".ascii" => {
                        let mut value;

                        let mut arg = match textitem.next() {
                            Some(a) if a.starts_with('"') => a,
                            _ => panic!("arg must be str"),
                        };

                        value = arg.replace('"', "");

                        while !arg.ends_with('"') {
                            arg = match textitem.next() {
                                Some(a) => a,
                                _ => panic!("arg must be str"),
                            };

                            value = format!("{value} {}", arg.replace('"', ""))
                        }

                        self.add(TextItem::new(TextItemKind::String(value), address, linenum));
                    }

                    _ => {
                        return Err(AssemblerError::new(
                            Some(linenum),
                            AssemErrorKind::InvalidMnemonic(mnem.into()),
                        ))
                    }
                }
            } else {
                let (op, sbit, cond) = match OpCode::parse(mnem) {
                    Some(t) => t,
                    None => {
                        return Err(AssemblerError::new(
                            Some(linenum),
                            AssemErrorKind::InvalidMnemonic(mnem.into()),
                        ))
                    }
                };

                let mut instr = InstructionBuilder::new(op).condition(cond);

                if sbit {
                    instr = instr.update()
                }

                while let Some(a) = textitem.next() {
                    if let Some(arg) = Argument::parse(a) {
                        instr = instr.argument(arg);
                    } else {
                        return Err(AssemblerError::new(
                            Some(linenum),
                            AssemErrorKind::InvalidArgument(a.into()),
                        ));
                    }
                }

                // Stores have regd after regs
                if matches!(op, OpCode::Str | OpCode::Stb) {
                    instr.args.reverse();
                }

                self.add(TextItem::new(TextItemKind::Instr(instr), address, linenum));
            }
        }

        Ok(())
    }

    pub(crate) fn resolve_symbols(&mut self) -> Result<(), AssemblerError> {
        for (symbol, value) in self.symbols.clone() {
            for textitem in self.as_mut_text_items() {
                let mut symbol = symbol.clone();
                let mut value = value.clone();
                match textitem.kind {
                    TextItemKind::Instr(ref mut i) => {
                        match i {
                            InstructionBuilder {
                                opcode: OpCode::Br, ..
                            } => {
                                // IP is 4 ahead when executing an instruction
                                value.apply(|v| {
                                    let newv = (*v - textitem.address as isize) / 2 - 2;
                                    *v = newv;
                                });
                            }

                            InstructionBuilder {
                                opcode: OpCode::Mov,
                                args: a,
                                ..
                            } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
                                let [_, Argument::Label(l)] = a.as_slice() else {
                                    unreachable!()
                                };

                                if l.starts_with('=') {
                                    symbol = format!("={}", symbol);
                                    value.apply(|v| {
                                        *v = ((*v as u16) & 0xff) as isize;
                                    })
                                }
                            }

                            InstructionBuilder {
                                opcode: OpCode::Movt,
                                args: a,
                                ..
                            } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
                                let [_, Argument::Label(l)] = a.as_slice() else {
                                    unreachable!()
                                };

                                if l.starts_with('=') {
                                    symbol = format!("={}", symbol);
                                    value.apply(|v| {
                                        *v = ((*v as u16) >> 8) as isize;
                                    })
                                }
                            }

                            _ => {}
                        }

                        i.replace(&symbol, value);
                    }
                    _ => {}
                }
            }
        }

        Ok(())
    }

    // TODO: Add ELF support.
    pub(crate) fn encode(self) -> Result<Vec<u8>, AssemblerError> {
        let mut program = vec![];

        if self.format == BinFormat::Elf {
            return Err(AssemblerError::new(
                None,
                AssemErrorKind::ElfNotYetSupported,
            ));
        }

        // Prune empty sections and sort by address.
        let mut sections: Vec<TextSection> = self
            .sections
            .into_iter()
            .filter(|s| !s.items.is_empty())
            .collect();

        sections.sort_by(|a, b| a.items[0].address.cmp(&b.items[0].address));

        // Emit in order each section and pad with zeroes between.
        let mut progcounter = 0x000000;
        for section in sections {
            let numzeroes = section.items[0].address - progcounter;

            for _ in 0..numzeroes {
                program.push(0x00);
            }

            progcounter += numzeroes;

            for instr in section.items {
                match instr.kind {
                    TextItemKind::Instr(i) => {
                        if progcounter % 2 != 0 {
                            return Err(AssemblerError::new(
                                Some(instr.line),
                                AssemErrorKind::UnalignedInstruction,
                            ));
                        }

                        // TODO: Check alignment and error if instrs are mis-aligned.
                        let built = match i.build() {
                            Ok(b) => b,
                            Err(e) => {
                                return Err(AssemblerError::new(
                                    Some(instr.line),
                                    AssemErrorKind::InvalidInstruction(e),
                                ))
                            }
                        };

                        if !built.executable(section.mode) {
                            return Err(AssemblerError::new(
                                Some(instr.line),
                                AssemErrorKind::NonExecableInstr,
                            ));
                        }

                        let [first, second] = built.encode().to_le_bytes();
                        program.push(first);
                        program.push(second);

                        progcounter += 2;
                    }

                    TextItemKind::Dir(Directive::Word(w)) => {
                        let [first, second] = w.to_le_bytes();
                        program.push(first);
                        program.push(second);

                        progcounter += 2;
                    }

                    TextItemKind::Dir(Directive::Space(s)) => {
                        for _ in 0..s {
                            program.push(0x00);
                        }

                        progcounter += s;
                    }

                    TextItemKind::String(s) => {
                        // TODO: Encode ascii and then emit with a final zero byte
                        let strsize = s.len();
                        if !s.is_ascii() {
                            return Err(AssemblerError::new(
                                Some(instr.line),
                                AssemErrorKind::StringNotAscii,
                            ));
                        }

                        let encoding = s.into_bytes();

                        for c in encoding {
                            program.push(c);
                        }

                        program.push(0x00);
                        progcounter += strsize + 1;
                    }

                    _ => {}
                }
            }
        }

        Ok(program)
    }
}