fix setglobal popping

This commit is contained in:
prod2 2022-01-29 07:24:58 +01:00
parent d7f59f5ad7
commit 71a3d6ad45
5 changed files with 21 additions and 9 deletions

View File

@ -9,8 +9,8 @@ const debugCompiler* = false
const debugDumpChunk* = defined(debug)
const assertionsCompiler* = true # sanity checks in the compiler
# vm debug options (setting any to true will slow runtime down!)
const debugVM* = false
const assertionsVM* = false # sanity checks in the VM, such as the stack being empty at the end
const debugVM* = defined(debug)
const assertionsVM* = defined(debug) # sanity checks in the VM, such as the stack being empty at the end
const profileInstructions* = false # if true, the time spent on every opcode is measured
const compileTests* = defined(debug)

8
tests/while.nds Normal file
View File

@ -0,0 +1,8 @@
var i = 1;
while (i < 300) {
i = i + 1;
};
print i;

4
tests/while2.nds Normal file
View File

@ -0,0 +1,4 @@
var i = 5;
while (i > 0)
print i = i - 1
;

View File

@ -1,7 +1,7 @@
import ../pointerutils
# configure stacks here
const boundsChecks = false
const boundsChecks = defined(debug)
# boundsChecks default: false, true has a large performance impact, and emitting correct code is on the compiler's job
# boundsChecking is only meant for debugging
const growthFactor = 2
@ -74,7 +74,7 @@ proc deleteTopN*[T](stack: var Stack[T], n: Natural) =
proc getIndex*[T](stack: Stack[T], index: int): T =
when boundsChecks:
if index < 0 or index >= stack.len():
raise newException(Defect, "Attempt to getIndex with an index out of bounds.")
raise newException(Defect, &"Attempt to getIndex with an index {index} which is out of bounds (len: {stack.len()}).")
stack.start.padd(index * sizeof(T))[]
proc getIndexNeg*[T](stack: Stack[T], index: int): T =

10
vm.nim
View File

@ -71,9 +71,9 @@ proc run*(chunk: Chunk): InterpretResult =
ip = ip.padd(1)
when debugVM:
let ii = ip.pdiff(chunk.code[0].unsafeAddr)
let ii = ip.pdiff(chunk.code[0].unsafeAddr) - 1
let opname = ($ins)
var msg = &"[{ii:4}] {opname}"
var msg = &"[{ii:04}] {opname}"
msg &= " Stack: [ "
for i in 0 .. stack.high():
let e = stack[i]
@ -175,7 +175,7 @@ proc run*(chunk: Chunk): InterpretResult =
break
of opSetGlobal:
let name = readConstant().asString()
let existed = globals.tableSet(name.fromNdString(), stack.pop())
let existed = globals.tableSet(name.fromNdString(), stack.peek())
if not existed:
runtimeError("Attempt to redefine an existing global variable.")
break
@ -187,11 +187,11 @@ proc run*(chunk: Chunk): InterpretResult =
stack[slot + frameBottom] = stack.peek()
of opJumpIfFalse:
let offset = readDU8()
if stack.peek().isFalsey:
if stack.peek().isFalsey():
ip = ip.padd(offset)
of opJumpIfFalsePop:
let offset = readDU8()
if stack.pop().isFalsey:
if stack.pop().isFalsey():
ip = ip.padd(offset)
of opJump:
let offset = readDU8()