LibJS: Add short circuit logical evaluation

When evaluating logical binop expressions, the rhs must not be
evaluated if the lhs leads to the whole expression not being
truthy.
This commit is contained in:
Stephan Unverwerth 2020-04-03 19:11:31 +02:00 committed by Andreas Kling
commit 520311eb8b
Notes: sideshowbarker 2024-07-19 07:58:32 +09:00
2 changed files with 28 additions and 4 deletions

View file

@ -282,17 +282,26 @@ Value LogicalExpression::execute(Interpreter& interpreter) const
auto lhs_result = m_lhs->execute(interpreter);
if (interpreter.exception())
return {};
auto rhs_result = m_rhs->execute(interpreter);
if (interpreter.exception())
return {};
switch (m_op) {
case LogicalOp::And:
if (lhs_result.to_boolean())
if (lhs_result.to_boolean()) {
auto rhs_result = m_rhs->execute(interpreter);
if (interpreter.exception())
return {};
return Value(rhs_result);
}
return Value(lhs_result);
case LogicalOp::Or:
if (lhs_result.to_boolean())
return Value(lhs_result);
auto rhs_result = m_rhs->execute(interpreter);
if (interpreter.exception())
return {};
return Value(rhs_result);
}

View file

@ -0,0 +1,15 @@
function assert(x) { if (!x) throw 1; }
try {
let foo = 1;
false && (foo = 2);
assert(foo === 1);
foo = 1;
true || (foo = 2);
assert(foo === 1);
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}