From aea15f0a2c265ea1afc04a227eff5cbfaef9c3a3 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Thu, 13 Feb 2025 23:27:21 +0200 Subject: feat(assembler): Bytes output and pretty print --- assembler/src/parser/code_gen.rs | 11 +++++++++++ assembler/src/parser/mod.rs | 27 ++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) (limited to 'assembler/src/parser') diff --git a/assembler/src/parser/code_gen.rs b/assembler/src/parser/code_gen.rs index 77f2c2f..4352e9e 100644 --- a/assembler/src/parser/code_gen.rs +++ b/assembler/src/parser/code_gen.rs @@ -52,4 +52,15 @@ impl Program { } self.instructions.clear(); } + + pub(crate) fn to_bytes(self, absolute_start: usize) -> Vec { + let mut res = Vec::new(); + res.resize(absolute_start, Default::default()); + res.extend(self.constants); + res + .into_iter() + .map(|x| x.to_be_bytes()) + .flatten() + .collect() + } } diff --git a/assembler/src/parser/mod.rs b/assembler/src/parser/mod.rs index 5dbedf6..79b8835 100644 --- a/assembler/src/parser/mod.rs +++ b/assembler/src/parser/mod.rs @@ -2,7 +2,10 @@ mod code_gen; mod syntax; mod instruction; -use std::collections::HashMap; +use std::{ + collections::HashMap, + fmt::{ Display, Formatter, Result }, +}; use crate::Word; #[derive(Debug, Default)] @@ -12,6 +15,28 @@ pub(crate) struct Program { instructions: Vec, } +impl Display for Program { + fn fmt(&self, f: &mut Formatter) -> Result { + writeln!(f, "-- Definitions --")?; + for (name, loc) in self.definitions.iter() { + writeln!(f, "{} := {:?}", name, loc)?; + } + writeln!(f, "-- Constants --")?; + for (i, cnst) in self.constants.iter().enumerate() { + writeln!(f, "{: >8}: {} ", i, cnst)?; + } + writeln!(f, "-- Instructions --")?; + for (i, instr) in self.instructions.iter().enumerate() { + write!(f, "{: >8}: {} ", i, instr.name)?; + for arg in &instr.args { + write!(f, "{:?}, ", arg)?; + } + writeln!(f, "")?; + } + Ok(()) + } +} + #[derive(Debug, Default, PartialEq, Eq, Clone)] pub(crate) enum Address { Memory(usize), -- cgit v1.3.1-23-gd82d