From f2f8aed23a1b9721b83125ae6ceaeb3f64abe976 Mon Sep 17 00:00:00 2001 From: Kayne Ruse Date: Sat, 11 Mar 2023 17:59:09 +1100 Subject: [PATCH] Added short-circuiting support to && and || --- source/toy_interpreter.c | 14 ++++++++------ test/scripts/comparisons.toy | 3 +++ test/scripts/short-circuiting-support.toy | 9 +++++++++ test/test_interpreter.c | 1 + 4 files changed, 21 insertions(+), 6 deletions(-) create mode 100644 test/scripts/short-circuiting-support.toy diff --git a/source/toy_interpreter.c b/source/toy_interpreter.c index 574de9d..7dae301 100644 --- a/source/toy_interpreter.c +++ b/source/toy_interpreter.c @@ -1082,11 +1082,12 @@ static bool execAnd(Toy_Interpreter* interpreter) { return false; } - if (TOY_IS_TRUTHY(lhs) && TOY_IS_TRUTHY(rhs)) { - Toy_pushLiteralArray(&interpreter->stack, TOY_TO_BOOLEAN_LITERAL(true)); + //short-circuit support + if (!TOY_IS_TRUTHY(lhs)) { + Toy_pushLiteralArray(&interpreter->stack, lhs); } else { - Toy_pushLiteralArray(&interpreter->stack, TOY_TO_BOOLEAN_LITERAL(false)); + Toy_pushLiteralArray(&interpreter->stack, rhs); } Toy_freeLiteral(lhs); @@ -1115,11 +1116,12 @@ static bool execOr(Toy_Interpreter* interpreter) { return false; } - if (TOY_IS_TRUTHY(lhs) || TOY_IS_TRUTHY(rhs)) { - Toy_pushLiteralArray(&interpreter->stack, TOY_TO_BOOLEAN_LITERAL(true)); + //short-circuit support + if (TOY_IS_TRUTHY(lhs)) { + Toy_pushLiteralArray(&interpreter->stack, lhs); } else { - Toy_pushLiteralArray(&interpreter->stack, TOY_TO_BOOLEAN_LITERAL(false)); + Toy_pushLiteralArray(&interpreter->stack, rhs); } Toy_freeLiteral(lhs); diff --git a/test/scripts/comparisons.toy b/test/scripts/comparisons.toy index f46d8cd..241d8bb 100644 --- a/test/scripts/comparisons.toy +++ b/test/scripts/comparisons.toy @@ -23,5 +23,8 @@ assert !false, "!false"; var c = false; assert !c, "!c"; +//test multiple comparisons +assert 1 == 2 == false, "Left-accociative equality failed"; + print "All good"; diff --git a/test/scripts/short-circuiting-support.toy b/test/scripts/short-circuiting-support.toy new file mode 100644 index 0000000..5e5bb17 --- /dev/null +++ b/test/scripts/short-circuiting-support.toy @@ -0,0 +1,9 @@ +//explicitly support && and || short circuits + +assert 1 && 2 == 2, "&& short-circuit failed"; + +assert 1 || 2 == 1, "|| short-circuit failed"; + + +print "All good"; + diff --git a/test/test_interpreter.c b/test/test_interpreter.c index da7a007..615490d 100644 --- a/test/test_interpreter.c +++ b/test/test_interpreter.c @@ -132,6 +132,7 @@ int main() { "panic-within-functions.toy", "polyfill-insert.toy", "polyfill-remove.toy", + "short-circuiting-support.toy", "ternary-expressions.toy", "types.toy", NULL