japl/nim/util/debug.nim

51 lines
1.7 KiB
Nim
Raw Normal View History

2020-08-07 17:11:06 +02:00
import ../meta/chunk
import ../meta/valueobject
import strformat
proc simpleInstruction(name: string, index: int): int =
echo &"\tOpCode at offset: {name}"
echo ""
return index + 1
2020-08-07 19:38:52 +02:00
proc constantLongInstruction(name: string, chunk: Chunk, offset: int): int =
# Rebuild the index
var constantArray: array[3, uint8] = [chunk.code[offset + 1], chunk.code[offset + 2], chunk.code[offset + 3]]
var constant: int
copyMem(constant.addr, unsafeAddr(constantArray), sizeof(constantArray))
echo &"\tOpCode at offset: {name}, points to {constant}"
printValue(chunk.consts.values[constant])
echo ""
return offset + 4
2020-08-07 17:11:06 +02:00
proc constantInstruction(name: string, chunk: Chunk, offset: int): int =
var constant = chunk.code[offset + 1]
echo &"\tOpCode at offset: {name}, points to index {constant}"
printValue(chunk.consts.values[constant])
echo ""
return offset + 2
proc disassembleInstruction*(chunk: Chunk, offset: int): int =
echo &"Current offset: {offset}\nCurrent line: {chunk.lines[offset]}"
var opcode = OpCode(chunk.code[offset])
if opcode == OP_RETURN:
2020-08-07 19:38:52 +02:00
result = simpleInstruction("OP_RETURN", offset)
2020-08-07 17:11:06 +02:00
elif opcode == OP_CONSTANT:
2020-08-07 19:38:52 +02:00
result = constantInstruction("OP_CONSTANT", chunk, offset)
elif opcode == OP_CONSTANT_LONG:
result = constantLongInstruction("OP_CONSTANT_LONG", chunk, offset)
2020-08-07 17:11:06 +02:00
else:
echo &"Unknown opcode {opcode} at index {offset}"
2020-08-07 19:38:52 +02:00
result = offset + 1
2020-08-07 17:11:06 +02:00
proc disassembleChunk*(chunk: Chunk, name: string) =
echo &"==== JAPL VM Debugger - Chunk '{name}' ====\n"
var index = 0
2020-08-07 19:38:52 +02:00
echo chunk.lines
2020-08-07 17:11:06 +02:00
while index < chunk.code.len:
index = disassembleInstruction(chunk, index)
echo &"==== Debug session ended - Chunk '{name}' ===="