Fixed bugs with globals and added related test

This commit is contained in:
Mattia Giambirtone 2023-05-23 12:10:30 +02:00
parent bc0f614143
commit 86231291c4
Signed by: nocturn9x
GPG Key ID: 8270F9F467971E59
3 changed files with 21 additions and 13 deletions

View File

@ -900,9 +900,6 @@ proc prepareAutoFunction(self: BytecodeCompiler, fn: Name, args: seq[tuple[name:
## by declaring a concrete version of it along
## with its arguments
# First we declare the function's generics, if it has any.
# This is because the function's return type may in itself
# be a generic, so it needs to exist first
let idx = self.stackIndex
self.stackIndex = 1
var default: Expression
@ -1244,11 +1241,12 @@ method identifier(self: BytecodeCompiler, node: IdentExpr, name: Name = nil, com
if s.depth > 0:
# Loads a regular variable from the current frame
self.emitByte(LoadVar, s.ident.token.line)
# No need to check for -1 here: we already did a nil check above!
self.emitBytes(s.position.toTriple(), s.ident.token.line)
else:
# Loads a global variable from an absolute stack
# position
self.emitByte(LoadGlobal, s.ident.token.line)
self.emitBytes(s.position.toTriple(), s.ident.token.line)
# No need to check for -1 here: we already did a nil check above!
self.emitBytes(s.position.toTriple(), s.ident.token.line)
method assignment(self: BytecodeCompiler, node: ASTNode, compile: bool = true): Type {.discardable.} =
@ -1946,12 +1944,11 @@ proc funDecl(self: BytecodeCompiler, node: FunDecl, name: Name) =
# the end of the module
self.forwarded.add((name, 0))
name.valueType.forwarded = true
self.currentFunction = function
return
if name.isBuiltin:
# Builtins are handled at call time
return
self.currentFunction = name
if self.currentFunction.isBuiltin:
self.currentFunction = function
return
let stackIdx = self.stackIndex
self.stackIndex = name.position
if not node.isTemplate:
@ -2090,7 +2087,8 @@ proc compile*(self: BytecodeCompiler, ast: seq[Declaration], file: string, lines
else:
self.ast = ast
self.current = 0
self.stackIndex = 1
if not incremental:
self.stackIndex = 1
self.lines = lines
self.source = source
self.isMainModule = isMainModule

View File

@ -10,8 +10,8 @@ fn fib(n: int): int {
}
print("Computing the value of fib(37)");
print("Computing the value of fib(35)");
var x = time.clock();
print(fib(37));
print(fib(35));
print(time.clock() - x);
print("Done!");

10
tests/globals.pn Normal file
View File

@ -0,0 +1,10 @@
import std;
# Seemingly unnecessary, but importing modules
# changes the internal stack index in the compiler
# so we need to test for that as well
import time;
var x = 69420;
print(x == 69420);
print(testGlobals());