From 4098fbd417a931f0ae9fbe0fe2f0ffe911b13878 Mon Sep 17 00:00:00 2001 From: Cassie Jones Date: Sat, 11 Jan 2020 07:20:21 -0500 Subject: [PATCH] Add a very basic assembler utility --- toolchain/src/bin/assembler.rs | 29 +++++++++++++++++++++++++++++ toolchain/src/inst/test.rs | 16 ++++++++++++---- toolchain/src/main.rs | 3 --- 3 files changed, 41 insertions(+), 7 deletions(-) create mode 100644 toolchain/src/bin/assembler.rs delete mode 100644 toolchain/src/main.rs diff --git a/toolchain/src/bin/assembler.rs b/toolchain/src/bin/assembler.rs new file mode 100644 index 0000000..a360381 --- /dev/null +++ b/toolchain/src/bin/assembler.rs @@ -0,0 +1,29 @@ +use std::io::{self, BufRead}; +use toolchain::inst::{encode::Encode, parse::parse_inst}; + +macro_rules! other_err { + ($fmt:expr $(, $arg:expr)* $(,)?) => { + io::Error::new(io::ErrorKind::Other, format!($fmt, $($arg),*)) + } +} + +fn main() -> io::Result<()> { + let mut cursor = io::Cursor::new(Vec::new()); + for (i, line) in io::stdin().lock().lines().enumerate() { + let line = line.map_err(|_| other_err!("Error reading line {}", i + 1))?; + let line = line.trim(); + if line.is_empty() { + continue; + } + let inst = parse_inst(&line) + .ok_or_else(|| other_err!("Error parsing instruction on line {}", i + 1))?; + inst.encode(&mut cursor)?; + } + for line in cursor.into_inner().chunks(40) { + for byte in line { + print!("{:02x}", byte); + } + println!(); + } + Ok(()) +} diff --git a/toolchain/src/inst/test.rs b/toolchain/src/inst/test.rs index 58a8697..4fcc054 100644 --- a/toolchain/src/inst/test.rs +++ b/toolchain/src/inst/test.rs @@ -1,10 +1,16 @@ -use super::{parse, encode::Encode}; +use super::{encode::Encode, parse}; use std::io::Cursor; fn display(buf: &[u8]) -> String { match buf.len() { 1 => format!("{:04b}_{:04b}", buf[0] >> 4, buf[0] & 0xf), - 2 => format!("{:04b}_{:04b} {:04b}_{:04b}", buf[0] >> 4, buf[0] & 0xf, buf[1] >> 4, buf[1] & 0xf), + 2 => format!( + "{:04b}_{:04b} {:04b}_{:04b}", + buf[0] >> 4, + buf[0] & 0xf, + buf[1] >> 4, + buf[1] & 0xf + ), n => unreachable!("Shouldn't be instructions of length {}", n), } } @@ -13,7 +19,7 @@ macro_rules! case { ($txt:expr => !) => { assert!( parse::parse_inst($txt).is_none(), - "expect to not parse {:?}", + "expect to not parse {:?}", $txt, ); }; @@ -21,7 +27,9 @@ macro_rules! case { let mut buf = [0, 0]; let mut cursor = Cursor::new(&mut buf[..]); let parsed = parse::parse_inst($txt).expect(&format!("to parse {:?}", $txt)); - parsed.encode(&mut cursor).expect(&format!("to encode {:?}", parsed)); + parsed + .encode(&mut cursor) + .expect(&format!("to encode {:?}", parsed)); let pos = cursor.position() as usize; assert_eq!($res, &display(&buf[..pos]), "While parsing {:?}", $txt); }; diff --git a/toolchain/src/main.rs b/toolchain/src/main.rs deleted file mode 100644 index c89b901..0000000 --- a/toolchain/src/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - todo!(); -} -- 2.47.0