From 4515d21211263a2c7367ec20ec01ce9efaae1d18 Mon Sep 17 00:00:00 2001 From: Bad Diode Date: Wed, 27 Oct 2021 17:15:48 +0200 Subject: Fix depth resolution on recursive calls --- src/bytecode/compiler.h | 37 ++++++++++++++++++++----------------- src/bytecode/vm.h | 5 +++-- 2 files changed, 23 insertions(+), 19 deletions(-) (limited to 'src/bytecode') diff --git a/src/bytecode/compiler.h b/src/bytecode/compiler.h index 27ff312..124c345 100755 --- a/src/bytecode/compiler.h +++ b/src/bytecode/compiler.h @@ -608,26 +608,29 @@ parse_tree(Chunk *chunk, Compiler *compiler) { return; } break; case TOKEN_SYMBOL: { - size_t depth = compiler->scope_depth - 1; - ssize_t idx = -1; - do { - Scope *scope = &compiler->scopes[depth]; - idx = find_local_index(scope, tok); + if (compiler->scope_depth > 1) { + size_t depth = compiler->scope_depth - 1; + ssize_t idx = -1; + do { + Scope *scope = &compiler->scopes[depth]; + idx = find_local_index(scope, tok); + if (idx >= 0) { + break; + } + depth--; + } while (depth > 0); + if (idx >= 0) { - break; + emit_constant(chunk, tok, FIXNUM_VAL(depth)); + emit_constant(chunk, tok, FIXNUM_VAL(idx)); + add_code(chunk, OP_LOCAL, tok.line, tok.column); + return; } - depth--; - } while (depth > 0); - - if (idx >= 0) { - emit_constant(chunk, tok, FIXNUM_VAL(depth)); - emit_constant(chunk, tok, FIXNUM_VAL(idx)); - add_code(chunk, OP_LOCAL, tok.line, tok.column); - } else { - Object obj = make_symbol(tok.value); - emit_constant(chunk, tok, obj); - add_code(chunk, OP_GET, tok.line, tok.column); } + + Object obj = make_symbol(tok.value); + emit_constant(chunk, tok, obj); + add_code(chunk, OP_GET, tok.line, tok.column); return; } break; case TOKEN_NIL: { diff --git a/src/bytecode/vm.h b/src/bytecode/vm.h index 3c99131..3fba3d7 100755 --- a/src/bytecode/vm.h +++ b/src/bytecode/vm.h @@ -177,9 +177,9 @@ vm_interpret(VM *vm) { case OP_LOCAL: { ssize_t idx = AS_FIXNUM(array_pop(vm->stack)); ssize_t depth = AS_FIXNUM(array_pop(vm->stack)); + depth = array_size(vm->frames) - depth; CallFrame frame = vm->frames[depth]; array_push(vm->stack, vm->stack[frame.stack_offset + idx]); - } break; case OP_CONSTANT: { u8 constant = *vm->pc++; @@ -300,8 +300,9 @@ vm_interpret(VM *vm) { #ifdef DEBUG disassemble_chunk(proc.chunk); + printf("n_locals: %ld\n", n_locals); + printf("n_params: %ld\n", n_params); #endif - // Tail-call optimization. if (proc.chunk != frame->chunk || *vm->pc != OP_RETURN) { // Prepare new call frame. -- cgit v1.2.1