Skip to content

Commit

Permalink
Add instruction bytes to listing output
Browse files Browse the repository at this point in the history
  • Loading branch information
Granddave committed Dec 20, 2023
1 parent 6f2f93f commit ff96d7a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 10 deletions.
25 changes: 25 additions & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,31 @@ impl ASTInstructionNode {
ASTOperand::Implied => 1,
}
}

// TODO: Merge with the implementation in the compiler module
pub fn bytes(&self) -> Vec<u8> {
let mut bytes = vec![];

bytes.push(
crate::assembler::compiler::opcode::OPCODE_MAPPING
.find_opcode(self.ins)
.unwrap_or_else(|| panic!("Invalid opcode: '{:#04x}'", self.ins.mnemonic as u8)),
);

match self.operand {
ASTOperand::Immediate(value) => bytes.push(value),
ASTOperand::Absolute(address) => {
bytes.push((address & 0xFF) as u8);
bytes.push((address >> 8) as u8);
}
ASTOperand::ZeroPage(address) => bytes.push(address),
ASTOperand::Relative(offset) => bytes.push(offset as u8),
ASTOperand::Implied => {}
_ => panic!("Cannot calculate bytes for: {:#?}", self),
}

bytes
}
}

impl fmt::Display for ASTInstructionNode {
Expand Down
29 changes: 19 additions & 10 deletions src/disassembler/listing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,23 @@ impl Listing {

#[tracing::instrument]
fn generate_line(&self, node: &ASTInstructionNode) -> String {
format!("{:04x}: {}\n", self.current_address, node)
let bytes = node.bytes();
let bytes_str = bytes
.iter()
.map(|b| format!("{:02X}", b))
.collect::<Vec<String>>()
.join(" ");
format!(
"${:04X} {:08} {}\n",
self.current_address, bytes_str, node
)
}

#[tracing::instrument]
pub fn generate(&mut self) -> String {
self.str.push_str("Addr Ins\n");
self.str.push_str("---------------\n");
// 0600: JSR $0606
self.str.push_str(" Addr Hexdump Instructions\n");
self.str.push_str("-----------------------------\n");
// $0600 20 06 06 JSR $0606

for node in &self.ast {
// TODO: Add support for other AST nodes
Expand Down Expand Up @@ -76,12 +85,12 @@ mod tests {
),
];
let mut listing = Listing::default(ast);
let expected = "Addr Ins
---------------
0600: JSR $0606
0603: LDA #$01
0605: LDA $0200
0608: LDA $0200,X
let expected = " Addr Hexdump Instructions
-----------------------------
$0600 20 06 06 JSR $0606
$0603 A9 01 LDA #$01
$0605 AD 00 02 LDA $0200
$0608 BD 00 02 LDA $0200,X
";

assert_eq!(listing.generate(), expected);
Expand Down

0 comments on commit ff96d7a

Please sign in to comment.