From cfe02062a64e25706d5d5ebe0ec492680da47335 Mon Sep 17 00:00:00 2001 From: ala89 Date: Sat, 2 Dec 2023 15:49:27 +0100 Subject: [PATCH] Add for and while semantics + tests --- src/interpreter.cpp | 27 +++++++++++++++++++++++++++ test/statements.cpp | 12 ++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/interpreter.cpp b/src/interpreter.cpp index eba9b84..4f98161 100644 --- a/src/interpreter.cpp +++ b/src/interpreter.cpp @@ -50,6 +50,33 @@ EvalResult eval(Node &ast, Memory &memory) { return {}; } break; + case NodeType::While: { + while (true) { + int cond = get(eval(node.children[0], memory)); + if (!cond) break; + + eval(node.children[1], memory); + } + + return {}; + } break; + case NodeType::For: { + memory.add_scope(); + + eval(node.children[0], memory); + + while (true) { + int cond = get(eval(node.children[1], memory)); + if (!cond) break; + + eval(node.children[3], memory); + eval(node.children[2], memory); + } + + memory.remove_scope(); + + return {}; + } break; case NodeType::Bloc: { memory.add_scope(); eval(node.children[0], memory); diff --git a/test/statements.cpp b/test/statements.cpp index 7b69ab7..1c9ac36 100644 --- a/test/statements.cpp +++ b/test/statements.cpp @@ -35,5 +35,17 @@ int main() { true ); + _TEST_ASSERT( + _TEST_NO_EXCEPTION(get(execute("int i = 0; while (i < 100) i++; i;")) == 100), + "While", + true + ); + + _TEST_ASSERT( + _TEST_NO_EXCEPTION(get(execute("int i = 0; for (int j = 0; j < 100; j++) { i++; } i;")) == 100), + "For", + true + ); + return 0; } \ No newline at end of file