Add loop expressions.

This commit is contained in:
Stephen Chung
2022-10-29 12:09:18 +08:00
parent 6af66d3ed3
commit c14fbdb14d
10 changed files with 146 additions and 73 deletions

View File

@@ -55,10 +55,13 @@ fn test_expressions() -> Result<(), Box<EvalAltResult>> {
)
.is_err());
assert!(engine.eval_expression::<()>("40 + 2;").is_err());
assert!(engine.eval_expression::<()>("40 + { 2 }").is_err());
assert!(engine.eval_expression::<()>("x = 42").is_err());
assert!(engine.compile_expression("40 + 2;").is_err());
assert!(engine.compile_expression("40 + { 2 }").is_err());
assert!(engine.compile_expression("x = 42").is_err());
assert!(engine.compile_expression("let x = 42").is_err());
assert!(engine
.compile_expression("do { break 42; } while true")
.is_err());
engine.compile("40 + { let x = 2; x }")?;

View File

@@ -231,6 +231,22 @@ fn test_for_loop() -> Result<(), Box<EvalAltResult>> {
);
}
assert_eq!(
engine.eval::<INT>(
r#"
let a = [123, 999, 42, 0, true, "hello", "world!", 987.6543];
for (item, count) in a {
switch item.type_of() {
"i64" if item.is_even => break count,
"f64" if item.to_int().is_even => break count,
}
}
"#
)?,
2
);
Ok(())
}

View File

@@ -22,6 +22,22 @@ fn test_while() -> Result<(), Box<EvalAltResult>> {
6
);
assert_eq!(
engine.eval::<INT>(
"
let x = 0;
while x < 10 {
x += 1;
if x > 5 { break x * 2; }
if x > 3 { continue; }
x += 3;
}
",
)?,
12
);
Ok(())
}
@@ -46,6 +62,25 @@ fn test_do() -> Result<(), Box<EvalAltResult>> {
)?,
6
);
assert_eq!(
engine.eval::<INT>(
"
let x = 0;
do {
x += 1;
if x > 5 { break x * 2; }
if x > 3 { continue; }
x += 3;
} while x < 10;
",
)?,
12
);
engine.run("do {} while false")?;
assert_eq!(engine.eval::<INT>("do { break 42; } while false")?, 42);
Ok(())
}