| 1 | use crate::instructions::Instruction; |
| 2 | |
| 3 | fn tokenize(line: &str) -> Vec<String> { |
| 4 | line.split(|c| c == ' ' || c == ',' || c == '\t') |
| 5 | .filter(|s| !s.is_empty()) |
| 6 | .map(|s| s.to_lowercase()) |
| 7 | .collect() |
| 8 | } |
| 9 | |
| 10 | fn parse_reg(s: &str) -> u8 { |
| 11 | match s { |
| 12 | "a" => 0, |
| 13 | "b" => 1, |
| 14 | "c" => 2, |
| 15 | "d" => 3, |
| 16 | _ => panic!("Unknown register {}", s), |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | pub fn assembler(source: &str) -> Vec<u8> { |
| 21 | let mut bytes = Vec::new(); |
| 22 | |
| 23 | for (line_no, line) in source.lines().enumerate() { |
| 24 | let line = line.trim(); |
| 25 | |
| 26 | // Comments in assembly start with ";" |
| 27 | if line.is_empty() || line.starts_with(';') { |
| 28 | continue; |
| 29 | } |
| 30 | |
| 31 | let tokens = tokenize(line); |
| 32 | |
| 33 | match tokens[0].as_str() { |
| 34 | "mov" => { |
| 35 | // mov reg, imm |
| 36 | let reg = parse_reg(&tokens[1]); |
| 37 | let imm: u8 = tokens[2].parse().unwrap(); |
| 38 | |
| 39 | bytes.push(Instruction::MOV as u8); |
| 40 | bytes.push(reg); |
| 41 | bytes.push(imm); |
| 42 | } |
| 43 | |
| 44 | "add" => { |
| 45 | // add a, b |
| 46 | let r1 = parse_reg(&tokens[1]); |
| 47 | let r2 = parse_reg(&tokens[2]); |
| 48 | |
| 49 | bytes.push(Instruction::ADD as u8); |
| 50 | bytes.push(r1); |
| 51 | bytes.push(r2); |
| 52 | } |
| 53 | |
| 54 | "sub" => { |
| 55 | // sub a, b |
| 56 | let r1 = parse_reg(&tokens[1]); |
| 57 | let r2 = parse_reg(&tokens[2]); |
| 58 | |
| 59 | bytes.push(Instruction::SUB as u8); |
| 60 | bytes.push(r1); |
| 61 | bytes.push(r2); |
| 62 | } |
| 63 | |
| 64 | "hlt" => { |
| 65 | bytes.push(Instruction::HLT as u8); |
| 66 | } |
| 67 | |
| 68 | _ => panic!("Line {}: unknown instruction", line_no + 1), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | bytes |
| 73 | } |