Skip to content

Commit

Permalink
Prevent a division by zero
Browse files Browse the repository at this point in the history
Fixes: 8b5feee ("assembler: Implement and add tests for operators")

Signed-off-by: Miquel Sabaté Solà <[email protected]>
  • Loading branch information
mssola committed Dec 20, 2024
1 parent bdb7254 commit d88fab8
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions lib/xixanta/src/assembler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,13 @@ impl Assembler {
lval * rval
}
OperationType::Div => {
if rval == 0 {
return Err(EvalError {
line: node.value.line,
global: false,
message: "attempting to divide by zero".to_string(),
});
}
let lval = self.evaluate_node(node.left.as_ref().unwrap())?.value();
lval / rval
}
Expand Down Expand Up @@ -1994,6 +2001,50 @@ ldx #+Value
assert_eq!(pos.bytes[2], 0x00);
}

#[test]
fn divide_by_zero() {
let mut asm = Assembler::new(EMPTY.to_vec());
asm.mappings[0].segments[0].bundles = minimal_header();
asm.mappings[0].offset = 6;
asm.current_mapping = 1;
let res = &asm
.assemble(
std::env::current_dir().unwrap().to_path_buf(),
r#"Value = 0
ldx #(2 / Value)
"#
.as_bytes(),
)
.unwrap_err();

assert_eq!(
res.first().unwrap().to_string(),
"attempting to divide by zero (line 2)"
);
}

#[test]
fn bad_shift() {
let mut asm = Assembler::new(EMPTY.to_vec());
asm.mappings[0].segments[0].bundles = minimal_header();
asm.mappings[0].offset = 6;
asm.current_mapping = 1;
let res = &asm
.assemble(
std::env::current_dir().unwrap().to_path_buf(),
r#"Value = #$11
ldx #(2 << Value)
"#
.as_bytes(),
)
.unwrap_err();

assert_eq!(
res.first().unwrap().to_string(),
"shift operator too big (line 2)"
);
}

// Regular instructions

#[test]
Expand Down

0 comments on commit d88fab8

Please sign in to comment.