feat: 添加三元运算符支持,更新解析器和解释器以处理条件表达式
This commit is contained in:
@@ -361,6 +361,14 @@ impl Interpreter {
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::Ternary { condition, then_branch, else_branch } => {
|
||||
let cond = self.evaluate(*condition)?;
|
||||
if self.is_truthy(&cond) {
|
||||
self.evaluate(*then_branch)
|
||||
} else {
|
||||
self.evaluate(*else_branch)
|
||||
}
|
||||
}
|
||||
Expr::Call { callee, arguments } => {
|
||||
let func = self.evaluate(*callee)?;
|
||||
let mut args = Vec::new();
|
||||
@@ -730,6 +738,57 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Ternary
|
||||
// =========================================================================
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_true_condition() {
|
||||
assert_num(&eval_expr("true ? 1 : 2"), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_false_condition() {
|
||||
assert_num(&eval_expr("false ? 1 : 2"), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_truthy_condition() {
|
||||
// Non-nil, non-false values are truthy
|
||||
assert_num(&eval_expr("1 ? 42 : 99"), 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_nil_condition() {
|
||||
assert_num(&eval_expr("nil ? 1 : 2"), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_nested() {
|
||||
let interp = run("let x = 5; let r = x > 3 ? (x > 10 ? 100 : 50) : 0;");
|
||||
assert_num(&get_var(&interp, "r"), 50.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_with_computed_branches() {
|
||||
let interp = run("let x = 10; let r = x > 5 ? x * 2 : x / 2;");
|
||||
assert_num(&get_var(&interp, "r"), 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_short_circuit_then() {
|
||||
// When condition is false, then_branch is not evaluated
|
||||
let interp = run("let x = 0; let r = false ? (x = 999) : (x = 42);");
|
||||
assert_num(&get_var(&interp, "x"), 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_ternary_short_circuit_else() {
|
||||
// When condition is true, else_branch is not evaluated
|
||||
let interp = run("let x = 0; let r = true ? (x = 42) : (x = 999);");
|
||||
assert_num(&get_var(&interp, "x"), 42.0);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Unary
|
||||
// =========================================================================
|
||||
|
||||
Reference in New Issue
Block a user