Skip to main content

cfd16_assembler/
parse.rs

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/// Format in which the assembled format should be encoded.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum BinFormat {
35    /// Format which can be linked with libraries, used as
36    /// a shared object, but cannot be executed directly by
37    /// a processor (needs to be loaded by the OS.)
38    Elf,
39
40    /// Format which contains no extra information about
41    /// the program or how to link it. Just raw machine code.
42    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(
105        source: String,
106        format: BinFormat,
107        file: String,
108    ) -> Result<Self, AssemblerError> {
109        let source = Program::preprocess(source, file.clone())?;
110        let mut prog = Program::new(format);
111
112        prog.parse(&source, file)?;
113
114        Ok(prog)
115    }
116
117    pub(crate) fn new(format: BinFormat) -> Self {
118        Self {
119            format,
120            sections: vec![],
121            symbols: HashMap::new(),
122        }
123    }
124
125    fn as_mut_text_items(&mut self) -> Vec<&mut TextItem> {
126        self.sections
127            .iter_mut()
128            .map(|s| s.items.iter_mut())
129            .flatten()
130            .collect()
131    }
132
133    pub(crate) fn add(&mut self, item: TextItem) {
134        match self.sections.iter_mut().last() {
135            Some(ref mut s) => s.items.push(item),
136            None => {
137                let mut s = TextSection::new(Mode::User, SecKind::Text);
138                s.items.push(item);
139                self.sections.push(s)
140            }
141        }
142    }
143
144    pub(crate) fn advance(&mut self, mode: Mode, kind: SecKind) {
145        self.sections.push(TextSection::new(mode, kind));
146    }
147
148    pub(crate) fn preprocess(source: String, file: String) -> Result<String, AssemblerError> {
149        let mut last_label: Option<String> = None;
150        let mut mappings: Vec<(String, String, String)> = vec![];
151
152        // First pass: Resolve Dotted Labels
153        for (n, line) in source.lines().enumerate() {
154            if line.contains(':') {
155                let split: Vec<&str> = line.split(':').collect();
156
157                let mut label = String::from(split[0]);
158
159                match (label.starts_with('.'), last_label.as_ref()) {
160                    (true, None) => {
161                        let loc = Location::new(file, n);
162                        return Err(AssemblerError::new(
163                            Some(loc),
164                            AssemErrorKind::NoLabelBeforeDotLabel(label),
165                        ));
166                    }
167
168                    (true, Some(l)) => {
169                        let prev = label.clone();
170                        label = format!("{}{}", l.clone(), label);
171                        mappings.push((l.clone(), prev, label.clone()));
172                    }
173                    _ => {
174                        last_label = Some(label.clone());
175                    }
176                }
177            }
178        }
179
180        let mut output = String::new();
181        let mut last_label: Option<&str> = None;
182
183        // Second pass: Replace labels in arguments and remove comments
184        for line in source.lines() {
185            let mut line = line;
186
187            if line.contains(';') {
188                line = line.split(';').nth(0).unwrap();
189            }
190
191            if line.contains(':') {
192                if let Some(label) = line.split(':').next() {
193                    if !label.starts_with('.') {
194                        last_label = Some(label);
195                    }
196                }
197            }
198
199            let mut line = String::from(line);
200
201            for (parent, needle, replacement) in &mappings {
202                if last_label != Some(parent) {
203                    break;
204                }
205
206                line = line.replace(needle, replacement);
207            }
208
209            output = format!("{output}{line}\n")
210        }
211
212        Ok(output)
213    }
214
215    pub(crate) fn rebase(&mut self, address: usize) -> usize {
216        let mut output = 0;
217        for section in &mut self.sections {
218            for textitem in &mut section.items {
219                let newaddr = textitem.address + address;
220                if newaddr > output {
221                    output = newaddr;
222                }
223                textitem.address += address;
224            }
225        }
226
227        let _ = self.symbols.values_mut().map(|v| match v {
228            Argument::Imm(i) => *i += address as isize,
229            _ => {}
230        });
231
232        output
233    }
234
235    pub(crate) fn consume(&mut self, other: Program) {
236        // Consume textitems from the other
237        match other.sections.len() {
238            0 => {}
239
240            1 => {
241                let latest = self.sections.iter_mut().last().unwrap();
242
243                latest
244                    .items
245                    .extend_from_slice(other.sections[0].items.as_slice());
246            }
247
248            _ => self.sections.extend_from_slice(other.sections.as_slice()),
249        }
250
251        // Consume symbols from the other
252        for (k, v) in other.symbols.iter() {
253            self.symbols.insert(k.clone(), v.clone());
254        }
255    }
256
257    pub(crate) fn parse(&mut self, source: &str, file: String) -> Result<(), AssemblerError> {
258        let mut address = 0;
259
260        for (i, line) in source.lines().enumerate() {
261            let loc = Location::new(file.clone(), i);
262            self.parse_line(&mut address, line, loc)?;
263        }
264
265        Ok(())
266    }
267
268    fn parse_line(
269        &mut self,
270        address: &mut isize,
271        line: &str,
272        loc: Location,
273    ) -> Result<(), AssemblerError> {
274        let mut line = line;
275
276        // We have some sort of label here, which we want to strip off and
277        // store in `self.symbols` before moving onto the instr/directive
278        // if it exists.
279        if line.contains(':') {
280            let mut splitline = line.split(':');
281            let label = match splitline.next() {
282                Some(l) => l,
283                None => return Err(AssemblerError::new(Some(loc), AssemErrorKind::InvalidLabel)),
284            };
285
286            self.symbols
287                .insert(label.trim().into(), Argument::Imm(*address & 0xffff));
288
289            let instr_left = splitline.collect::<Vec<&str>>();
290            if instr_left.len() > 1 {
291                return Err(AssemblerError::new(Some(loc), AssemErrorKind::InvalidLabel));
292            }
293
294            line = instr_left[0];
295        }
296
297        // Remove 'meaningless' tokens while preserving argument separation.
298        let line = line.replace(",", " ").replace("(", " ").replace(")", " ");
299
300        let mut textitem = line
301            .split(';')
302            .nth(0)
303            .expect("Shouldn't happen") // TODO: Change and handle if necessary
304            .split(' ')
305            .filter(|s| !s.is_empty())
306            .peekable();
307
308        if let Some(mnem) = textitem.next() {
309            if mnem.starts_with('.') {
310                match mnem.to_lowercase().as_str() {
311                    ".space" => {
312                        let arg = match textitem.next() {
313                            Some(a) => a,
314                            None => {
315                                return Err(AssemblerError::new(
316                                    Some(loc),
317                                    AssemErrorKind::InvalidArgument(
318                                        "No argument provided to '.space'".into(),
319                                    ),
320                                ));
321                            }
322                        };
323
324                        let value = match Argument::parse_int(arg) {
325                            Ok(v) => v,
326                            Err(_) => {
327                                return Err(AssemblerError::new(
328                                    Some(loc),
329                                    AssemErrorKind::InvalidArgument("Could not parse argument provided to '.space' as an integer.".into()),
330                                ));
331                            }
332                        };
333
334                        self.add(TextItem::new(
335                            TextItemKind::Dir(Directive::Space(value as usize)),
336                            address,
337                            loc,
338                        ));
339                    }
340
341                    ".word" => {
342                        let arg = match textitem.next() {
343                            Some(a) => a,
344                            None => {
345                                return Err(AssemblerError::new(
346                                    Some(loc),
347                                    AssemErrorKind::InvalidArgument(
348                                        "No argument provided to '.word'".into(),
349                                    ),
350                                ));
351                            }
352                        };
353
354                        let value = match Argument::parse_int(arg) {
355                            Ok(v) => v,
356                            Err(_) => {
357                                return Err(AssemblerError::new(
358                                    Some(loc),
359                                    AssemErrorKind::InvalidArgument("Could not parse argument provided to '.word' as an integer.".into()),
360                                ));
361                            }
362                        };
363
364                        self.add(TextItem::new(
365                            TextItemKind::Dir(Directive::Word(value as u16)),
366                            address,
367                            loc,
368                        ));
369                    }
370
371                    ".org" => {
372                        let arg = match textitem.next() {
373                            Some(a) => a,
374                            None => {
375                                return Err(AssemblerError::new(
376                                    Some(loc),
377                                    AssemErrorKind::InvalidArgument(
378                                        "No argument provided to '.word'".into(),
379                                    ),
380                                ));
381                            }
382                        };
383
384                        let value = match Argument::parse_int(arg) {
385                            Ok(v) => v,
386                            Err(_) => {
387                                return Err(AssemblerError::new(
388                                    Some(loc),
389                                    AssemErrorKind::InvalidArgument("Could not parse argument provided to '.word' as an integer.".into()),
390                                ));
391                            }
392                        };
393
394                        *address = value
395                    }
396
397                    ".global" => {
398                        self.add(TextItem::new(
399                            TextItemKind::Dir(Directive::Global(textitem.next().unwrap().into())),
400                            address,
401                            loc,
402                        ));
403                    }
404
405                    ".extern" => {
406                        self.add(TextItem::new(
407                            TextItemKind::Dir(Directive::Extern(textitem.next().unwrap().into())),
408                            address,
409                            loc,
410                        ));
411                    }
412
413                    ".kernel.text" => self.advance(Mode::Kernel, SecKind::Text),
414                    ".kernel.data" => self.advance(Mode::Kernel, SecKind::Data),
415                    ".user.text" | ".text" => self.advance(Mode::User, SecKind::Text),
416                    ".user.data" | ".data" => self.advance(Mode::User, SecKind::Data),
417
418                    ".equ" => {
419                        let symbol = textitem.next().unwrap();
420                        let value = match Argument::parse(textitem.next().unwrap()) {
421                            Some(v) => v,
422                            None => {
423                                return Err(AssemblerError::new(
424                                    Some(loc),
425                                    AssemErrorKind::InvalidArgument(
426                                        "'.equ' should be provided with a valid second argument."
427                                            .into(),
428                                    ),
429                                ));
430                            }
431                        };
432
433                        // NOTE: Ensure no definitions are dotted so that preprocessing
434                        //       for un-dotting symbols works.
435                        if symbol.starts_with('.') {
436                            return Err(AssemblerError::new(
437                                Some(loc),
438                                AssemErrorKind::InvalidLabel,
439                            ));
440                        }
441
442                        self.symbols.insert(symbol.into(), value);
443                    }
444
445                    ".mov" => {
446                        let regval = textitem.next().unwrap();
447                        let register = Argument::parse(regval);
448
449                        if let Some(Argument::Reg(_)) = register {
450                        } else {
451                            return Err(AssemblerError::new(
452                                Some(loc),
453                                AssemErrorKind::InvalidArgument(regval.into()),
454                            ));
455                        }
456
457                        let value = match Argument::parse(textitem.next().unwrap()) {
458                            Some(Argument::Imm(i)) => {
459                                let [top, bottom] = (i as u16).to_be_bytes();
460                                (Argument::Imm(bottom as isize), Argument::Imm(top as isize))
461                            }
462
463                            Some(Argument::Label(l)) => {
464                                let prefixed = format!("={}", l);
465                                (Argument::Label(prefixed.clone()), Argument::Label(prefixed))
466                            }
467
468                            _ => todo!(),
469                        };
470
471                        self.add(TextItem::new(
472                            TextItemKind::Instr(
473                                InstructionBuilder::new(OpCode::Mov)
474                                    .argument(register.as_ref().unwrap().clone())
475                                    .argument(value.0),
476                            ),
477                            address,
478                            loc.clone(),
479                        ));
480
481                        self.add(TextItem::new(
482                            TextItemKind::Instr(
483                                InstructionBuilder::new(OpCode::Movt)
484                                    .argument(register.as_ref().unwrap().clone())
485                                    .argument(value.1),
486                            ),
487                            address,
488                            loc,
489                        ));
490                    }
491
492                    ".nop" => {
493                        self.add(TextItem::new(
494                            TextItemKind::Instr(InstructionBuilder::default()),
495                            address,
496                            loc,
497                        ));
498                    }
499
500                    ".ascii" => {
501                        let value = parse_string(&mut textitem);
502                        self.add(TextItem::new(TextItemKind::String(value), address, loc));
503                    }
504
505                    ".include" => {
506                        let value = parse_string(&mut textitem);
507
508                        let source = match fs::read_to_string(&value) {
509                            Ok(s) => s,
510                            Err(_) => {
511                                return Err(AssemblerError::new(
512                                    Some(loc),
513                                    AssemErrorKind::IncludePathInvalid,
514                                ))
515                            }
516                        };
517
518                        let mut subprog = match Program::from_source(source, self.format, value) {
519                            Ok(t) => t,
520                            Err(e) => return Err(AssemblerError::included(Some(loc), e)),
521                        };
522
523                        let newaddr = subprog.rebase(*address as usize);
524                        *address = newaddr as isize + 2;
525
526                        self.consume(subprog);
527                    }
528
529                    _ => {
530                        return Err(AssemblerError::new(
531                            Some(loc),
532                            AssemErrorKind::InvalidMnemonic(mnem.into()),
533                        ))
534                    }
535                }
536            } else {
537                let (op, sbit, cond) = match OpCode::parse(mnem) {
538                    Some(t) => t,
539                    None => {
540                        return Err(AssemblerError::new(
541                            Some(loc),
542                            AssemErrorKind::InvalidMnemonic(mnem.into()),
543                        ))
544                    }
545                };
546
547                let mut instr = InstructionBuilder::new(op).condition(cond);
548
549                if sbit {
550                    instr = instr.update()
551                }
552
553                while let Some(a) = textitem.next() {
554                    if let Some(arg) = Argument::parse(a) {
555                        instr = instr.argument(arg);
556                    } else {
557                        return Err(AssemblerError::new(
558                            Some(loc),
559                            AssemErrorKind::InvalidArgument(a.into()),
560                        ));
561                    }
562                }
563
564                // Stores have regd after regs
565                if matches!(op, OpCode::Str | OpCode::Stb) {
566                    instr.args.reverse();
567                }
568
569                self.add(TextItem::new(TextItemKind::Instr(instr), address, loc));
570            }
571        }
572
573        Ok(())
574    }
575
576    pub(crate) fn resolve_symbols(&mut self) -> Result<(), AssemblerError> {
577        for (symbol, value) in self.symbols.clone() {
578            for textitem in self.as_mut_text_items() {
579                let mut symbol = symbol.clone();
580                let mut value = value.clone();
581                match textitem.kind {
582                    TextItemKind::Instr(ref mut i) => {
583                        match i {
584                            InstructionBuilder {
585                                opcode: OpCode::Br, ..
586                            } => {
587                                // IP is 4 ahead when executing an instruction
588                                value.apply(|v| {
589                                    let newv = (*v - textitem.address as isize) / 2 - 2;
590                                    *v = newv;
591                                });
592                            }
593
594                            InstructionBuilder {
595                                opcode: OpCode::Mov,
596                                args: a,
597                                ..
598                            } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
599                                let [_, Argument::Label(l)] = a.as_slice() else {
600                                    unreachable!()
601                                };
602
603                                if l.starts_with('=') {
604                                    symbol = format!("={}", symbol);
605                                    value.apply(|v| {
606                                        *v = ((*v as u16) & 0xff) as isize;
607                                    })
608                                }
609                            }
610
611                            InstructionBuilder {
612                                opcode: OpCode::Movt,
613                                args: a,
614                                ..
615                            } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
616                                let [_, Argument::Label(l)] = a.as_slice() else {
617                                    unreachable!()
618                                };
619
620                                if l.starts_with('=') {
621                                    symbol = format!("={}", symbol);
622                                    value.apply(|v| {
623                                        *v = ((*v as u16) >> 8) as isize;
624                                    })
625                                }
626                            }
627
628                            _ => {}
629                        }
630
631                        i.replace(&symbol, value);
632                    }
633                    _ => {}
634                }
635            }
636        }
637
638        Ok(())
639    }
640
641    // TODO: Add ELF support.
642    pub(crate) fn encode(self) -> Result<Vec<u8>, AssemblerError> {
643        let mut program = vec![];
644
645        if self.format == BinFormat::Elf {
646            return Err(AssemblerError::new(
647                None,
648                AssemErrorKind::ElfNotYetSupported,
649            ));
650        }
651
652        // Prune empty sections and sort by address.
653        let mut sections: Vec<TextSection> = self
654            .sections
655            .into_iter()
656            .filter(|s| !s.items.is_empty())
657            .collect();
658
659        sections.sort_by(|a, b| a.items[0].address.cmp(&b.items[0].address));
660
661        // Emit in order each section and pad with zeroes between.
662        let mut progcounter = 0x000000;
663        for section in sections {
664            let numzeroes = section.items[0].address - progcounter;
665
666            for _ in 0..numzeroes {
667                program.push(0x00);
668            }
669
670            progcounter += numzeroes;
671
672            for instr in section.items {
673                match instr.kind {
674                    TextItemKind::Instr(i) => {
675                        if progcounter % 2 != 0 {
676                            return Err(AssemblerError::new(
677                                Some(instr.loc),
678                                AssemErrorKind::UnalignedInstruction,
679                            ));
680                        }
681
682                        // TODO: Check alignment and error if instrs are mis-aligned.
683                        let built = match i.build() {
684                            Ok(b) => b,
685                            Err(e) => {
686                                return Err(AssemblerError::new(
687                                    Some(instr.loc),
688                                    AssemErrorKind::InvalidInstruction(e),
689                                ))
690                            }
691                        };
692
693                        if !built.executable(section.mode) {
694                            return Err(AssemblerError::new(
695                                Some(instr.loc),
696                                AssemErrorKind::NonExecableInstr,
697                            ));
698                        }
699
700                        let [first, second] = built.encode().to_le_bytes();
701                        program.push(first);
702                        program.push(second);
703
704                        progcounter += 2;
705                    }
706
707                    TextItemKind::Dir(Directive::Word(w)) => {
708                        let [first, second] = w.to_le_bytes();
709                        program.push(first);
710                        program.push(second);
711
712                        progcounter += 2;
713                    }
714
715                    TextItemKind::Dir(Directive::Space(s)) => {
716                        for _ in 0..s {
717                            program.push(0x00);
718                        }
719
720                        progcounter += s;
721                    }
722
723                    TextItemKind::String(s) => {
724                        // TODO: Encode ascii and then emit with a final zero byte
725                        let strsize = s.len();
726                        if !s.is_ascii() {
727                            return Err(AssemblerError::new(
728                                Some(instr.loc),
729                                AssemErrorKind::StringNotAscii,
730                            ));
731                        }
732
733                        let encoding = s.into_bytes();
734
735                        for c in encoding {
736                            program.push(c);
737                        }
738
739                        program.push(0x00);
740                        progcounter += strsize + 1;
741                    }
742
743                    _ => {}
744                }
745            }
746        }
747
748        Ok(program)
749    }
750}