nondescript/src/ndspkg/compiler/jumps.nim

41 lines
1.1 KiB
Nim

import ../chunk
import ../config
import types
import utils
# JUMP HELPERS
proc emitJump*(comp: Compiler, delta: int, op: OpCode, stacklen: var int): int =
# delta -> 0 if the jump does not pop
# delta -> -1 if the jump pops the condition from the stack
comp.writeChunk(delta, op)
comp.writeChunk(0, 0xffffff.toDU8)
stacklen = comp.stackIndex
comp.chunk.len - argSize
proc patchJump*(comp: Compiler, offset: int, stacklen: int) =
if comp.stackIndex != stacklen:
comp.error("Assertion failed: loop doesn't preserve stackindex.")
let jump = (comp.chunk.len - offset - argSize)
if (jump > argMax):
comp.error("Too much code to jump over.")
let jumpt = jump.toDU8
comp.chunk.code[offset] = jumpt[0]
comp.chunk.code[offset + 1] = jumpt[1]
proc emitLoop*(comp: Compiler, loopstart: int, delta: int, op: OpCode, stacklen: int) =
if comp.stackIndex != stacklen:
comp.error("Assertion failed: loop doesn't preserve stackindex.")
comp.writeChunk(delta, op)
let offset = comp.chunk.len - loopstart + argSize
if offset > argMax:
comp.error("Loop body too large.")
comp.writeChunk(0, offset.toDU8)