diff options
Diffstat (limited to 'lib/xixanta')
| -rw-r--r-- | lib/xixanta/Cargo.toml | 14 | ||||
| -rw-r--r-- | lib/xixanta/src/assembler.rs | 1711 | ||||
| -rw-r--r-- | lib/xixanta/src/context.rs | 66 | ||||
| -rw-r--r-- | lib/xixanta/src/errors.rs | 25 | ||||
| -rw-r--r-- | lib/xixanta/src/instruction.rs | 277 | ||||
| -rw-r--r-- | lib/xixanta/src/lib.rs | 10 | ||||
| -rw-r--r-- | lib/xixanta/src/opcodes.rs | 631 |
7 files changed, 2734 insertions, 0 deletions
diff --git a/lib/xixanta/Cargo.toml b/lib/xixanta/Cargo.toml new file mode 100644 index 0000000..76a0660 --- /dev/null +++ b/lib/xixanta/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "xixanta" +version = "0.1.0" +description = "TBD" + +authors.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +lazy_static = "1.4.0" diff --git a/lib/xixanta/src/assembler.rs b/lib/xixanta/src/assembler.rs new file mode 100644 index 0000000..5d03186 --- /dev/null +++ b/lib/xixanta/src/assembler.rs @@ -0,0 +1,1711 @@ +use crate::context::Context; +use crate::errors::ParseError; +use crate::instruction::{ + AddressingMode, Encodable, Generic, Instruction, Literal, Node, PString, Scoped, +}; +use crate::opcodes::{INSTRUCTIONS, OPCODES}; +use std::collections::hash_map::Entry; +use std::io::{self, BufRead, Read}; +use std::ops::Range; + +type Result<T> = std::result::Result<T, ParseError>; + +pub struct Assembler { + line: usize, + column: usize, + offset_address: usize, + context: Context, + + // TODO: segments instead + nodes: Vec<Node>, +} + +impl Default for Assembler { + fn default() -> Self { + Assembler::new() + } +} + +impl Assembler { + pub fn new() -> Self { + Self { + line: 0, + column: 0, + offset_address: 0, + context: Context::new(), + nodes: vec![], + } + } + + pub fn reset(&mut self) { + self.line = 0; + self.column = 0; + self.offset_address = 0; + self.nodes = vec![]; + self.context = Context::new(); + } + + pub fn to_nodes(&mut self, reader: impl Read) -> Result<&Vec<Node>> { + self.from_reader(reader)?; + self.context.reset(); + self.evaluate()?; + + Ok(&self.nodes) + } + + pub fn assemble(&mut self, reader: impl Read) -> Result<Vec<&dyn Encodable>> { + let mut instructions: Vec<&dyn Encodable> = vec![]; + + for node in self.to_nodes(reader)? { + match node { + Node::Instruction(instr) => instructions.push(instr), + Node::Literal(lit) => instructions.push(lit), + _ => {} + } + } + + Ok(instructions) + } + + pub fn disassemble(&mut self, reader: impl Read) -> Result<Vec<&dyn Encodable>> { + self.from_byte_reader(reader)?; + + let mut instructions: Vec<&dyn Encodable> = vec![]; + for node in &self.nodes { + match node { + Node::Instruction(instr) => instructions.push(instr), + Node::Literal(lit) => instructions.push(lit), + _ => {} + } + } + + Ok(instructions) + } + + pub fn from_reader<R: Read>(&mut self, reader: R) -> Result<()> { + for line in io::BufReader::new(reader).lines() { + // TODO: instead of this, accumulate errors so to give as many + // errors as possible. + self.parse_line(line?.as_str())?; + self.line += 1; + } + Ok(()) + } + + pub fn parse_line(&mut self, line: &str) -> Result<()> { + self.column = 0; + + if !self.skip_whitespace(line) { + return Ok(()); + } + + match self.parse_identifier(line) { + Some(identifier) => self.parse_from_identifier(identifier, line), + None => Ok(()), + } + } + + pub fn evaluate(&mut self) -> Result<()> { + for node in &mut self.nodes { + match node { + Node::Instruction(instr) => { + Self::update_instruction_with_context(instr, &self.context)? + } + Node::Scoped(scope) => { + if scope.start { + self.context.push(&scope.identifier.value); + } else { + _ = self.context.pop(); + } + } + Node::Literal(literal) => { + Self::update_literal_with_context(literal, &self.context)? + } + _ => {} + } + } + + Ok(()) + } + + fn update_instruction_with_context(instr: &mut Instruction, context: &Context) -> Result<()> { + // To keep things simple, we remove out the `implied` case and we parse + // further with a known `Some` value for the base algorithm implemented + // in `update_instruction_and_bytes`. + if instr.left.is_some() { + Self::update_addressing_and_bytes(instr, context)?; + } else { + instr.mode = AddressingMode::Implied; + } + + // Now that we have the addressing mode and the bytes, we can fill out + // the rest of it by fetching the values on `INSTRUCTIONS`. + match INSTRUCTIONS.get(&instr.mnemonic.value.to_lowercase()) { + Some(entries) => match entries.get(&instr.mode) { + Some(values) => { + instr.cycles = values.cycles; + instr.opcode = values.opcode; + instr.size = values.size; + instr.affected_on_page = values.affected_on_page; + } + None => { + return Err(instr.mnemonic.parser_error( + format!( + "bad addressing mode '{}' for the instruction '{}'", + &instr.mode, &instr.mnemonic.value + ) + .as_str(), + )); + } + }, + None => { + return Err(instr.mnemonic.parser_error( + format!("unknown instruction '{}'", &instr.mnemonic.value).as_str(), + )); + } + } + + Ok(()) + } + + fn update_addressing_and_bytes(instr: &mut Instruction, context: &Context) -> Result<()> { + // `unwrap()` is guaranteed to work by the caller. + let left = instr.left.as_ref().unwrap(); + + // We will first try to check if there's any variable involved on the + // left arm and replace the string if so. This will greatly simplify + // things down the line. That being said, there is a special reserved + // case, which is the implied addressing by using "a". In this case, we + // want to ensure that we assume an implied addressing and not a + // variable named "a". + if left.value.to_lowercase() == "a" { + instr.mode = AddressingMode::Implied; + } else { + let nleft = Self::replace_variable(left, context)?; + + if nleft.value.starts_with('$') { + // This is an address. At this point we should assume that the + // left node contains the address itself, and that the right one + // will contain whether there is indexing. + + let string = nleft.value.chars().as_str(); + instr.bytes = Self::parse_hex_from(string, &nleft, true, false, true)?; + + match &instr.right { + Some(xy) => match xy.value.to_lowercase().as_str() { + "x" => { + if string.len() == 3 { + instr.mode = AddressingMode::ZeropageIndexedX; + } else { + instr.mode = AddressingMode::IndexedX; + } + } + "y" => { + if string.len() == 3 { + instr.mode = AddressingMode::ZeropageIndexedY; + } else { + instr.mode = AddressingMode::IndexedY; + } + } + _ => return Err(xy.parser_error("index is neither X nor Y")), + }, + None => { + if string.len() == 3 { + instr.mode = AddressingMode::RelativeOrZeropage; + } else { + instr.mode = AddressingMode::Absolute; + } + } + } + } else if nleft.value.starts_with('#') { + // Immediate addressing in any case: hexadecimal, binary or + // decimal. Hence, just figure out the character being used and + // call the right function for it. + + let mut chars = nleft.value.chars(); + chars.next(); + let string = chars.as_str(); + + instr.bytes = Self::parse_numeric(string, &nleft, false)?; + instr.mode = AddressingMode::Immediate; + } else if nleft.value.starts_with('(') { + // Indirect addressing. In this case the left arm can be further + // subdivided. That is, indirect X-indexing is represented like + // so: `instr ($NN, x)`. Hence, first of all we have to figure + // out whether there is a subdivision. + + let (left1, oleft2) = Self::split_left_arm(&nleft)?; + match oleft2 { + Some(left2) => { + // There is subdivision. Thus, we have to assume + // indirect X-indexing, which means that the right arm + // should be None and that the right side of the left + // node must match the X register. Other than that, the + // address being referenced must be zero page. + if instr.right.is_some() { + return Err(instr.right.as_ref().unwrap().parser_error( + "bad indirect mode, expecting an indirect X-indexed addressing mode" + )); + } + if left2.value.to_lowercase() != "x" { + return Err(left2.parser_error( + "the index in indirect X-indexed addressing must be X", + )); + } + match Self::parse_hex_from(&left1.value, &left1, false, false, true) { + Ok(bytes) => instr.bytes = bytes, + Err(e) => { + let msg = String::from( + "when parsing an instruction with indirect X-indexed addressing: ", + ) + &e.message; + return Err(left1.parser_error(msg.as_str())); + } + } + instr.mode = AddressingMode::IndirectX; + } + None => { + // There is no subdivision on the left arm. Hence, if + // there is something on the right arm then we must + // assume indirect Y-index addressing, and if not then + // it's indirect addressing with no indices involvved. + if instr.right.is_some() { + if instr.right.as_ref().unwrap().value.to_lowercase() != "y" { + return Err(instr.right.as_ref().unwrap().parser_error( + "the index in indirect Y-indexed addressing must be Y", + )); + } + match Self::parse_hex_from(&left1.value, &left1, false, false, true) { + Ok(bytes) => instr.bytes = bytes, + Err(e) => { + let msg = String::from( + "when parsing an instruction with indirect Y-indexed addressing: ", + ) + &e.message; + return Err(left1.parser_error(msg.as_str())); + } + } + instr.mode = AddressingMode::IndirectY; + } else { + instr.bytes = + Self::parse_hex_from(&left1.value, &left1, true, true, true)?; + instr.mode = AddressingMode::Indirect; + } + } + } + } else { + // At this point all of the syntax cases have been exhausted: + // the programmer messed up. From this point on we try to figure + // out how they messed up. + + if nleft.value.starts_with('=') { + return Err(instr.mnemonic.parser_error( + format!( + "cannot use '{}' in an assignment because it's a word reserved for an instruction mnemonic", + instr.mnemonic.value + ).as_str(), + )); + } + return Err(instr.mnemonic.parser_error( + format!( + "unknown addressing mode for instruction '{}'", + instr.mnemonic.value + ) + .as_str(), + )); + } + } + + Ok(()) + } + + fn update_literal_with_context(literal: &mut Literal, context: &Context) -> Result<()> { + // Evaluate any possible variable being used inside of this literal. + let evaled = Self::replace_variable(&literal.identifier, context)?; + + // Parse the numeric value after a possible variable has been replaced. + let two_bytes_allowed = literal.size == 2; + let res = Self::parse_numeric( + evaled.value.as_str(), + &literal.identifier, + two_bytes_allowed, + ); + + // And finally assign the computed bytes. + match res { + Ok(bytes) => { + literal.bytes = bytes; + Ok(()) + } + Err(e) => { + let msg = String::from("when parsing a data literal: ") + &e.message; + Err(literal.identifier.parser_error(msg.as_str())) + } + } + } + + fn parse_numeric(string: &str, node: &PString, two_bytes_allowed: bool) -> Result<[u8; 2]> { + if string.starts_with('$') { + Ok(Self::parse_hex_from( + string, + node, + two_bytes_allowed, + false, + true, + )?) + } else if string.starts_with('%') { + Ok([Self::parse_binary_from(string, node)?, 0]) + } else { + Ok([Self::parse_decimal_from(string, node)?, 0]) + } + } + + fn split_left_arm(node: &PString) -> Result<(PString, Option<PString>)> { + let mut chars = node.value.chars(); + chars.next(); + let string = chars.as_str(); + + match string.find(|c: char| c == ',') { + Some(idx) => { + let left1 = string.get(..idx).unwrap_or("").trim(); + let left2 = string.get(idx + 1..).unwrap_or("").trim(); + + Ok(( + PString { + value: left1.to_string(), + line: node.line, + range: Range { + start: node.range.start + 1, + end: node.range.start + 1 + left1.len(), + }, + }, + Some(PString { + value: left2.to_string(), + line: node.line, + range: Range { + start: node.range.start + 1 + idx, + end: node.range.start + 1 + idx + left2.len(), + }, + }), + )) + } + None => Ok(( + PString { + value: string.to_string(), + line: node.line, + range: Range { + start: node.range.start + 1, + end: node.range.end, + }, + }, + None, + )), + } + } + + fn parse_binary_from(string: &str, node: &PString) -> Result<u8> { + let mut value = 0; + let mut shift = 0; + + for c in string.get(1..).unwrap_or("").chars().rev() { + if c == '1' { + let val = 1 << shift; + value += val; + } else if c != '0' { + return Err( + node.parser_error(format!("bad binary format for '{}'", string).as_str()) + ); + } + + shift += 1; + } + + if shift < 8 { + Err(node.parser_error("missing binary digits to get a full byte")) + } else if shift > 8 { + Err(node.parser_error("too many binary digits for a single byte")) + } else { + Ok(value) + } + } + + fn replace_variable(node: &PString, context: &Context) -> Result<PString> { + match node.value.find(|c: char| c.is_alphabetic() || c == '_') { + Some(idx) => { + // Before doing any replacement, let's check the character + // before the one that was found. In this case, if it was a + // proper ASCII digit, then it cannot be a variable but it's + // part of a numeric literal (e.g. '1A'): then just let the + // different numeric parsing functions do their job. + if idx > 0 { + let prev = node.value.chars().nth(idx - 1).unwrap_or(' '); + if prev.is_ascii_digit() { + return Ok(node.clone()); + } + } + + // The variable might still be before an inner comma (e.g. + // sta ($20, x)). We will assume that variables can happen + // only before that. + let end = node.value.find(',').unwrap_or(node.value.len()); + let mut string = node.value.get(idx..end).unwrap_or(""); + let tail = node.value.get(end..).unwrap_or(""); + + // Get the context that might be being referenced. + let ctxt = match string.find("::") { + Some(_) => { + let tctxt = string.rsplit_once("::").unwrap_or(("", "")); + if tctxt.0.is_empty() { + context.current() + } else { + string = tctxt.1; + context.find(tctxt.0) + } + } + None => context.current(), + }; + + match ctxt { + Some(hash) => { + // If there was a comma before the "variable" (i.e. idx > + // end and hence string == ""), or this is just the regular + // X or Y index, just return early. + match string.to_lowercase().as_str() { + "x" | "y" | "" => return Ok(node.clone()), + _ => {} + } + + // It's not any of the indices, let's look for a match on + // the current scope. + match hash.get(string) { + Some(var) => { + let value = String::from(node.value.get(..idx).unwrap_or("")) + + var.value.as_str(); + Ok(PString { + value: value.clone() + tail, + line: node.line, + range: Range { + start: node.range.start, + end: node.range.start + value.len(), + }, + }) + } + None => { + // If a variable could not be found, check that + // this is not a purely hexadecimal number (e.g. + // 'AA'). If that's the case, then just return + // its value. + if Self::parse_hex_from(string, node, true, false, false).is_ok() { + return Ok(node.clone()); + } + + // We've tried hard to not assume the programmer + // messing up, but there's no other way around + // it: it's an "unknown variable" error. + return Err(node.parser_error( + format!("unknown variable '{}'", string).as_str(), + )); + } + } + } + None => { + Err(node.parser_error(format!("unknown scope '{}'", "Global").as_str())) + } + } + } + None => Ok(node.clone()), + } + } + + // Parse an hexadecimal value from the given `string`. A `node` must also be + // supplied so a ParseError can be pushed inside of it in case anything goes + // wrong. Other than that, there are three boolean parameters that have to + // be passed: + // - `two_bytes_allowed`: the value can be 8-bit or 16-bit long. + // - `exactly_two_bytes`: the value has to be exactly 16-bit long. + // - `char_given`: whether the string starts with a '$' character or not. + fn parse_hex_from( + string: &str, + node: &PString, + two_bytes_allowed: bool, + exactly_two_bytes: bool, + char_given: bool, + ) -> Result<[u8; 2]> { + let mut chars = string.chars(); + let len = if char_given { + chars.next(); + string.len() - 1 + } else { + string.len() + }; + + match len { + 2 => { + if exactly_two_bytes { + return Err(node.parser_error("expecting a full 16-bit address")); + } + let mut i = Self::char_to_hex(node, chars.next())? * 16; + i += Self::char_to_hex(node, chars.next())?; + + Ok([i, 0]) + } + 4 => { + if !two_bytes_allowed { + return Err(node.parser_error("only one byte of data is allowed here")); + } + + let mut hi = Self::char_to_hex(node, chars.next())? * 16; + hi += Self::char_to_hex(node, chars.next())?; + + let mut lo = Self::char_to_hex(node, chars.next())? * 16; + lo += Self::char_to_hex(node, chars.next())?; + + Ok([lo, hi]) + } + _ => { + if two_bytes_allowed { + Err(node.parser_error("expecting a number of 2/4 hexadecimal digits")) + } else if exactly_two_bytes { + Err(node.parser_error("expecting a number of 4 hexadecimal digits")) + } else { + Err(node.parser_error("expecting a number of 2 hexadecimal digits")) + } + } + } + } + + fn char_to_hex(node: &PString, oc: Option<char>) -> Result<u8> { + match oc { + Some(c) => match c.to_digit(16) { + Some(c) => Ok(c as u8), + None => Err(node.parser_error("could not convert digit to hexadecimal")), + }, + None => Err(node.parser_error("digit out of bounds")), + } + } + + fn parse_decimal_from(string: &str, node: &PString) -> Result<u8> { + let mut value = 0; + let mut shift = 1; + + if string.is_empty() { + return Err(node.parser_error("empty decimal literal")); + } + + for c in string.chars().rev() { + if shift > 100 { + return Err(node.parser_error("decimal value is too big")); + } + if c != '0' { + match c.to_digit(10) { + Some(digit) => { + value += digit * shift; + } + None => { + return Err( + node.parser_error(format!("'{}' is not a decimal value", c).as_str()) + ) + } + } + } + + shift *= 10; + } + if value > 255 { + return Err(node.parser_error("decimal value is too big")); + } + + Ok(value as u8) + } + + // Advances `self.column` until a non-whitespace character is found. Returns + // false if the line can be skipped entirely, true otherwise. + fn skip_whitespace(&mut self, line: &str) -> bool { + for c in line.get(self.column..).unwrap_or("").chars() { + if !c.is_whitespace() { + if c == ';' { + return false; + } + return true; + } + + self.column += 1; + } + + true + } + + // Returns a PString object which holds the information for an identifier. + // + // NOTE: this function assumes that `self.column` points to a non-whitespace + // character. + fn parse_identifier(&mut self, line: &str) -> Option<PString> { + let column = self.column; + + // For the general case we just need to iterate until a whitespace + // character or an inline comment is found. Then our PString object + // is merely whatever is on the column..self.column range. + for c in line.get(column..).unwrap_or("").chars() { + if c.is_whitespace() || c == ';' { + let range = Range { + start: column, + end: self.column, + }; + + return Some(PString { + value: String::from(line.get(range.clone()).unwrap_or("").trim()), + line: self.line, + range, + }); + } + + self.column += 1; + } + + // Otherwise, we might be at a point whether there is nothing (e.g. an + // empty line), or the line is merely the identifier (e.g. instruction + // with implied addressing). + let range = Range { + start: column, + end: line.len(), + }; + let id = String::from(line.get(range.clone()).unwrap_or("").trim()); + if id.is_empty() { + None + } else { + Some(PString { + value: id, + line: self.line, + range, + }) + } + } + + // Given a PString object which acts as the identifier, try to parse the + // rest of the line depending on whether it's an instruction (e.g. `adc + // $20`), a control statement (e.g. `.macro whatever`) or a general + // statement (e.g. `Var = $10`). + fn parse_from_identifier(&mut self, id: PString, line: &str) -> Result<()> { + if id.value.starts_with('.') { + // If the statement starts with a '.', it's guaranteed to be a + // control statement. + self.parse_control(id, line) + } else { + // Otherwise, we will parse it either as an instruction or a general + // statement depending on whether the parsed identifier is a valid + // instruction mnemonic or not. + match INSTRUCTIONS.get(&id.value) { + Some(_instr) => self.parse_instruction(id, line), + None => self.parse_statement(id, line), + } + } + } + + // TODO: + // - functions + // - macros + fn parse_control(&mut self, id: PString, line: &str) -> Result<()> { + match id.value.to_lowercase().as_str() { + ".scope" => self.parse_scope_definition(&id, line), + ".endscope" => self.parse_scope_end(&id), + ".byte" | ".db" => self.parse_literal_bytes(&id, line, false), + ".word" | ".dw" => self.parse_literal_bytes(&id, line, true), + _ => { + return Err( + id.parser_error(format!("unknown control statement '{}'", id.value).as_str()) + ) + } + } + } + + fn parse_scope_definition(&mut self, id: &PString, line: &str) -> Result<()> { + self.skip_whitespace(line); + + let identifier = self.fetch_identifier(id, line)?; + if identifier.is_reserved() { + return Err(identifier.parser_error( + format!("cannot use reserved name '{}'", identifier.value).as_str(), + )); + } + self.context.push(&identifier.value); + self.nodes.push(Node::Scoped(Scoped { + identifier, + start: true, + })); + + Ok(()) + } + + fn parse_scope_end(&mut self, id: &PString) -> Result<()> { + if !self.context.pop() { + return Err(id.parser_error("missmatched '.endscope': there is no scope to end")); + } + self.nodes.push(Node::Scoped(Scoped { + identifier: PString::new(), + start: false, + })); + + Ok(()) + } + + fn parse_literal_bytes( + &mut self, + node: &PString, + line: &str, + two_bytes_allowed: bool, + ) -> Result<()> { + loop { + self.skip_whitespace(line); + + match line.chars().nth(self.column) { + Some(byte) => { + let needle = if byte == '\'' { + self.column += 1; + self.skip_whitespace(line); + '\'' + } else if byte == '"' { + self.column += 1; + self.skip_whitespace(line); + '"' + } else { + ',' + }; + + let idx = line + .get(self.column..) + .unwrap_or("") + .find(|c: char| c == needle) + .unwrap_or(line.len() - self.column); + + // If this is the last character, the needle was a quote and + // the last char is not the needle, then it means that the + // quote was left open. Complain about this as well. + if idx == line.len() - self.column { + if line.chars().nth(idx).unwrap_or(' ') != needle + && (needle == '"' || needle == '\'') + { + return Err(node.parser_error("non-terminated quote for byte literal")); + } + } + + // NOTE: for now we push an incomplete literal. We need the + // first pass to fill the context and then a second pass + // will evaluate each literal as needed (e.g. replacing + // values from variables being used in this literal). + let string = line.get(self.column..self.column + idx).unwrap_or(" "); + self.nodes.push(Node::Literal(Literal { + identifier: PString { + value: string.to_owned(), + line: self.line, + range: Range { + start: self.column, + end: self.column + idx, + }, + }, + size: if two_bytes_allowed { 2 } else { 1 }, + bytes: [0, 0], + })); + + self.column += idx; + for c in line.get(self.column..).unwrap_or(" ").chars() { + if c == ',' { + break; + } + if c == ';' { + return Ok(()); + } + self.column += 1; + } + self.column += 1; + self.skip_whitespace(line); + } + None => break, + }; + } + + Ok(()) + } + + fn fetch_identifier(&mut self, id: &PString, line: &str) -> Result<PString> { + let idx = line + .get(self.column..) + .unwrap_or(" ") + .find(|c: char| c.is_whitespace()); + + match idx { + Some(offset) => { + let end = self.column + offset; + let rest = line.get(end..).unwrap_or("").trim(); + if !rest.is_empty() { + if rest.chars().nth(0).unwrap_or(' ') != ';' { + return Err(id.parser_error( + "there should not be any further content besides the identifier", + )); + } + } + Ok(PString { + value: line.get(self.column..end).unwrap_or(" ").trim().to_string(), + line: self.line, + range: Range { + start: self.column, + end, + }, + }) + } + None => Ok(PString { + value: line.get(self.column..).unwrap_or(" ").trim().to_string(), + line: self.line, + range: Range { + start: self.column, + end: line.len(), + }, + }), + } + } + + fn parse_statement(&mut self, id: PString, line: &str) -> Result<()> { + if line.chars().nth(self.column).unwrap_or(' ') == ':' { + self.parse_label(id, line) + } else { + self.parse_assignment(id, line) + } + } + + fn parse_label(&mut self, _id: PString, _line: &str) -> Result<()> { + // TODO: + + Ok(()) + } + + fn parse_assignment(&mut self, id: PString, line: &str) -> Result<()> { + // You cannot assign into a name which is reserved. + if id.is_reserved() { + return Err( + id.parser_error(format!("cannot use reserved name '{}'", id.value).as_str()) + ); + } + + // To avoid problems down the line, you cannot assign into names which + // are proper hexadecimal values. + if Self::parse_hex_from(&id.value, &id, true, false, false).is_ok() { + return Err(id.parser_error( + format!( + "cannot use names which are valid hexadecimal values such as '{}'", + id.value + ) + .as_str(), + )); + } + + // You cannot assign into scoped names: declare them into their + // respective scopes instead. + if id.value.contains("::") { + return Err(id.parser_error( + format!( + "the name '{}' is scoped: do not declare variables this way", + id.value + ) + .as_str(), + )); + } + + // Skip whitespaces and make sure that we have a '=' sign. + self.skip_whitespace(line); + if line.chars().nth(self.column).unwrap_or(' ') != '=' { + return Err(self.parser_error(format!("unknown instruction '{}'", id.value).as_str())); + } + + // Skip the '=' sign and any possible whitespaces. + self.column += 1; + if !self.skip_whitespace(line) { + return Err(self.parser_error("incomplete assignment")); + } + + let l = String::from(line.get(self.column..).unwrap_or("").trim()); + if l.is_empty() { + return Err(self.parser_error("incomplete assignment")); + } + + // The `Context` struct pretty much guarantees that `current` and + // `current_mut` will return something, so it's safe to ignore a + // `None`. + if let Some(entry) = self.context.current_mut() { + match entry.entry(id.value.clone()) { + Entry::Occupied(e) => { + return Err(ParseError { + line: self.line, + message: format!( + "variable '{}' is being re-assigned: it was previously defined in line {}", + id.value, e.get().clone().line), + }) + } + Entry::Vacant(e) => e.insert(PString { + value: l, + line: self.line, + range: Range { + start: id.range.start, + end: line.len(), + }, + }), + }; + } + + Ok(()) + } + + fn parse_instruction(&mut self, id: PString, line: &str) -> Result<()> { + // Parse the instruction into a `Generic` node. + let node = self.get_generic_instruction_node(id, line)?; + + // Make sure that there is no dangling content. + for c in line.get(self.column..).unwrap_or("").chars() { + if c == ';' { + break; + } + if !c.is_whitespace() { + return Err(self.parser_error("only one statement is allowed per line")); + } + self.column += 1; + } + + // And push a new `Instruction` object based on the parsed node. Note + // that this instruction will be incomplete: we first need to evaluate + // variables first in this context to be able to fully parse this + // object. + self.push_incomplete_instruction_from(node) + } + + // Returns a `Generic` node with the contents that can be parsed with the + // rest of the `line` and assuming that this is an assembly instruction + // which is identified by `id`. + fn get_generic_instruction_node(&mut self, id: PString, line: &str) -> Result<Generic> { + // First of all, make sure that we are at a non-whitespace character. + self.skip_whitespace(line); + + // Instructions have a character which split the left and the right arms + // of the instruction. This is the character that we will use in order + // to stop on the first loop. + let needle_char = match line.chars().nth(self.column) { + Some(c) => { + if c == '(' { + ')' + } else { + ',' + } + } + None => ',', + }; + + let mut column = self.column; + let mut left = None; + let mut right = None; + let mut found = false; + + // First of the two loops: fetch the left arm. It iterates + // until the needle_char is found and then initializes the `left` + // variable with the fetched contents. + for c in line.get(column..).unwrap_or("").chars() { + if c == ';' { + break; + } + if c == needle_char { + self.init_positioned_maybe(&mut left, line, column, self.column); + + for inner in line.get(self.column..).unwrap_or("").chars() { + if inner.is_whitespace() || inner == ';' { + break; + } + self.column += 1; + } + + found = true; + break; + } + + self.column += 1; + } + + // If the previous loop found the needle, the we might have a right arm. + // Otherwise, if the needle was not found but the end of the line was + // reached, we might still need to pick up the contents that were not + // saved in the previous loop. + if found { + // Ready the `column` for the right arm. + self.skip_whitespace(line); + column = self.column; + + // Second loop: fetch the right arm. This time it iterates until a + // whitespace character or ';' is found. + for c in line.get(column..).unwrap_or("").chars() { + if c == ';' { + self.init_positioned_maybe(&mut right, line, column, self.column); + break; + } + self.column += 1; + } + + // Similarly to the first loop, if this second one reached the end + // without finding a whitespace or a ';' character, make sure that this + // content is not ignored. + self.init_positioned_maybe(&mut right, line, column, self.column); + } else { + self.init_positioned_maybe(&mut left, line, column, self.column); + } + + Ok(Generic { + identifier: id, + left, + right, + }) + } + + // Initialize the PString object `p` with the contents of + // `line.get(left..right)` unless it has already a `Some` value or the + // fetched contents would result in an empty string. + fn init_positioned_maybe( + &mut self, + p: &mut Option<PString>, + line: &str, + left: usize, + right: usize, + ) { + if !p.is_none() || left == right { + return; + } + + let string = String::from(line.get(left..right).unwrap_or("").trim()); + if !string.is_empty() { + *p = Some(PString { + value: string, + line: self.line, + range: Range { + start: left, + end: right, + }, + }); + } + } + + fn push_incomplete_instruction_from(&mut self, node: Generic) -> Result<()> { + let mut instr = Instruction::from(&node.identifier.value); + instr.left = node.left; + instr.right = node.right; + + self.nodes.push(Node::Instruction(instr)); + Ok(()) + } + + fn parser_error(&self, msg: &str) -> ParseError { + ParseError { + message: String::from(msg), + line: self.line, + } + } + + pub fn from_byte_reader<R: Read>(&mut self, mut reader: R) -> Result<()> { + loop { + let mut buf = [0; 1]; + let n = reader.read(&mut buf)?; + if n == 0 { + break; + } + + match OPCODES.get(&buf[0]) { + Some(v) => { + let mut bs = [0; 2]; + for i in 0..v.size - 1 { + let nn = reader.read(&mut buf)?; + if nn == 0 { + break; + } + bs[i as usize] = buf[0]; + } + self.nodes.push(Node::Instruction(Instruction { + mnemonic: PString::from(&v.mnemonic), + opcode: v.opcode, + size: v.size, + bytes: bs, + left: None, + right: None, + mode: v.mode.to_owned(), + cycles: v.cycles, + affected_on_page: v.affected_on_page, + })) + } + + None => { + return Err( + self.parser_error(format!("unknown byte '0x{:02X}'", buf[0]).as_str()) + ) + } + } + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::instruction::Node::Instruction; + + fn assert_hex(one: &dyn Encodable, expected: &[u8]) { + assert_eq!( + one.to_hex(), + expected + .iter() + .map(|x| format!("{:02X}", x)) + .collect::<Vec<_>>() + ); + } + + fn instruction_test( + line: &str, + hex: &[u8], + cycles: u8, + affected: bool, + skip_disassemble: bool, + ) { + let mut parser = Assembler::new(); + let res = parser.to_nodes(line.as_bytes()); + + if res.is_err() { + if let Err(e) = res.clone() { + assert_eq!( + e, + ParseError { + line: 0, + message: String::from("") + } + ) + } + } + + let vec = res.unwrap(); + assert_eq!(vec.len(), 1); + + if let Instruction(instr) = &vec[0] { + assert_hex(instr, hex); + assert_eq!(instr.cycles, cycles); + assert_eq!(instr.affected_on_page, affected); + } else { + println!("Not an instruction!"); + assert!(false); + } + + // Now disassemble. + + if skip_disassemble { + return; + } + + parser.reset(); + let dis = parser.disassemble(hex); + assert!(dis.is_ok()); + + let dvec = dis.unwrap(); + assert_eq!(dvec.len(), 1); + + let dinstr = dvec[0]; + assert_eq!(dinstr.to_human(), line); + } + + fn instruction_err(line: &str, message: &str) { + let mut parser = Assembler::new(); + let err = parser.assemble(line.as_bytes()); + + assert!(err.is_err()); + if let Err(e) = err { + assert_eq!(e.message, message); + } + } + + // Mainly errors. + + #[test] + fn bad_addressing() { + instruction_err("unknown #$20", "unknown instruction 'unknown'"); + instruction_err( + "adc ($2002, x)", + "when parsing an instruction with indirect X-indexed addressing: only one byte of data is allowed here", + ); + instruction_err( + "adc ($2002, x), y", + "bad indirect mode, expecting an indirect X-indexed addressing mode", + ); + instruction_err( + "adc ($2002), y", + "when parsing an instruction with indirect Y-indexed addressing: only one byte of data is allowed here", + ); + instruction_err( + "adc ($20, y)", + "the index in indirect X-indexed addressing must be X", + ); + instruction_err( + "adc ($20), x", + "the index in indirect Y-indexed addressing must be Y", + ); + instruction_err("jmp ($20)", "expecting a full 16-bit address"); + instruction_err("adc $20, z", "index is neither X nor Y"); + instruction_err( + "adc ($2000)", + "bad addressing mode 'indirect' for the instruction 'adc'", + ); + } + + #[test] + fn parse_binary() { + instruction_err("adc #%", "missing binary digits to get a full byte"); + instruction_err("adc #%0001", "missing binary digits to get a full byte"); + instruction_err("adc #%0001000", "missing binary digits to get a full byte"); + instruction_err( + "adc #%000100001", + "too many binary digits for a single byte", + ); + instruction_test("adc #%10100010", &[0x69, 0xA2], 2, false, true); + } + + #[test] + fn parse_hexadecimal() { + instruction_err("adc $", "expecting a number of 2/4 hexadecimal digits"); + instruction_err("adc #$", "expecting a number of 2 hexadecimal digits"); + instruction_err("adc $AW", "unknown variable 'AW'"); + instruction_test("adc $AA", &[0x65, 0xAA], 3, false, false); + instruction_test("adc $10", &[0x65, 0x10], 3, false, false); + instruction_test("adc $10AB", &[0x6D, 0xAB, 0x10], 4, false, false); + } + + #[test] + fn parse_decimal() { + instruction_err("adc #", "empty decimal literal"); + instruction_err("adc #256", "decimal value is too big"); + instruction_err("adc #2000", "decimal value is too big"); + instruction_err("adc #2A", "'A' is not a decimal value"); + instruction_test("adc #1", &[0x69, 0x01], 2, false, true); + } + + // Individual instructions. + + #[test] + fn adc() { + instruction_test("adc #20", &[0x69, 0x14], 2, false, true); + instruction_test("adc #$20", &[0x69, 0x20], 2, false, false); + instruction_test("adc $2002", &[0x6D, 0x02, 0x20], 4, false, false); + instruction_test("adc $20", &[0x65, 0x20], 3, false, false); + instruction_test("adc $20, x", &[0x75, 0x20], 4, false, false); + instruction_test("adc $2002, x", &[0x7D, 0x02, 0x20], 4, true, false); + instruction_test("adc $2002, y", &[0x79, 0x02, 0x20], 4, true, false); + instruction_test("adc ($20, x)", &[0x61, 0x20], 6, false, false); + instruction_test("adc ($20), y", &[0x71, 0x20], 5, true, false); + } + + #[test] + fn sbc() { + instruction_test("sbc #$20", &[0xE9, 0x20], 2, false, false); + instruction_test("sbc $2002", &[0xED, 0x02, 0x20], 4, false, false); + instruction_test("sbc $20", &[0xE5, 0x20], 3, false, false); + instruction_test("sbc $20, x", &[0xF5, 0x20], 4, false, false); + instruction_test("sbc $2002, x", &[0xFD, 0x02, 0x20], 4, true, false); + instruction_test("sbc $2002, y", &[0xF9, 0x02, 0x20], 4, true, false); + instruction_test("sbc ($20, x)", &[0xE1, 0x20], 6, false, false); + instruction_test("sbc ($20), y", &[0xF1, 0x20], 5, true, false); + } + + #[test] + fn shift() { + // asl + instruction_test("asl", &[0x0A], 2, false, false); + instruction_test("asl a", &[0x0A], 2, false, true); + instruction_test("asl $20", &[0x06, 0x20], 5, false, false); + instruction_test("asl $20, x", &[0x16, 0x20], 6, false, false); + instruction_test("asl $2002", &[0x0E, 0x02, 0x20], 6, false, false); + instruction_test("asl $2002, x", &[0x1E, 0x02, 0x20], 7, false, false); + + // lsr + instruction_test("lsr", &[0x4A], 2, false, false); + instruction_test("lsr a", &[0x4A], 2, false, true); + instruction_test("lsr $20", &[0x46, 0x20], 5, false, false); + instruction_test("lsr $20, x", &[0x56, 0x20], 6, false, false); + instruction_test("lsr $2002", &[0x4E, 0x02, 0x20], 6, false, false); + instruction_test("lsr $2002, x", &[0x5E, 0x02, 0x20], 7, false, false); + } + + #[test] + fn rotate() { + // rol + instruction_test("rol", &[0x2A], 2, false, false); + instruction_test("rol a", &[0x2A], 2, false, true); + instruction_test("rol $20", &[0x26, 0x20], 5, false, false); + instruction_test("rol $20, x", &[0x36, 0x20], 6, false, false); + instruction_test("rol $2002", &[0x2E, 0x02, 0x20], 6, false, false); + instruction_test("rol $2002, x", &[0x3E, 0x02, 0x20], 7, false, false); + + // ror + instruction_test("ror", &[0x6A], 2, false, false); + instruction_test("ror a", &[0x6A], 2, false, true); + instruction_test("ror $20", &[0x66, 0x20], 5, false, false); + instruction_test("ror $20, x", &[0x76, 0x20], 6, false, false); + instruction_test("ror $2002", &[0x6E, 0x02, 0x20], 6, false, false); + instruction_test("ror $2002, x", &[0x7E, 0x02, 0x20], 7, false, false); + } + + #[test] + fn and() { + instruction_test("and #$20", &[0x29, 0x20], 2, false, false); + instruction_test("and $2002", &[0x2D, 0x02, 0x20], 4, false, false); + instruction_test("and $20", &[0x25, 0x20], 3, false, false); + instruction_test("and $20, x", &[0x35, 0x20], 4, false, false); + instruction_test("and $2002, x", &[0x3D, 0x02, 0x20], 4, true, false); + instruction_test("and $2002, y", &[0x39, 0x02, 0x20], 4, true, false); + instruction_test("and ($20, x)", &[0x21, 0x20], 6, false, false); + instruction_test("and ($20), y", &[0x31, 0x20], 5, true, false); + } + + #[test] + fn or() { + // eor + instruction_test("eor #$20", &[0x49, 0x20], 2, false, false); + instruction_test("eor $20", &[0x45, 0x20], 3, false, false); + instruction_test("eor $20, x", &[0x55, 0x20], 4, false, false); + instruction_test("eor $2002", &[0x4D, 0x02, 0x20], 4, false, false); + instruction_test("eor $2002, x", &[0x5D, 0x02, 0x20], 4, true, false); + instruction_test("eor $2002, y", &[0x59, 0x02, 0x20], 4, true, false); + instruction_test("eor ($20, x)", &[0x41, 0x20], 6, false, false); + instruction_test("eor ($20), y", &[0x51, 0x20], 5, true, false); + + // ora + instruction_test("ora #$20", &[0x09, 0x20], 2, false, false); + instruction_test("ora $20", &[0x05, 0x20], 3, false, false); + instruction_test("ora $20, x", &[0x15, 0x20], 4, false, false); + instruction_test("ora $2002", &[0x0D, 0x02, 0x20], 4, false, false); + instruction_test("ora $2002, x", &[0x1D, 0x02, 0x20], 4, true, false); + instruction_test("ora $2002, y", &[0x19, 0x02, 0x20], 4, true, false); + instruction_test("ora ($20, x)", &[0x01, 0x20], 6, false, false); + instruction_test("ora ($20), y", &[0x11, 0x20], 5, true, false); + } + + #[test] + fn jump() { + instruction_test("jsr $2002", &[0x20, 0x02, 0x20], 6, false, false); + + instruction_test("jmp $2002", &[0x4C, 0x02, 0x20], 3, false, false); + instruction_test("jmp ($2002)", &[0x6C, 0x02, 0x20], 5, false, false); + } + + #[test] + fn inc_dec_instructions() { + // inc + instruction_test("inc $10", &[0xE6, 0x10], 5, false, false); + instruction_test("inc $1000", &[0xEE, 0x00, 0x10], 6, false, false); + instruction_test("inc $10, x", &[0xF6, 0x10], 6, false, false); + instruction_test("inc $1000, x", &[0xFE, 0x00, 0x10], 7, false, false); + + instruction_test("inx", &[0xE8], 2, false, false); + + instruction_test("iny", &[0xC8], 2, false, false); + + // dec + instruction_test("dec $10", &[0xC6, 0x10], 5, false, false); + instruction_test("dec $1000", &[0xCE, 0x00, 0x10], 6, false, false); + instruction_test("dec $10, x", &[0xD6, 0x10], 6, false, false); + instruction_test("dec $1000, x", &[0xDE, 0x00, 0x10], 7, false, false); + + instruction_test("dex", &[0xCA], 2, false, false); + + instruction_test("dey", &[0x88], 2, false, false); + } + + #[test] + fn transfer_instructions() { + instruction_test("tax", &[0xAA], 2, false, false); + instruction_test("tay", &[0xA8], 2, false, false); + instruction_test("tsx", &[0xBA], 2, false, false); + instruction_test("txa", &[0x8A], 2, false, false); + instruction_test("txs", &[0x9A], 2, false, false); + instruction_test("tya", &[0x98], 2, false, false); + } + + #[test] + fn return_instructions() { + instruction_test("rti", &[0x40], 6, false, false); + instruction_test("rts", &[0x60], 6, false, false); + } + + #[test] + fn set_clear_instructions() { + instruction_test("clc", &[0x18], 2, false, false); + instruction_test("cld", &[0xD8], 2, false, false); + instruction_test("cli", &[0x58], 2, false, false); + instruction_test("clv", &[0xB8], 2, false, false); + + instruction_test("sec", &[0x38], 2, false, false); + instruction_test("sed", &[0xF8], 2, false, false); + instruction_test("sei", &[0x78], 2, false, false); + } + + #[test] + fn push_pull_instructions() { + instruction_test("pha", &[0x48], 3, false, false); + instruction_test("php", &[0x08], 3, false, false); + instruction_test("pla", &[0x68], 4, false, false); + instruction_test("plp", &[0x28], 4, false, false); + } + + #[test] + fn nop_brk() { + instruction_test("nop", &[0xEA], 2, false, false); + instruction_test("brk", &[0x00], 7, false, false); + } + + #[test] + fn cmp() { + // cmp + instruction_test("cmp #$20", &[0xC9, 0x20], 2, false, false); + instruction_test("cmp $2002", &[0xCD, 0x02, 0x20], 4, false, false); + instruction_test("cmp $20", &[0xC5, 0x20], 3, false, false); + instruction_test("cmp $20, x", &[0xD5, 0x20], 4, false, false); + instruction_test("cmp $2002, x", &[0xDD, 0x02, 0x20], 4, true, false); + instruction_test("cmp $2002, y", &[0xD9, 0x02, 0x20], 4, true, false); + instruction_test("cmp ($20, x)", &[0xC1, 0x20], 6, false, false); + instruction_test("cmp ($20), y", &[0xD1, 0x20], 5, true, false); + + // cpx + instruction_test("cpx #$20", &[0xE0, 0x20], 2, false, false); + instruction_test("cpx $2002", &[0xEC, 0x02, 0x20], 4, false, false); + instruction_test("cpx $20", &[0xE4, 0x20], 3, false, false); + + // cpy + instruction_test("cpy #$20", &[0xC0, 0x20], 2, false, false); + instruction_test("cpy $2002", &[0xCC, 0x02, 0x20], 4, false, false); + instruction_test("cpy $20", &[0xC4, 0x20], 3, false, false); + } + + #[test] + fn load() { + // lda + instruction_test("lda #$20", &[0xA9, 0x20], 2, false, false); + instruction_test("lda $20", &[0xA5, 0x20], 3, false, false); + instruction_test("lda $20, x", &[0xB5, 0x20], 4, false, false); + instruction_test("lda $2002", &[0xAD, 0x02, 0x20], 4, false, false); + instruction_test("lda $2002, x", &[0xBD, 0x02, 0x20], 4, true, false); + instruction_test("lda $2002, y", &[0xB9, 0x02, 0x20], 4, true, false); + instruction_test("lda ($20, x)", &[0xA1, 0x20], 6, false, false); + instruction_test("lda ($20), y", &[0xB1, 0x20], 5, true, false); + + // ldx + instruction_test("ldx #$20", &[0xA2, 0x20], 2, false, false); + instruction_test("ldx $20", &[0xA6, 0x20], 3, false, false); + instruction_test("ldx $20, y", &[0xB6, 0x20], 4, false, false); + instruction_test("ldx $2002", &[0xAE, 0x02, 0x20], 4, false, false); + instruction_test("ldx $2002, y", &[0xBE, 0x02, 0x20], 4, true, false); + + // ldy + instruction_test("ldy #$20", &[0xA0, 0x20], 2, false, false); + instruction_test("ldy $20", &[0xA4, 0x20], 3, false, false); + instruction_test("ldy $20, x", &[0xB4, 0x20], 4, false, false); + instruction_test("ldy $2002", &[0xAC, 0x02, 0x20], 4, false, false); + instruction_test("ldy $2002, x", &[0xBC, 0x02, 0x20], 4, true, false); + } + + #[test] + fn store_instructions() { + //sta + instruction_test("sta $20", &[0x85, 0x20], 3, false, false); + instruction_test("sta $20, x", &[0x95, 0x20], 4, false, false); + instruction_test("sta $2002", &[0x8D, 0x02, 0x20], 4, false, false); + instruction_test("sta $2002, x", &[0x9D, 0x02, 0x20], 5, false, false); + instruction_test("sta $2002, y", &[0x99, 0x02, 0x20], 5, false, false); + instruction_test("sta ($20, x)", &[0x81, 0x20], 6, false, false); + instruction_test("sta ($20), y", &[0x91, 0x20], 6, false, false); + + // stx + instruction_test("stx $20", &[0x86, 0x20], 3, false, false); + instruction_test("stx $20, y", &[0x96, 0x20], 4, false, false); + instruction_test("stx $2002", &[0x8E, 0x02, 0x20], 4, false, false); + + // sty + instruction_test("sty $20", &[0x84, 0x20], 3, false, false); + instruction_test("sty $20, x", &[0x94, 0x20], 4, false, false); + instruction_test("sty $2002", &[0x8C, 0x02, 0x20], 4, false, false); + } + + #[test] + fn bit() { + instruction_test("bit $10", &[0x24, 0x10], 3, false, false); + instruction_test("bit $1001", &[0x2C, 0x01, 0x10], 4, false, false); + } + + // Variables & scopes. + + #[test] + fn scoped_variable() { + let mut parser = Assembler::new(); + let res = parser + .assemble( + r#" +.scope One ; This is a comment + adc #Variable + + Variable = $20 +.endscope + +.scope Another + Variable = $40 +.endscope + +Variable = $30 +adc #Variable + +adc #One::Variable +adc #Another::Variable +"# + .as_bytes(), + ) + .unwrap(); + + assert_eq!(res.len(), 4); + let instrs: Vec<[u8; 2]> = vec![[0x69, 0x20], [0x69, 0x30], [0x69, 0x20], [0x69, 0x40]]; + + for i in 0..4 { + assert_eq!( + res[i].to_hex(), + instrs[i] + .iter() + .map(|x| format!("{:02X}", x)) + .collect::<Vec<_>>() + ); + } + } + + #[test] + fn redefined_variable() { + let mut parser = Assembler::new(); + let res = parser.assemble( + r#" +.scope One + Variable = 1 +.endscope + +Variable = 1 +Yet = 3 +Yet = 4 +"# + .as_bytes(), + ); + + assert!(res.is_err()); + if let Err(e) = res { + assert_eq!( + e.message, + "variable 'Yet' is being re-assigned: it was previously defined in line 6" + ); + } + } + + #[test] + fn bad_variable_names() { + instruction_err("a = 2", "cannot use reserved name 'a'"); + instruction_err("X = 2", "cannot use reserved name 'X'"); + + instruction_err( + "AA = 2", + "cannot use names which are valid hexadecimal values such as 'AA'", + ); + + instruction_err( + "Scope::Variable = 2", + "the name 'Scope::Variable' is scoped: do not declare variables this way", + ); + } + + #[test] + fn bad_assignment() { + instruction_err("Variable =", "incomplete assignment"); + instruction_err("Variable = ; comment", "incomplete assignment"); + instruction_err("adc = $12", "cannot use 'adc' in an assignment because it's a word reserved for an instruction mnemonic"); + } + + // Literals + + #[test] + fn byte_literals_errors() { + instruction_err( + ".byte $0102", + "when parsing a data literal: only one byte of data is allowed here", + ); + instruction_err(".byte '$01", "non-terminated quote for byte literal"); + instruction_err(".byte '$01, $02", "non-terminated quote for byte literal"); + } + + #[test] + fn byte_literals() { + let mut asm = Assembler::new(); + + let mut res = asm.assemble(".byte $01".as_bytes()).unwrap(); + assert_eq!(res.len(), 1); + assert_hex(res[0], &[0x01]); + + asm.reset(); + res = asm.assemble(".db $01, $02".as_bytes()).unwrap(); + assert_eq!(res.len(), 2); + assert_hex(res[0], &[0x01]); + assert_hex(res[1], &[0x02]); + + asm.reset(); + res = asm + .assemble(".byte $01, 2, '%00000011', \"$04\"".as_bytes()) + .unwrap(); + assert_eq!(res.len(), 4); + assert_hex(res[0], &[0x01]); + assert_hex(res[1], &[0x02]); + assert_hex(res[2], &[0x03]); + assert_hex(res[3], &[0x04]); + } + + #[test] + fn word_literals() { + let mut asm = Assembler::new(); + + let mut res = asm.assemble(".word $01".as_bytes()).unwrap(); + assert_eq!(res.len(), 1); + assert_hex(res[0], &[0x01, 0x00]); + + asm.reset(); + res = asm.assemble(".dw $0102, $02".as_bytes()).unwrap(); + assert_eq!(res.len(), 2); + assert_hex(res[0], &[0x02, 0x01]); + assert_hex(res[1], &[0x02, 0x00]); + + asm.reset(); + res = asm + .assemble(".word $0102, $0204, '$0308', \"$0410\"".as_bytes()) + .unwrap(); + assert_eq!(res.len(), 4); + assert_hex(res[0], &[0x02, 0x01]); + assert_hex(res[1], &[0x04, 0x02]); + assert_hex(res[2], &[0x08, 0x03]); + assert_hex(res[3], &[0x10, 0x04]); + } + + #[test] + fn variables_in_literals() { + let mut asm = Assembler::new(); + let res = asm + .assemble( + r#" +.scope One + Variable = $01 +.endscope + +Variable = $02 +.byte One::Variable, Variable, $03 +"# + .as_bytes(), + ) + .unwrap(); + + assert_eq!(res.len(), 3); + assert_hex(res[0], &[0x01]); + assert_hex(res[1], &[0x02]); + assert_hex(res[2], &[0x03]); + } +} diff --git a/lib/xixanta/src/context.rs b/lib/xixanta/src/context.rs new file mode 100644 index 0000000..62ec7e0 --- /dev/null +++ b/lib/xixanta/src/context.rs @@ -0,0 +1,66 @@ +use crate::instruction::PString; +use std::collections::HashMap; + +const GLOBAL_CONTEXT: &str = "Global"; + +#[derive(Debug)] +pub struct Context { + stack: Vec<String>, + map: HashMap<String, HashMap<String, PString>>, +} + +impl Default for Context { + fn default() -> Self { + Context::new() + } +} + +impl Context { + pub fn new() -> Self { + Context { + stack: vec![], + map: HashMap::from([(String::from(GLOBAL_CONTEXT), HashMap::new())]), + } + } + + pub fn reset(&mut self) { + self.stack = vec![]; + } + + pub fn find(&self, name: &str) -> Option<&HashMap<String, PString>> { + self.map.get(name) + } + + pub fn current(&self) -> Option<&HashMap<String, PString>> { + match self.stack.last() { + Some(name) => self.map.get(name), + None => self.map.get(GLOBAL_CONTEXT), + } + } + + pub fn current_mut(&mut self) -> Option<&mut HashMap<String, PString>> { + match self.stack.last() { + Some(name) => self.map.get_mut(name), + None => self.map.get_mut(GLOBAL_CONTEXT), + } + } + + pub fn push(&mut self, identifier: &String) { + let name = match self.stack.last() { + Some(n) => n.to_owned() + &String::from("::") + identifier, + None => identifier.to_string(), + }; + + self.stack.push(name.clone()); + self.map.entry(name).or_default(); + } + + pub fn pop(&mut self) -> bool { + if self.stack.is_empty() { + return false; + } + + self.stack.truncate(self.stack.len() - 1); + true + } +} diff --git a/lib/xixanta/src/errors.rs b/lib/xixanta/src/errors.rs new file mode 100644 index 0000000..48f7286 --- /dev/null +++ b/lib/xixanta/src/errors.rs @@ -0,0 +1,25 @@ +use std::fmt; + +#[derive(Debug, Clone, PartialEq)] +pub struct ParseError { + pub line: usize, + pub message: String, +} + +impl std::error::Error for ParseError {} + +impl From<std::io::Error> for ParseError { + fn from(err: std::io::Error) -> Self { + // TODO + ParseError { + line: 0, + message: err.to_string(), + } + } +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "parser (line {}): {}.", self.line + 1, self.message) + } +} diff --git a/lib/xixanta/src/instruction.rs b/lib/xixanta/src/instruction.rs new file mode 100644 index 0000000..fac6d8e --- /dev/null +++ b/lib/xixanta/src/instruction.rs @@ -0,0 +1,277 @@ +use crate::errors::ParseError; +use std::fmt; +use std::ops::Range; + +/// PString is a String with position information. +#[derive(Debug, Clone, PartialEq)] +pub struct PString { + pub value: String, + pub line: usize, + pub range: Range<usize>, +} + +impl PString { + pub fn new() -> Self { + PString { + value: String::from(""), + line: 0, + range: Range { start: 0, end: 0 }, + } + } + + pub fn from(value: &str) -> Self { + PString { + value: String::from(value), + line: 0, + range: Range { start: 0, end: 0 }, + } + } + + pub fn parser_error(&self, message: &str) -> ParseError { + // TODO: we can go further :) + ParseError { + line: self.line, + message: String::from(message), + } + } + + pub fn is_reserved(&self) -> bool { + matches!(self.value.to_lowercase().as_str(), "x" | "y" | "a") + } +} + +#[derive(Eq, Hash, PartialEq, Debug, Clone)] +pub enum AddressingMode { + Unknown, + Implied, + Immediate, + Absolute, + RelativeOrZeropage, + IndexedX, + IndexedY, + ZeropageIndexedX, + ZeropageIndexedY, + Indirect, + IndirectX, + IndirectY, +} + +impl fmt::Display for AddressingMode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + AddressingMode::Implied => write!(f, "implied"), + AddressingMode::Immediate => write!(f, "immediate"), + AddressingMode::Absolute => write!(f, "absolute"), + AddressingMode::RelativeOrZeropage => write!(f, "relative or zeropage"), + AddressingMode::IndexedX => write!(f, "indexed by x"), + AddressingMode::IndexedY => write!(f, "indexed by y"), + AddressingMode::ZeropageIndexedX => write!(f, "zeropage indexed by x"), + AddressingMode::ZeropageIndexedY => write!(f, "zeropage indexed by y"), + AddressingMode::Indirect => write!(f, "indirect"), + AddressingMode::IndirectX => write!(f, "indirect indexed by x"), + AddressingMode::IndirectY => write!(f, "indirect indexed by y"), + _ => write!(f, "unknown"), + } + } +} + +/// Encodable is a trait to be implemented by those structs that might need to +/// be encoded into the outside world. That is, structures that make sense to +/// output into files or other output streams. +pub trait Encodable { + /// Returns a fixed array of bytes which belong to an encodable object. Note + /// that the capacity is fixed, but the actual size must be checked with the + /// `size` trait function, otherwise elements beyond that size might contain + /// junk. + fn to_bytes(&self) -> [u8; 3]; + + /// Returns the actual size of the data returned by `to_bytes`. + fn size(&self) -> u8; + + /// Returns a vector which contains the exact byte data for the given + /// object. In contrast with `to_bytes`, the caller does not need to check + /// for `size`: the returned vector is tailored to the exact amount of + /// bytes for the object. + fn to_hex(&self) -> Vec<String>; + + /// Returns a string representation which makes sense to a human (e.g. + /// instead of providing the byte encoded opcode for an instruction, show + /// the mnemonic). + fn to_human(&self) -> String; + + /// Returns a string representation with higher verbosity than `to_human`. + fn to_verbose(&self) -> String; +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Instruction { + pub mnemonic: PString, + pub opcode: u8, + pub bytes: [u8; 2], + pub size: u8, + pub left: Option<PString>, + pub right: Option<PString>, + pub mode: AddressingMode, + pub cycles: u8, + pub affected_on_page: bool, +} + +impl Instruction { + pub fn unknown() -> Instruction { + Instruction { + mnemonic: PString::new(), + opcode: 0, + bytes: [0, 0], + size: 0, + left: None, + right: None, + mode: AddressingMode::Unknown, + cycles: 0, + affected_on_page: false, + } + } + + pub fn from(mnemonic: &str) -> Instruction { + Instruction { + mnemonic: PString::from(mnemonic), + opcode: 0, + bytes: [0, 0], + size: 0, + left: None, + right: None, + mode: AddressingMode::Unknown, + cycles: 0, + affected_on_page: false, + } + } +} + +impl Encodable for Instruction { + fn size(&self) -> u8 { + self.size + } + + fn to_hex(&self) -> Vec<String> { + let mut ret = vec![]; + + ret.push(format!("{:02X}", self.opcode)); + if self.size > 1 { + ret.push(format!("{:02X}", self.bytes[0])); + } + if self.size == 3 { + ret.push(format!("{:02X}", self.bytes[1])); + } + + ret + } + + fn to_bytes(&self) -> [u8; 3] { + [self.opcode.to_le_bytes()[0], self.bytes[0], self.bytes[1]] + } + + fn to_human(&self) -> String { + match self.mode { + AddressingMode::Implied => self.mnemonic.value.clone(), + AddressingMode::Immediate => format!("{} #${:02X}", self.mnemonic.value, self.bytes[0]), + AddressingMode::Absolute => format!( + "{} ${:02X}{:02X}", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::RelativeOrZeropage => { + format!("{} ${:02X}", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::IndexedX => format!( + "{} ${:02X}{:02X}, x", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::IndexedY => format!( + "{} ${:02X}{:02X}, y", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::ZeropageIndexedX => { + format!("{} ${:02X}, x", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::ZeropageIndexedY => { + format!("{} ${:02X}, y", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::Indirect => format!( + "{} (${:02X}{:02X})", + self.mnemonic.value, self.bytes[1], self.bytes[0] + ), + AddressingMode::IndirectX => { + format!("{} (${:02X}, x)", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::IndirectY => { + format!("{} (${:02X}), y", self.mnemonic.value, self.bytes[0]) + } + AddressingMode::Unknown => String::from("unknown instruction"), + } + } + + fn to_verbose(&self) -> String { + format!("{:#?}", self) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Generic { + pub identifier: PString, + pub left: Option<PString>, + pub right: Option<PString>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Scoped { + pub identifier: PString, + pub start: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Literal { + pub identifier: PString, + pub bytes: [u8; 2], + pub size: u8, +} + +impl Encodable for Literal { + fn size(&self) -> u8 { + self.size + } + + fn to_hex(&self) -> Vec<String> { + let mut ret = vec![]; + + ret.push(format!("{:02X}", self.bytes[0])); + if self.size == 2 { + ret.push(format!("{:02X}", self.bytes[1])); + } else if self.size != 1 { + panic!("size for literal should be either 1 or 2"); + } + + ret + } + + fn to_bytes(&self) -> [u8; 3] { + [self.bytes[0], self.bytes[1], 0] + } + + fn to_human(&self) -> String { + match self.size { + 1 => format!(".byte ${:02X}", self.bytes[0]), + 2 => format!(".byte ${:02X}{:02X}", self.bytes[1], self.bytes[0]), + _ => String::from("unknown literal"), + } + } + + fn to_verbose(&self) -> String { + format!("{:#?}", self) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Node { + Generic(Generic), + Instruction(Instruction), + Scoped(Scoped), + Literal(Literal), +} diff --git a/lib/xixanta/src/lib.rs b/lib/xixanta/src/lib.rs new file mode 100644 index 0000000..fc8ca96 --- /dev/null +++ b/lib/xixanta/src/lib.rs @@ -0,0 +1,10 @@ +#[macro_use] +extern crate lazy_static; + +// TODO: be more mindful on what's exported outside. + +pub mod assembler; +mod context; +mod errors; +pub mod instruction; +mod opcodes; diff --git a/lib/xixanta/src/opcodes.rs b/lib/xixanta/src/opcodes.rs new file mode 100644 index 0000000..bca8104 --- /dev/null +++ b/lib/xixanta/src/opcodes.rs @@ -0,0 +1,631 @@ +use crate::instruction::AddressingMode; +use std::collections::HashMap; + +#[derive(Debug)] +pub struct ShortEntry { + pub cycles: u8, + pub opcode: u8, + pub size: u8, + pub affected_on_page: bool, +} + +#[derive(Debug)] +pub struct Entry { + pub mode: AddressingMode, + pub mnemonic: String, + pub cycles: u8, + pub opcode: u8, + pub size: u8, + pub affected_on_page: bool, +} + +lazy_static! { + // TODO + pub static ref INSTRUCTIONS: HashMap<String, HashMap<AddressingMode, ShortEntry>> = { + let mut instrs = HashMap::new(); + + // adc + let mut adc = HashMap::new(); + adc.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x69, affected_on_page: false }); + adc.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x65, affected_on_page: false }); + adc.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x75, affected_on_page: false }); + adc.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x6D, affected_on_page: false }); + adc.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x7D, affected_on_page: true }); + adc.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x79, affected_on_page: true }); + adc.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x61, affected_on_page: false }); + adc.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x71, affected_on_page: true }); + instrs.insert(String::from("adc"), adc); + + // and + let mut and = HashMap::new(); + and.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x29, affected_on_page: false }); + and.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x25, affected_on_page: false }); + and.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x35, affected_on_page: false }); + and.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x2D, affected_on_page: false }); + and.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x3D, affected_on_page: true }); + and.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x39, affected_on_page: true }); + and.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x21, affected_on_page: false }); + and.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x31, affected_on_page: true }); + instrs.insert(String::from("and"), and); + + // asl + let mut asl = HashMap::new(); + asl.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x0A, affected_on_page: false }); + asl.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x06, affected_on_page: false }); + asl.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x16, affected_on_page: false }); + asl.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x0E, affected_on_page: false }); + asl.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x1E, affected_on_page: false }); + instrs.insert(String::from("asl"), asl); + + // BCC: TODO + // BCS: TODO + // BEQ: TODO + + // bit + let mut bit = HashMap::new(); + bit.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x24, affected_on_page: false }); + bit.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x2C, affected_on_page: false }); + instrs.insert(String::from("bit"), bit); + + // BMI: TODO + // BNE: TODO + // BPL: TODO + + // brk + let mut brk = HashMap::new(); + brk.insert(AddressingMode::Implied, ShortEntry{ cycles: 7, size: 1, opcode: 0x00, affected_on_page: false }); + instrs.insert(String::from("brk"), brk); + + // BVC: TODO + // BVS: TODO + + // clc + let mut clc = HashMap::new(); + clc.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x18, affected_on_page: false }); + instrs.insert(String::from("clc"), clc); + + // cld + let mut cld = HashMap::new(); + cld.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xD8, affected_on_page: false }); + instrs.insert(String::from("cld"), cld); + + // cli + let mut cli = HashMap::new(); + cli.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x58, affected_on_page: false }); + instrs.insert(String::from("cli"), cli); + + // clv + let mut clv = HashMap::new(); + clv.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xB8, affected_on_page: false }); + instrs.insert(String::from("clv"), clv); + + // cmp + let mut cmp = HashMap::new(); + cmp.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xC9, affected_on_page: false }); + cmp.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xC5, affected_on_page: false }); + cmp.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xD5, affected_on_page: false }); + cmp.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xCD, affected_on_page: false }); + cmp.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xDD, affected_on_page: true }); + cmp.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xD9, affected_on_page: true }); + cmp.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0xC1, affected_on_page: false }); + cmp.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0xD1, affected_on_page: true }); + instrs.insert(String::from("cmp"), cmp); + + // cpx + let mut cpx = HashMap::new(); + cpx.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xE0, affected_on_page: false }); + cpx.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xE4, affected_on_page: false }); + cpx.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xEC, affected_on_page: false }); + instrs.insert(String::from("cpx"), cpx); + + // cpy + let mut cpy = HashMap::new(); + cpy.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xC0, affected_on_page: false }); + cpy.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xC4, affected_on_page: false }); + cpy.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xCC, affected_on_page: false }); + instrs.insert(String::from("cpy"), cpy); + + // dec + let mut dec = HashMap::new(); + dec.insert(AddressingMode::RelativeOrZeropage, ShortEntry { cycles: 5, size: 2, opcode: 0xC6, affected_on_page: false }); + dec.insert(AddressingMode::ZeropageIndexedX, ShortEntry { cycles: 6, size: 2, opcode: 0xD6, affected_on_page: false }); + dec.insert(AddressingMode::Absolute, ShortEntry { cycles: 6, size: 3, opcode: 0xCE, affected_on_page: false }); + dec.insert(AddressingMode::IndexedX, ShortEntry { cycles: 7, size: 3, opcode: 0xDE, affected_on_page: false }); + instrs.insert(String::from("dec"), dec); + + // dex + let mut dex = HashMap::new(); + dex.insert(AddressingMode::Implied, ShortEntry { cycles: 2, size: 1, opcode: 0xCA, affected_on_page: false }); + instrs.insert(String::from("dex"), dex); + + // dey + let mut dey = HashMap::new(); + dey.insert(AddressingMode::Implied, ShortEntry { cycles: 2, size: 1, opcode: 0x88, affected_on_page: false }); + instrs.insert(String::from("dey"), dey); + + // eor + let mut eor = HashMap::new(); + eor.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x49, affected_on_page: false }); + eor.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x45, affected_on_page: false }); + eor.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x55, affected_on_page: false }); + eor.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x4D, affected_on_page: false }); + eor.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x5D, affected_on_page: true }); + eor.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x59, affected_on_page: true }); + eor.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x41, affected_on_page: false }); + eor.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x51, affected_on_page: true }); + instrs.insert(String::from("eor"), eor); + + // inc + let mut inc = HashMap::new(); + inc.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0xE6, affected_on_page: false }); + inc.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0xF6, affected_on_page: false }); + inc.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0xEE, affected_on_page: false }); + inc.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0xFE, affected_on_page: false }); + instrs.insert(String::from("inc"), inc); + + // inx + let mut inx = HashMap::new(); + inx.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xE8, affected_on_page: false }); + instrs.insert(String::from("inx"), inx); + + // iny + let mut iny = HashMap::new(); + iny.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xC8, affected_on_page: false }); + instrs.insert(String::from("iny"), iny); + + // jmp + let mut jmp = HashMap::new(); + jmp.insert(AddressingMode::Absolute, ShortEntry{ cycles: 3, size: 3, opcode: 0x4C, affected_on_page: false }); + jmp.insert(AddressingMode::Indirect, ShortEntry{ cycles: 5, size: 3, opcode: 0x6C, affected_on_page: false }); + instrs.insert(String::from("jmp"), jmp); + + // jsr + let mut jsr = HashMap::new(); + jsr.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x20, affected_on_page: false }); + instrs.insert(String::from("jsr"), jsr); + + // lda + let mut lda = HashMap::new(); + lda.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xA9, affected_on_page: false }); + lda.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xA5, affected_on_page: false }); + lda.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xB5, affected_on_page: false }); + lda.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xAD, affected_on_page: false }); + lda.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xBD, affected_on_page: true }); + lda.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xB9, affected_on_page: true }); + lda.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0xA1, affected_on_page: false }); + lda.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0xB1, affected_on_page: true }); + instrs.insert(String::from("lda"), lda); + + // ldx + let mut ldx = HashMap::new(); + ldx.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xA2, affected_on_page: false }); + ldx.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xA6, affected_on_page: false }); + ldx.insert(AddressingMode::ZeropageIndexedY, ShortEntry{ cycles: 4, size: 2, opcode: 0xB6, affected_on_page: false }); + ldx.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xAE, affected_on_page: false }); + ldx.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xBE, affected_on_page: true }); + instrs.insert(String::from("ldx"), ldx); + + // ldy + let mut ldy = HashMap::new(); + ldy.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xA0, affected_on_page: false }); + ldy.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xA4, affected_on_page: false }); + ldy.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xB4, affected_on_page: false }); + ldy.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xAC, affected_on_page: false }); + ldy.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xBC, affected_on_page: true }); + instrs.insert(String::from("ldy"), ldy); + + // lsr + let mut lsr = HashMap::new(); + lsr.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x4A, affected_on_page: false }); + lsr.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x46, affected_on_page: false }); + lsr.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x56, affected_on_page: false }); + lsr.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x4E, affected_on_page: false }); + lsr.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x5E, affected_on_page: false }); + instrs.insert(String::from("lsr"), lsr); + + // nop + let mut nop = HashMap::new(); + nop.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xEA, affected_on_page: false }); + instrs.insert(String::from("nop"), nop); + + // ora + let mut ora = HashMap::new(); + ora.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0x09, affected_on_page: false }); + ora.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x05, affected_on_page: false }); + ora.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x15, affected_on_page: false }); + ora.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x0D, affected_on_page: false }); + ora.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0x1D, affected_on_page: true }); + ora.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0x19, affected_on_page: true }); + ora.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x01, affected_on_page: false }); + ora.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0x11, affected_on_page: true }); + instrs.insert(String::from("ora"), ora); + + // pha + let mut pha = HashMap::new(); + pha.insert(AddressingMode::Implied, ShortEntry{ cycles: 3, size: 1, opcode: 0x48, affected_on_page: false }); + instrs.insert(String::from("pha"), pha); + + // php + let mut php = HashMap::new(); + php.insert(AddressingMode::Implied, ShortEntry{ cycles: 3, size: 1, opcode: 0x08, affected_on_page: false }); + instrs.insert(String::from("php"), php); + + // pla + let mut pla = HashMap::new(); + pla.insert(AddressingMode::Implied, ShortEntry{ cycles: 4, size: 1, opcode: 0x68, affected_on_page: false }); + instrs.insert(String::from("pla"), pla); + + // plp + let mut plp = HashMap::new(); + plp.insert(AddressingMode::Implied, ShortEntry{ cycles: 4, size: 1, opcode: 0x28, affected_on_page: false }); + instrs.insert(String::from("plp"), plp); + + // rol + let mut rol = HashMap::new(); + rol.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x2A, affected_on_page: false }); + rol.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x26, affected_on_page: false }); + rol.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x36, affected_on_page: false }); + rol.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x2E, affected_on_page: false }); + rol.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x3E, affected_on_page: false }); + instrs.insert(String::from("rol"), rol); + + // ror + let mut ror = HashMap::new(); + ror.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x6A, affected_on_page: false }); + ror.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 5, size: 2, opcode: 0x66, affected_on_page: false }); + ror.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 6, size: 2, opcode: 0x76, affected_on_page: false }); + ror.insert(AddressingMode::Absolute, ShortEntry{ cycles: 6, size: 3, opcode: 0x6E, affected_on_page: false }); + ror.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 7, size: 3, opcode: 0x7E, affected_on_page: false }); + instrs.insert(String::from("ror"), ror); + + // rti + let mut rti = HashMap::new(); + rti.insert(AddressingMode::Implied, ShortEntry{ cycles: 6, size: 1, opcode: 0x40, affected_on_page: false }); + instrs.insert(String::from("rti"), rti); + + // rts + let mut rts = HashMap::new(); + rts.insert(AddressingMode::Implied, ShortEntry{ cycles: 6, size: 1, opcode: 0x60, affected_on_page: false }); + instrs.insert(String::from("rts"), rts); + + // sbc + let mut sbc = HashMap::new(); + sbc.insert(AddressingMode::Immediate, ShortEntry{ cycles: 2, size: 2, opcode: 0xE9, affected_on_page: false }); + sbc.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0xE5, affected_on_page: false }); + sbc.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0xF5, affected_on_page: false }); + sbc.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0xED, affected_on_page: false }); + sbc.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 4, size: 3, opcode: 0xFD, affected_on_page: true }); + sbc.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 4, size: 3, opcode: 0xF9, affected_on_page: true }); + sbc.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0xE1, affected_on_page: false }); + sbc.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 5, size: 2, opcode: 0xF1, affected_on_page: true }); + instrs.insert(String::from("sbc"), sbc); + + // sec + let mut sec = HashMap::new(); + sec.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x38, affected_on_page: false }); + instrs.insert(String::from("sec"), sec); + + // sed + let mut sed = HashMap::new(); + sed.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xF8, affected_on_page: false }); + instrs.insert(String::from("sed"), sed); + + // sei + let mut sei = HashMap::new(); + sei.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x78, affected_on_page: false }); + instrs.insert(String::from("sei"), sei); + + // sta + let mut sta = HashMap::new(); + sta.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x85, affected_on_page: false }); + sta.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x95, affected_on_page: false }); + sta.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x8D, affected_on_page: false }); + sta.insert(AddressingMode::IndexedX, ShortEntry{ cycles: 5, size: 3, opcode: 0x9D, affected_on_page: false }); + sta.insert(AddressingMode::IndexedY, ShortEntry{ cycles: 5, size: 3, opcode: 0x99, affected_on_page: false }); + sta.insert(AddressingMode::IndirectX, ShortEntry{ cycles: 6, size: 2, opcode: 0x81, affected_on_page: false }); + sta.insert(AddressingMode::IndirectY, ShortEntry{ cycles: 6, size: 2, opcode: 0x91, affected_on_page: false }); + instrs.insert(String::from("sta"), sta); + + // stx + let mut stx = HashMap::new(); + stx.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x86, affected_on_page: false }); + stx.insert(AddressingMode::ZeropageIndexedY, ShortEntry{ cycles: 4, size: 2, opcode: 0x96, affected_on_page: false }); + stx.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x8E, affected_on_page: false }); + instrs.insert(String::from("stx"), stx); + + // sty + let mut sty = HashMap::new(); + sty.insert(AddressingMode::RelativeOrZeropage, ShortEntry{ cycles: 3, size: 2, opcode: 0x84, affected_on_page: false }); + sty.insert(AddressingMode::ZeropageIndexedX, ShortEntry{ cycles: 4, size: 2, opcode: 0x94, affected_on_page: false }); + sty.insert(AddressingMode::Absolute, ShortEntry{ cycles: 4, size: 3, opcode: 0x8C, affected_on_page: false }); + instrs.insert(String::from("sty"), sty); + + // tax + let mut tax = HashMap::new(); + tax.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xAA, affected_on_page: false }); + instrs.insert(String::from("tax"), tax); + + // tay + let mut tay = HashMap::new(); + tay.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xA8, affected_on_page: false }); + instrs.insert(String::from("tay"), tay); + + // tsx + let mut tsx = HashMap::new(); + tsx.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0xBA, affected_on_page: false }); + instrs.insert(String::from("tsx"), tsx); + + // txa + let mut txa = HashMap::new(); + txa.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x8A, affected_on_page: false }); + instrs.insert(String::from("txa"), txa); + + // txs + let mut txs = HashMap::new(); + txs.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x9A, affected_on_page: false }); + instrs.insert(String::from("txs"), txs); + + // tya + let mut tya = HashMap::new(); + tya.insert(AddressingMode::Implied, ShortEntry{ cycles: 2, size: 1, opcode: 0x98, affected_on_page: false }); + instrs.insert(String::from("tya"), tya); + + instrs + }; + + pub static ref OPCODES: HashMap<u8, Entry> = { + let mut opcodes = HashMap::new(); + + // adc + opcodes.insert(0x69, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("adc"), cycles: 2, size: 2, opcode: 0x69, affected_on_page: false }); + opcodes.insert(0x65, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("adc"), cycles: 3, size: 2, opcode: 0x65, affected_on_page: false }); + opcodes.insert(0x75, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("adc"), cycles: 4, size: 2, opcode: 0x75, affected_on_page: false }); + opcodes.insert(0x7D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("adc"), cycles: 4, size: 3, opcode: 0x7D, affected_on_page: true }); + opcodes.insert(0x79, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("adc"), cycles: 4, size: 3, opcode: 0x79, affected_on_page: true }); + opcodes.insert(0x61, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("adc"), cycles: 6, size: 2, opcode: 0x61, affected_on_page: false }); + opcodes.insert(0x71, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("adc"), cycles: 5, size: 2, opcode: 0x71, affected_on_page: true }); + opcodes.insert(0x6D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("adc"), cycles: 4, size: 3, opcode: 0x6D, affected_on_page: false }); + + // and + opcodes.insert(0x29, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("and"), cycles: 2, size: 2, opcode: 0x29, affected_on_page: false }); + opcodes.insert(0x25, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("and"), cycles: 3, size: 2, opcode: 0x25, affected_on_page: false }); + opcodes.insert(0x35, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("and"), cycles: 4, size: 2, opcode: 0x35, affected_on_page: false }); + opcodes.insert(0x2D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("and"), cycles: 4, size: 3, opcode: 0x2D, affected_on_page: false }); + opcodes.insert(0x3D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("and"), cycles: 4, size: 3, opcode: 0x3D, affected_on_page: true }); + opcodes.insert(0x39, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("and"), cycles: 4, size: 3, opcode: 0x39, affected_on_page: true }); + opcodes.insert(0x21, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("and"), cycles: 6, size: 2, opcode: 0x21, affected_on_page: false }); + opcodes.insert(0x31, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("and"), cycles: 5, size: 2, opcode: 0x31, affected_on_page: true }); + + // asl + opcodes.insert(0x0A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("asl"), cycles: 2, size: 1, opcode: 0x0A, affected_on_page: false }); + opcodes.insert(0x06, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("asl"), cycles: 5, size: 2, opcode: 0x06, affected_on_page: false }); + opcodes.insert(0x16, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("asl"), cycles: 6, size: 2, opcode: 0x16, affected_on_page: false }); + opcodes.insert(0x0E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("asl"), cycles: 6, size: 3, opcode: 0x0E, affected_on_page: false }); + opcodes.insert(0x1E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("asl"), cycles: 7, size: 3, opcode: 0x1E, affected_on_page: false }); + + // BCC + // BCS + // BEQ + + // bit + opcodes.insert(0x24, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("bit"), cycles: 3, size: 2, opcode: 0x24, affected_on_page: false }); + opcodes.insert(0x2C, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("bit"), cycles: 4, size: 3, opcode: 0x2C, affected_on_page: false }); + + // BMI + // BNE + // BPL + + // brk + opcodes.insert(0x00, Entry { mode: AddressingMode::Implied, mnemonic: String::from("brk"), cycles: 7, size: 1, opcode: 0x00, affected_on_page: false }); + + // BVC + // BVS + + // clc + opcodes.insert(0x18, Entry { mode: AddressingMode::Implied, mnemonic: String::from("clc"), cycles: 2, size: 1, opcode: 0x18, affected_on_page: false }); + + // cld + opcodes.insert(0xD8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("cld"), cycles: 2, size: 1, opcode: 0xD8, affected_on_page: false }); + + // cli + opcodes.insert(0x58, Entry { mode: AddressingMode::Implied, mnemonic: String::from("cli"), cycles: 2, size: 1, opcode: 0x58, affected_on_page: false }); + + // clv + opcodes.insert(0xB8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("clv"), cycles: 2, size: 1, opcode: 0xB8, affected_on_page: false }); + + // cmp + opcodes.insert(0xC9, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("cmp"), cycles: 2, size: 2, opcode: 0xC9, affected_on_page: false }); + opcodes.insert(0xC5, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("cmp"), cycles: 3, size: 2, opcode: 0xC5, affected_on_page: false }); + opcodes.insert(0xD5, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("cmp"), cycles: 4, size: 2, opcode: 0xD5, affected_on_page: false }); + opcodes.insert(0xCD, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("cmp"), cycles: 4, size: 3, opcode: 0xCD, affected_on_page: false }); + opcodes.insert(0xDD, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("cmp"), cycles: 4, size: 3, opcode: 0xDD, affected_on_page: true }); + opcodes.insert(0xD9, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("cmp"), cycles: 4, size: 3, opcode: 0xD9, affected_on_page: true }); + opcodes.insert(0xC1, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("cmp"), cycles: 6, size: 2, opcode: 0xC1, affected_on_page: false }); + opcodes.insert(0xD1, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("cmp"), cycles: 5, size: 2, opcode: 0xD1, affected_on_page: true }); + + // cpx + opcodes.insert(0xE0, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("cpx"), cycles: 2, size: 2, opcode: 0xE0, affected_on_page: false }); + opcodes.insert(0xE4, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("cpx"), cycles: 3, size: 2, opcode: 0xE4, affected_on_page: false }); + opcodes.insert(0xEC, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("cpx"), cycles: 4, size: 3, opcode: 0xEC, affected_on_page: false }); + + // cpy + opcodes.insert(0xC0, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("cpy"), cycles: 2, size: 2, opcode: 0xC0, affected_on_page: false }); + opcodes.insert(0xC4, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("cpy"), cycles: 3, size: 2, opcode: 0xC4, affected_on_page: false }); + opcodes.insert(0xCC, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("cpy"), cycles: 4, size: 3, opcode: 0xCC, affected_on_page: false }); + + // dec + opcodes.insert(0xC6, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("dec"), cycles: 5, size: 2, opcode: 0xC6, affected_on_page: false }); + opcodes.insert(0xD6, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("dec"), cycles: 6, size: 2, opcode: 0xD6, affected_on_page: false }); + opcodes.insert(0xCE, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("dec"), cycles: 6, size: 3, opcode: 0xCE, affected_on_page: false }); + opcodes.insert(0xDE, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("dec"), cycles: 7, size: 3, opcode: 0xDE, affected_on_page: false }); + + // dex + opcodes.insert(0xCA, Entry { mode: AddressingMode::Implied, mnemonic: String::from("dex"), cycles: 2, size: 1, opcode: 0xCA, affected_on_page: false }); + + // dey + opcodes.insert(0x88, Entry { mode: AddressingMode::Implied, mnemonic: String::from("dey"), cycles: 2, size: 1, opcode: 0x88, affected_on_page: false }); + + // eor + opcodes.insert(0x49, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("eor"), cycles: 2, size: 2, opcode: 0x49, affected_on_page: false }); + opcodes.insert(0x45, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("eor"), cycles: 3, size: 2, opcode: 0x45, affected_on_page: false }); + opcodes.insert(0x55, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("eor"), cycles: 4, size: 2, opcode: 0x55, affected_on_page: false }); + opcodes.insert(0x4D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("eor"), cycles: 4, size: 3, opcode: 0x4D, affected_on_page: false }); + opcodes.insert(0x5D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("eor"), cycles: 4, size: 3, opcode: 0x5D, affected_on_page: true }); + opcodes.insert(0x59, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("eor"), cycles: 4, size: 3, opcode: 0x59, affected_on_page: true }); + opcodes.insert(0x41, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("eor"), cycles: 6, size: 2, opcode: 0x41, affected_on_page: false }); + opcodes.insert(0x51, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("eor"), cycles: 5, size: 2, opcode: 0x51, affected_on_page: true }); + + // inc + opcodes.insert(0xE6, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("inc"), cycles: 5, size: 2, opcode: 0xE6, affected_on_page: false }); + opcodes.insert(0xF6, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("inc"), cycles: 6, size: 2, opcode: 0xF6, affected_on_page: false }); + opcodes.insert(0xEE, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("inc"), cycles: 6, size: 3, opcode: 0xEE, affected_on_page: false }); + opcodes.insert(0xFE, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("inc"), cycles: 7, size: 3, opcode: 0xFE, affected_on_page: false }); + + // inx + opcodes.insert(0xE8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("inx"), cycles: 2, size: 1, opcode: 0xE8, affected_on_page: false }); + + // iny + opcodes.insert(0xC8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("iny"), cycles: 2, size: 1, opcode: 0xC8, affected_on_page: false }); + + // jmp + opcodes.insert(0x4C, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("jmp"), cycles: 3, size: 3, opcode: 0x4C, affected_on_page: false }); + opcodes.insert(0x6C, Entry { mode: AddressingMode::Indirect, mnemonic: String::from("jmp"), cycles: 5, size: 3, opcode: 0x6C, affected_on_page: false }); + + // jsr + opcodes.insert(0x20, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("jsr"), cycles: 6, size: 3, opcode: 0x20, affected_on_page: false }); + + // lda + opcodes.insert(0xA9, Entry{ mode: AddressingMode::Immediate, mnemonic: String::from("lda"), cycles: 2, size: 2, opcode: 0xA9, affected_on_page: false }); + opcodes.insert(0xA5, Entry{ mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("lda"), cycles: 3, size: 2, opcode: 0xA5, affected_on_page: false }); + opcodes.insert(0xB5, Entry{ mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("lda"), cycles: 4, size: 2, opcode: 0xB5, affected_on_page: false }); + opcodes.insert(0xAD, Entry{ mode: AddressingMode::Absolute, mnemonic: String::from("lda"), cycles: 4, size: 3, opcode: 0xAD, affected_on_page: false }); + opcodes.insert(0xBD, Entry{ mode: AddressingMode::IndexedX, mnemonic: String::from("lda"), cycles: 4, size: 3, opcode: 0xBD, affected_on_page: true }); + opcodes.insert(0xB9, Entry{ mode: AddressingMode::IndexedY, mnemonic: String::from("lda"), cycles: 4, size: 3, opcode: 0xB9, affected_on_page: true }); + opcodes.insert(0xA1, Entry{ mode: AddressingMode::IndirectX, mnemonic: String::from("lda"), cycles: 6, size: 2, opcode: 0xA1, affected_on_page: false }); + opcodes.insert(0xB1, Entry{ mode: AddressingMode::IndirectY, mnemonic: String::from("lda"), cycles: 5, size: 2, opcode: 0xB1, affected_on_page: true }); + + // ldx + opcodes.insert(0xA2, Entry{ mode: AddressingMode::Immediate, mnemonic: String::from("ldx"), cycles: 2, size: 2, opcode: 0xA2, affected_on_page: false }); + opcodes.insert(0xA6, Entry{ mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ldx"), cycles: 3, size: 2, opcode: 0xA6, affected_on_page: false }); + opcodes.insert(0xB6, Entry{ mode: AddressingMode::ZeropageIndexedY, mnemonic: String::from("ldx"), cycles: 4, size: 2, opcode: 0xB6, affected_on_page: false }); + opcodes.insert(0xAE, Entry{ mode: AddressingMode::Absolute, mnemonic: String::from("ldx"), cycles: 4, size: 3, opcode: 0xAE, affected_on_page: false }); + opcodes.insert(0xBE, Entry{ mode: AddressingMode::IndexedY, mnemonic: String::from("ldx"), cycles: 4, size: 3, opcode: 0xBE, affected_on_page: true }); + + // ldy + opcodes.insert(0xA0, Entry{ mode: AddressingMode::Immediate, mnemonic: String::from("ldy"), cycles: 2, size: 2, opcode: 0xA0, affected_on_page: false }); + opcodes.insert(0xA4, Entry{ mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ldy"), cycles: 3, size: 2, opcode: 0xA4, affected_on_page: false }); + opcodes.insert(0xB4, Entry{ mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("ldy"), cycles: 4, size: 2, opcode: 0xB4, affected_on_page: false }); + opcodes.insert(0xAC, Entry{ mode: AddressingMode::Absolute, mnemonic: String::from("ldy"), cycles: 4, size: 3, opcode: 0xAC, affected_on_page: false }); + opcodes.insert(0xBC, Entry{ mode: AddressingMode::IndexedX, mnemonic: String::from("ldy"), cycles: 4, size: 3, opcode: 0xBC, affected_on_page: true }); + + // lsr + opcodes.insert(0x4A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("lsr"), cycles: 2, size: 1, opcode: 0x4A, affected_on_page: false }); + opcodes.insert(0x46, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("lsr"), cycles: 5, size: 2, opcode: 0x46, affected_on_page: false }); + opcodes.insert(0x56, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("lsr"), cycles: 6, size: 2, opcode: 0x56, affected_on_page: false }); + opcodes.insert(0x4E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("lsr"), cycles: 6, size: 3, opcode: 0x4E, affected_on_page: false }); + opcodes.insert(0x5E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("lsr"), cycles: 7, size: 3, opcode: 0x5E, affected_on_page: false }); + + // nop + opcodes.insert(0xEA, Entry { mode: AddressingMode::Implied, mnemonic: String::from("nop"), cycles: 2, size: 1, opcode: 0xEA, affected_on_page: false }); + + // ora + opcodes.insert(0x09, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("ora"), cycles: 2, size: 2, opcode: 0x09, affected_on_page: false }); + opcodes.insert(0x05, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ora"), cycles: 3, size: 2, opcode: 0x05, affected_on_page: false }); + opcodes.insert(0x15, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("ora"), cycles: 4, size: 2, opcode: 0x15, affected_on_page: false }); + opcodes.insert(0x0D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("ora"), cycles: 4, size: 3, opcode: 0x0D, affected_on_page: false }); + opcodes.insert(0x1D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("ora"), cycles: 4, size: 3, opcode: 0x1D, affected_on_page: true }); + opcodes.insert(0x19, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("ora"), cycles: 4, size: 3, opcode: 0x19, affected_on_page: true }); + opcodes.insert(0x01, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("ora"), cycles: 6, size: 2, opcode: 0x01, affected_on_page: false }); + opcodes.insert(0x11, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("ora"), cycles: 5, size: 2, opcode: 0x11, affected_on_page: true }); + + // pha + opcodes.insert(0x48, Entry { mode: AddressingMode::Implied, mnemonic: String::from("pha"), cycles: 3, size: 1, opcode: 0x48, affected_on_page: false }); + + // php + opcodes.insert(0x08, Entry { mode: AddressingMode::Implied, mnemonic: String::from("php"), cycles: 3, size: 1, opcode: 0x08, affected_on_page: false }); + + // pla + opcodes.insert(0x68, Entry { mode: AddressingMode::Implied, mnemonic: String::from("pla"), cycles: 4, size: 1, opcode: 0x68, affected_on_page: false }); + + // plp + opcodes.insert(0x28, Entry { mode: AddressingMode::Implied, mnemonic: String::from("plp"), cycles: 4, size: 1, opcode: 0x28, affected_on_page: false }); + + // rol + opcodes.insert(0x2A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("rol"), cycles: 2, size: 1, opcode: 0x2A, affected_on_page: false }); + opcodes.insert(0x26, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("rol"), cycles: 5, size: 2, opcode: 0x26, affected_on_page: false }); + opcodes.insert(0x36, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("rol"), cycles: 6, size: 2, opcode: 0x36, affected_on_page: false }); + opcodes.insert(0x2E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("rol"), cycles: 6, size: 3, opcode: 0x2E, affected_on_page: false }); + opcodes.insert(0x3E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("rol"), cycles: 7, size: 3, opcode: 0x3E, affected_on_page: false }); + + // ror + opcodes.insert(0x6A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("ror"), cycles: 2, size: 1, opcode: 0x6A, affected_on_page: false }); + opcodes.insert(0x66, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("ror"), cycles: 5, size: 2, opcode: 0x66, affected_on_page: false }); + opcodes.insert(0x76, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("ror"), cycles: 6, size: 2, opcode: 0x76, affected_on_page: false }); + opcodes.insert(0x6E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("ror"), cycles: 6, size: 3, opcode: 0x6E, affected_on_page: false }); + opcodes.insert(0x7E, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("ror"), cycles: 7, size: 3, opcode: 0x7E, affected_on_page: false }); + + // rti + opcodes.insert(0x40, Entry { mode: AddressingMode::Implied, mnemonic: String::from("rti"), cycles: 6, size: 1, opcode: 0x40, affected_on_page: false }); + + // rts + opcodes.insert(0x60, Entry { mode: AddressingMode::Implied, mnemonic: String::from("rts"), cycles: 6, size: 1, opcode: 0x60, affected_on_page: false }); + + // sbc + opcodes.insert(0xE9, Entry { mode: AddressingMode::Immediate, mnemonic: String::from("sbc"), cycles: 2, size: 2, opcode: 0xE9, affected_on_page: false }); + opcodes.insert(0xE5, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("sbc"), cycles: 3, size: 2, opcode: 0xE5, affected_on_page: false }); + opcodes.insert(0xF5, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("sbc"), cycles: 4, size: 2, opcode: 0xF5, affected_on_page: false }); + opcodes.insert(0xED, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("sbc"), cycles: 4, size: 3, opcode: 0xED, affected_on_page: false }); + opcodes.insert(0xFD, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("sbc"), cycles: 4, size: 3, opcode: 0xFD, affected_on_page: true }); + opcodes.insert(0xF9, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("sbc"), cycles: 4, size: 3, opcode: 0xF9, affected_on_page: true }); + opcodes.insert(0xE1, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("sbc"), cycles: 6, size: 2, opcode: 0xE1, affected_on_page: false }); + opcodes.insert(0xF1, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("sbc"), cycles: 5, size: 2, opcode: 0xF1, affected_on_page: true }); + + // sec + opcodes.insert(0x38, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("sec"), cycles: 2, size: 1, opcode: 0x38, affected_on_page: false }); + + // sed + opcodes.insert(0xF8, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("sed"), cycles: 2, size: 1, opcode: 0xF8, affected_on_page: false }); + + // sei + opcodes.insert(0x78, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("sei"), cycles: 2, size: 1, opcode: 0x78, affected_on_page: false }); + + // sta + opcodes.insert(0x85, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("sta"), cycles: 3, size: 2, opcode: 0x85, affected_on_page: false }); + opcodes.insert(0x95, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("sta"), cycles: 4, size: 2, opcode: 0x95, affected_on_page: false }); + opcodes.insert(0x8D, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("sta"), cycles: 4, size: 3, opcode: 0x8D, affected_on_page: false }); + opcodes.insert(0x9D, Entry { mode: AddressingMode::IndexedX, mnemonic: String::from("sta"), cycles: 5, size: 3, opcode: 0x9D, affected_on_page: false }); + opcodes.insert(0x99, Entry { mode: AddressingMode::IndexedY, mnemonic: String::from("sta"), cycles: 5, size: 3, opcode: 0x99, affected_on_page: false }); + opcodes.insert(0x81, Entry { mode: AddressingMode::IndirectX, mnemonic: String::from("sta"), cycles: 6, size: 2, opcode: 0x81, affected_on_page: false }); + opcodes.insert(0x91, Entry { mode: AddressingMode::IndirectY, mnemonic: String::from("sta"), cycles: 6, size: 2, opcode: 0x91, affected_on_page: false }); + + // stx + opcodes.insert(0x86, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("stx"), cycles: 3, size: 2, opcode: 0x86, affected_on_page: false }); + opcodes.insert(0x96, Entry { mode: AddressingMode::ZeropageIndexedY, mnemonic: String::from("stx"), cycles: 4, size: 2, opcode: 0x96, affected_on_page: false }); + opcodes.insert(0x8E, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("stx"), cycles: 4, size: 3, opcode: 0x8E, affected_on_page: false }); + + // sty + opcodes.insert(0x84, Entry { mode: AddressingMode::RelativeOrZeropage, mnemonic: String::from("sty"), cycles: 3, size: 2, opcode: 0x84, affected_on_page: false }); + opcodes.insert(0x94, Entry { mode: AddressingMode::ZeropageIndexedX, mnemonic: String::from("sty"), cycles: 4, size: 2, opcode: 0x94, affected_on_page: false }); + opcodes.insert(0x8C, Entry { mode: AddressingMode::Absolute, mnemonic: String::from("sty"), cycles: 4, size: 3, opcode: 0x8C, affected_on_page: false }); + + // tax + opcodes.insert(0xAA, Entry{ mode: AddressingMode::Implied, mnemonic: String::from("tax"), cycles: 2, size: 1, opcode: 0xAA, affected_on_page: false }); + + // tay + opcodes.insert(0xA8, Entry { mode: AddressingMode::Implied, mnemonic: String::from("tay"), cycles: 2, size: 1, opcode: 0xA8, affected_on_page: false }); + + // tsx + opcodes.insert(0xBA, Entry { mode: AddressingMode::Implied, mnemonic: String::from("tsx"), cycles: 2, size: 1, opcode: 0xBA, affected_on_page: false }); + + // txa + opcodes.insert(0x8A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("txa"), cycles: 2, size: 1, opcode: 0x8A, affected_on_page: false }); + + // txs + opcodes.insert(0x9A, Entry { mode: AddressingMode::Implied, mnemonic: String::from("txs"), cycles: 2, size: 1, opcode: 0x9A, affected_on_page: false }); + + // tya + opcodes.insert(0x98, Entry { mode: AddressingMode::Implied, mnemonic: String::from("tya"), cycles: 2, size: 1, opcode: 0x98, affected_on_page: false }); + + opcodes + }; +} |
