aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorBad Diode <bd@badd10de.dev>2024-06-30 08:59:50 +0200
committerBad Diode <bd@badd10de.dev>2024-06-30 08:59:50 +0200
commit593bb7d44082872e56b762fed374ad414245f4c2 (patch)
treee4e08d1b1531e51098c57a00e209baff5d1ce35d /src
parent85ee67a206a97954d69e50e962249b2d2e227b1b (diff)
downloadbdl-593bb7d44082872e56b762fed374ad414245f4c2.tar.gz
bdl-593bb7d44082872e56b762fed374ad414245f4c2.zip
Add while loop compilation
Diffstat (limited to 'src')
-rw-r--r--src/compiler.c34
1 files changed, 34 insertions, 0 deletions
diff --git a/src/compiler.c b/src/compiler.c
index 0f9607e..ea9234a 100644
--- a/src/compiler.c
+++ b/src/compiler.c
@@ -559,8 +559,42 @@ compile_if(Chunk *chunk, Node *node) {
559} 559}
560 560
561CompResult 561CompResult
562compile_while(Chunk *chunk, Node *node) {
563 sz start = array_size(chunk->code);
564 CompResult cond = compile_expr(chunk, node->while_cond);
565 OpCode jmpop;
566 switch (cond.type) {
567 case COMP_CONST: {
568 jmpop = OP_JMPFI;
569 } break;
570 case COMP_REG: {
571 jmpop = OP_JMPF;
572 } break;
573 default: {
574 return (CompResult){.type = COMP_ERR};
575 } break;
576 }
577 sz jump_a = array_size(chunk->code);
578
579 // Jump to the `end of the loop` branch.
580 EMIT_OP(jmpop, cond.idx, 0xff, 0, node->while_cond, chunk);
581
582 // Condition is true.
583 CompResult then_expr = compile_expr(chunk, node->while_expr);
584 sz end_expr = array_size(chunk->code);
585 sz loopback = add_constant(chunk, (start - end_expr));
586 EMIT_OP(OP_JMPI, loopback, 0, 0, node, chunk);
587 sz const_a = add_constant(chunk, end_expr - jump_a + 1);
588 chunk->code[jump_a].a = const_a;
589
590 // Return.
591 return (CompResult){.type = COMP_NIL};
592}
593
594CompResult
562compile_expr(Chunk *chunk, Node *node) { 595compile_expr(Chunk *chunk, Node *node) {
563 switch (node->kind) { 596 switch (node->kind) {
597 case NODE_WHILE: return compile_while(chunk, node);
564 case NODE_IF: return compile_if(chunk, node); 598 case NODE_IF: return compile_if(chunk, node);
565 // Logic. 599 // Logic.
566 // case NODE_XOR: 600 // case NODE_XOR: