Add for and while semantics + tests

This commit is contained in:
ala89 2023-12-02 15:49:27 +01:00
parent a693258d77
commit cfe02062a6
2 changed files with 39 additions and 0 deletions

View File

@ -50,6 +50,33 @@ EvalResult eval(Node &ast, Memory &memory) {
return {}; return {};
} break; } break;
case NodeType::While: {
while (true) {
int cond = get<int>(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<int>(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: { case NodeType::Bloc: {
memory.add_scope(); memory.add_scope();
eval(node.children[0], memory); eval(node.children[0], memory);

View File

@ -35,5 +35,17 @@ int main() {
true true
); );
_TEST_ASSERT(
_TEST_NO_EXCEPTION(get<int>(execute("int i = 0; while (i < 100) i++; i;")) == 100),
"While",
true
);
_TEST_ASSERT(
_TEST_NO_EXCEPTION(get<int>(execute("int i = 0; for (int j = 0; j < 100; j++) { i++; } i;")) == 100),
"For",
true
);
return 0; return 0;
} }