cfd16_assembler/
parse.rs

1use std::{collections::HashMap, default, fmt, str};
2
3use cfd16_lib::prelude::*;
4
5use crate::error::{AssemErrorKind, AssemblerError};
6use crate::text::*;
7
8type SymbolTable = HashMap<String, Argument>;
9
10/// Format in which the assembled format should be encoded.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum BinFormat {
13    /// Format which can be linked with libraries, used as
14    /// a shared object, but cannot be executed directly by
15    /// a processor (needs to be loaded by the OS.)
16    Elf,
17
18    /// Format which contains no extra information about
19    /// the program or how to link it. Just raw machine code.
20    Raw,
21}
22
23impl default::Default for BinFormat {
24    fn default() -> Self {
25        Self::Raw
26    }
27}
28
29impl fmt::Display for BinFormat {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            BinFormat::Elf => write!(f, "elf"),
33            BinFormat::Raw => write!(f, "bin"),
34        }
35    }
36}
37
38impl str::FromStr for BinFormat {
39    type Err = AssemblerError;
40
41    fn from_str(s: &str) -> Result<Self, Self::Err> {
42        match s {
43            "bin" => Ok(BinFormat::Raw),
44            "elf" => Ok(BinFormat::Elf),
45            _ => Err(AssemblerError::new(
46                None,
47                AssemErrorKind::NoSuchBinaryFormat,
48            )),
49        }
50    }
51}
52
53#[derive(Debug, Clone)]
54pub(crate) struct Program {
55    format: BinFormat,
56    sections: Vec<TextSection>,
57    symbols: SymbolTable,
58}
59
60impl fmt::Display for Program {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        let mut output = String::new();
63        let mut symbols = String::new();
64
65        for section in &self.sections {
66            output = format!("{output}\n{section}");
67        }
68
69        for (symbol, argument) in &self.symbols {
70            symbols = format!("{}\t{} => {}\n", symbols, symbol, argument);
71        }
72
73        write!(
74            f,
75            "Instrs:\n{}\n\nFormat: {}\n\nSymbols:\n{}",
76            output, self.format, symbols
77        )
78    }
79}
80
81impl Program {
82    pub(crate) fn new(format: BinFormat) -> Self {
83        Self {
84            format,
85            sections: vec![],
86            symbols: HashMap::new(),
87        }
88    }
89
90    fn as_mut_text_items(&mut self) -> Vec<&mut TextItem> {
91        self.sections
92            .iter_mut()
93            .map(|s| s.items.iter_mut())
94            .flatten()
95            .collect()
96    }
97
98    pub(crate) fn add(&mut self, item: TextItem) {
99        match self.sections.iter_mut().last() {
100            Some(ref mut s) => s.items.push(item),
101            None => {
102                let mut s = TextSection::new(Mode::User, SecKind::Text);
103                s.items.push(item);
104                self.sections.push(s)
105            }
106        }
107    }
108
109    pub(crate) fn advance(&mut self, mode: Mode, kind: SecKind) {
110        self.sections.push(TextSection::new(mode, kind));
111    }
112
113    pub(crate) fn preprocess(source: String) -> Result<String, AssemblerError> {
114        let mut last_label: Option<String> = None;
115        let mut mappings: Vec<(String, String, String)> = vec![];
116
117        // First pass: Resolve Dotted Labels
118        for (n, line) in source.lines().enumerate() {
119            if line.contains(':') {
120                let split: Vec<&str> = line.split(':').collect();
121
122                let mut label = String::from(split[0]);
123
124                match (label.starts_with('.'), last_label.as_ref()) {
125                    (true, None) => {
126                        return Err(AssemblerError::new(
127                            Some(n),
128                            AssemErrorKind::NoLabelBeforeDotLabel(label),
129                        ));
130                    }
131
132                    (true, Some(l)) => {
133                        let prev = label.clone();
134                        label = format!("{}{}", l.clone(), label);
135                        mappings.push((l.clone(), prev, label.clone()));
136                    }
137                    _ => {
138                        last_label = Some(label.clone());
139                    }
140                }
141            }
142        }
143
144        let mut output = String::new();
145        let mut last_label: Option<&str> = None;
146
147        // Second pass: Replace labels in arguments
148        for line in source.lines() {
149            if line.contains(':') {
150                if let Some(label) = line.split(':').next() {
151                    if !label.starts_with('.') {
152                        last_label = Some(label);
153                    }
154                }
155            }
156
157            let mut line = String::from(line);
158
159            for (parent, needle, replacement) in &mappings {
160                if last_label != Some(parent) {
161                    break;
162                }
163
164                line = line.replace(needle, replacement);
165            }
166
167            output = format!("{output}{line}\n")
168        }
169
170        Ok(output)
171    }
172
173    pub(crate) fn parse(&mut self, source: &str) -> Result<(), AssemblerError> {
174        let mut address = 0;
175
176        for (i, line) in source.lines().enumerate() {
177            self.parse_line(&mut address, (i, line))?;
178        }
179
180        Ok(())
181    }
182
183    fn parse_line(
184        &mut self,
185        address: &mut isize,
186        line: (usize, &str),
187    ) -> Result<(), AssemblerError> {
188        let (linenum, mut line) = line;
189
190        // We have some sort of label here, which we want to strip off and
191        // store in `self.symbols` before moving onto the instr/directive
192        // if it exists.
193        if line.contains(':') {
194            let mut splitline = line.split(':');
195            let label = match splitline.next() {
196                Some(l) => l,
197                None => {
198                    return Err(AssemblerError::new(
199                        Some(linenum),
200                        AssemErrorKind::InvalidLabel,
201                    ))
202                }
203            };
204
205            self.symbols
206                .insert(label.trim().into(), Argument::Imm(*address));
207
208            let instr_left = splitline.collect::<Vec<&str>>();
209            if instr_left.len() > 1 {
210                return Err(AssemblerError::new(
211                    Some(linenum),
212                    AssemErrorKind::InvalidLabel,
213                ));
214            }
215
216            line = instr_left[0];
217        }
218
219        // Remove 'meaningless' tokens while preserving argument separation.
220        let line = line.replace(",", " ").replace("(", " ").replace(")", " ");
221
222        let mut textitem = line
223            .split(';')
224            .nth(0)
225            .expect("Shouldn't happen") // TODO: Change and handle if necessary
226            .split(' ')
227            .filter(|s| !s.is_empty())
228            .peekable();
229
230        if let Some(mnem) = textitem.next() {
231            if mnem.starts_with('.') {
232                match mnem.to_lowercase().as_str() {
233                    ".space" => {
234                        let value = textitem.next().unwrap().parse::<usize>().unwrap();
235
236                        self.add(TextItem::new(
237                            TextItemKind::Dir(Directive::Space(value)),
238                            address,
239                            linenum,
240                        ));
241                    }
242
243                    ".word" => {
244                        self.add(TextItem::new(
245                            TextItemKind::Dir(Directive::Word(
246                                textitem.next().unwrap().parse::<u16>().unwrap(),
247                            )),
248                            address,
249                            linenum,
250                        ));
251                    }
252
253                    ".global" => {
254                        self.add(TextItem::new(
255                            TextItemKind::Dir(Directive::Global(textitem.next().unwrap().into())),
256                            address,
257                            linenum,
258                        ));
259                    }
260
261                    ".extern" => {
262                        self.add(TextItem::new(
263                            TextItemKind::Dir(Directive::Extern(textitem.next().unwrap().into())),
264                            address,
265                            linenum,
266                        ));
267                    }
268
269                    ".kernel.text" => self.advance(Mode::Kernel, SecKind::Text),
270                    ".kernel.data" => self.advance(Mode::Kernel, SecKind::Data),
271                    ".user.text" | ".text" => self.advance(Mode::User, SecKind::Text),
272                    ".user.data" | ".data" => self.advance(Mode::User, SecKind::Data),
273
274                    ".equ" => {
275                        let symbol = textitem.next().unwrap();
276                        let value = match Argument::parse(textitem.next().unwrap()) {
277                            Some(v) => v,
278                            None => {
279                                return Err(AssemblerError::new(
280                                    Some(linenum),
281                                    AssemErrorKind::InvalidArgument(
282                                        "'.equ' should be provided with a valid second argument."
283                                            .into(),
284                                    ),
285                                ));
286                            }
287                        };
288
289                        // NOTE: Ensure no definitions are dotted so that preprocessing
290                        //       for un-dotting symbols works.
291                        if symbol.starts_with('.') {
292                            return Err(AssemblerError::new(
293                                Some(linenum),
294                                AssemErrorKind::InvalidLabel,
295                            ));
296                        }
297
298                        self.symbols.insert(symbol.into(), value);
299                    }
300
301                    ".mov" => {
302                        let regval = textitem.next().unwrap();
303                        let register = Argument::parse(regval);
304
305                        if let Some(Argument::Reg(_)) = register {
306                        } else {
307                            return Err(AssemblerError::new(
308                                Some(linenum),
309                                AssemErrorKind::InvalidArgument(regval.into()),
310                            ));
311                        }
312
313                        let value = match Argument::parse(textitem.next().unwrap()) {
314                            Some(Argument::Imm(i)) => {
315                                let [top, bottom] = (i as u16).to_be_bytes();
316                                (Argument::Imm(bottom as isize), Argument::Imm(top as isize))
317                            }
318
319                            Some(Argument::Label(l)) => {
320                                let prefixed = format!("={}", l);
321                                (Argument::Label(prefixed.clone()), Argument::Label(prefixed))
322                            }
323
324                            _ => todo!(),
325                        };
326
327                        self.add(TextItem::new(
328                            TextItemKind::Instr(
329                                InstructionBuilder::new(OpCode::Mov)
330                                    .argument(register.as_ref().unwrap().clone())
331                                    .argument(value.0),
332                            ),
333                            address,
334                            linenum,
335                        ));
336
337                        self.add(TextItem::new(
338                            TextItemKind::Instr(
339                                InstructionBuilder::new(OpCode::Movt)
340                                    .argument(register.as_ref().unwrap().clone())
341                                    .argument(value.1),
342                            ),
343                            address,
344                            linenum,
345                        ));
346                    }
347
348                    ".nop" => {
349                        self.add(TextItem::new(
350                            TextItemKind::Instr(InstructionBuilder::default()),
351                            address,
352                            linenum,
353                        ));
354                    }
355
356                    _ => {
357                        return Err(AssemblerError::new(
358                            Some(linenum),
359                            AssemErrorKind::InvalidMnemonic(mnem.into()),
360                        ))
361                    }
362                }
363            } else {
364                let (op, sbit, cond) = match OpCode::parse(mnem) {
365                    Some(t) => t,
366                    None => {
367                        return Err(AssemblerError::new(
368                            Some(linenum),
369                            AssemErrorKind::InvalidMnemonic(mnem.into()),
370                        ))
371                    }
372                };
373
374                let mut instr = InstructionBuilder::new(op).condition(cond);
375
376                if sbit {
377                    instr = instr.update()
378                }
379
380                while let Some(a) = textitem.next() {
381                    if let Some(arg) = Argument::parse(a) {
382                        instr = instr.argument(arg);
383                    } else {
384                        return Err(AssemblerError::new(
385                            Some(linenum),
386                            AssemErrorKind::InvalidArgument(a.into()),
387                        ));
388                    }
389                }
390
391                self.add(TextItem::new(TextItemKind::Instr(instr), address, linenum));
392            }
393        }
394
395        Ok(())
396    }
397
398    pub(crate) fn resolve_symbols(&mut self) -> Result<(), AssemblerError> {
399        for (symbol, value) in self.symbols.clone() {
400            for textitem in self.as_mut_text_items() {
401                let mut symbol = symbol.clone();
402                let mut value = value.clone();
403                match textitem.kind {
404                    TextItemKind::Instr(ref mut i) => {
405                        match i {
406                            InstructionBuilder {
407                                opcode: OpCode::Br, ..
408                            } => {
409                                // IP is 4 ahead when executing an instruction
410                                value.apply(|v| {
411                                    let newv = (*v - textitem.address as isize) / 2 - 2;
412                                    *v = newv;
413                                });
414                            }
415
416                            InstructionBuilder {
417                                opcode: OpCode::Mov,
418                                args: a,
419                                ..
420                            } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
421                                let [_, Argument::Label(l)] = a.as_slice() else {
422                                    unreachable!()
423                                };
424
425                                if l.starts_with('=') {
426                                    symbol = format!("={}", symbol);
427                                    value.apply(|v| {
428                                        *v = ((*v as u16) & 0xff) as isize;
429                                    })
430                                }
431                            }
432
433                            InstructionBuilder {
434                                opcode: OpCode::Movt,
435                                args: a,
436                                ..
437                            } if matches!(a.as_slice(), [_, Argument::Label(_)]) => {
438                                let [_, Argument::Label(l)] = a.as_slice() else {
439                                    unreachable!()
440                                };
441
442                                if l.starts_with('=') {
443                                    symbol = format!("={}", symbol);
444                                    value.apply(|v| {
445                                        *v = ((*v as u16) >> 8) as isize;
446                                    })
447                                }
448                            }
449
450                            _ => {}
451                        }
452
453                        i.replace(&symbol, value);
454                    }
455                    _ => {}
456                }
457            }
458        }
459
460        Ok(())
461    }
462
463    // TODO: Add ELF support.
464    pub(crate) fn encode(self) -> Result<Vec<u8>, AssemblerError> {
465        let mut program = vec![];
466
467        if self.format == BinFormat::Elf {
468            return Err(AssemblerError::new(
469                None,
470                AssemErrorKind::ElfNotYetSupported,
471            ));
472        }
473
474        for section in self.sections {
475            for instr in section.items {
476                match instr.kind {
477                    TextItemKind::Instr(i) => {
478                        let built = match i.build() {
479                            Ok(b) => b,
480                            Err(e) => {
481                                return Err(AssemblerError::new(
482                                    Some(instr.line),
483                                    AssemErrorKind::InvalidInstruction(e),
484                                ))
485                            }
486                        };
487
488                        if !built.executable(section.mode) {
489                            return Err(AssemblerError::new(
490                                Some(instr.line),
491                                AssemErrorKind::NonExecableInstr,
492                            ));
493                        }
494
495                        let [first, second] = built.encode().to_le_bytes();
496                        program.push(first);
497                        program.push(second);
498                    }
499                    _ => {}
500                }
501            }
502        }
503
504        Ok(program)
505    }
506}