Clean up control flow code in the VM; Remove returns from if and if/else_if statements

This commit is contained in:
Jeff 2024-08-11 15:03:26 -04:00
parent 0c73f80947
commit 28c65b0715
2 changed files with 46 additions and 17 deletions

View File

@ -226,8 +226,6 @@ impl<'src> Parser<'src> {
if let Token::Else = self.current.0 {
self.next_token()?;
} else {
let else_if_end = self.current.1;
return Ok(Node::new(
Statement::IfElseIf {
condition,

View File

@ -254,15 +254,16 @@ impl Vm {
position: condition_position,
});
};
if let Some(condition) = condition_value.as_boolean() {
if condition {
return self.run_node(*body, context);
}
let condition = if let Some(condition) = condition_value.as_boolean() {
condition
} else {
return Err(VmError::ExpectedBoolean {
position: condition_position,
});
};
if condition {
self.run_node(*body, context)?;
}
Ok(None)
@ -321,15 +322,16 @@ impl Vm {
position: condition_position,
});
};
if let Some(condition) = condition_value.as_boolean() {
if condition {
return self.run_node(body, context);
}
let condition = if let Some(condition) = condition_value.as_boolean() {
condition
} else {
return Err(VmError::ExpectedBoolean {
position: condition_position,
});
};
if condition {
self.run_node(body, context)?;
}
}
@ -370,15 +372,16 @@ impl Vm {
position: condition_position,
});
};
if let Some(condition) = condition_value.as_boolean() {
if condition {
return self.run_node(body, context);
}
let condition = if let Some(condition) = condition_value.as_boolean() {
condition
} else {
return Err(VmError::ExpectedBoolean {
position: condition_position,
});
};
if condition {
return self.run_node(body, context);
}
}
@ -657,6 +660,34 @@ impl Display for VmError {
mod tests {
use super::*;
#[test]
fn r#if() {
let input = "if true { 1 }";
assert_eq!(run(input, &mut Context::new()), Ok(None));
}
#[test]
fn if_else() {
let input = "if false { 1 } else { 2 }";
assert_eq!(run(input, &mut Context::new()), Ok(Some(Value::integer(2))));
}
#[test]
fn if_else_if() {
let input = "if false { 1 } else if true { 2 }";
assert_eq!(run(input, &mut Context::new()), Ok(None));
}
#[test]
fn if_else_if_else() {
let input = "if false { 1 } else if false { 2 } else { 3 }";
assert_eq!(run(input, &mut Context::new()), Ok(Some(Value::integer(3))));
}
#[test]
fn while_loop() {
let input = "x = 0; while x < 5 { x += 1; } x";