japl/nim/meta/chunk.nim

89 lines
1.6 KiB
Nim
Raw Normal View History

## The module dedicated to the type Chunk.
## A chunk is a piece of bytecode.
2020-08-07 17:11:06 +02:00
import valueobject
type
OpCode* {.pure.} = enum
## Enum of possible opcodes.
Constant = 0u8,
ConstantLong,
Return,
Negate,
Add,
Subtract,
Divide,
Multiply,
Pow,
Mod,
Nil,
True,
False,
Greater,
Less,
Equal,
Not,
Slice,
SliceRange,
Pop,
DefineGlobal,
GetGlobal,
SetGlobal,
DeleteGlobal,
SetLocal,
GetLocal,
DeleteLocal,
JumpIfFalse,
Jump,
Loop,
Breal,
Shr,
Shl,
Nan,
Inf,
Xor,
Call,
Bor,
Band,
Bnot
2020-08-30 12:35:37 +02:00
2020-08-07 17:11:06 +02:00
Chunk* = ref object
## A piece of bytecode.
consts*: ValueArray
code*: seq[uint8]
lines*: seq[int]
2020-08-07 17:11:06 +02:00
proc newChunk*(): Chunk =
##
result = Chunk(consts: ValueArray(values: @[]), code: @[], lines: @[])
2020-08-07 17:11:06 +02:00
2020-08-07 19:38:52 +02:00
proc writeChunk*(self: Chunk, byt: uint8, line: int) =
self.code.add(byt)
2020-08-07 17:11:06 +02:00
self.lines.add(line)
2020-08-07 19:38:52 +02:00
proc writeChunk*(self: Chunk, bytes: array[3, uint8], line: int) =
2020-08-07 19:38:52 +02:00
for byt in bytes:
self.writeChunk(byt, line)
2020-08-07 17:11:06 +02:00
proc freeChunk*(self: var Chunk) =
self.consts = ValueArray(values: @[])
self.code = @[]
self.lines = @[]
proc addConstant*(chunk: var Chunk, constant: Value): int =
chunk.consts.values.add(constant)
return len(chunk.consts.values) - 1 # The index of the constant
2020-08-07 19:38:52 +02:00
proc writeConstant*(chunk: var Chunk, constant: Value): array[3, uint8] =
2020-08-07 19:38:52 +02:00
let index = chunk.addConstant(constant)
result = cast[array[3, uint8]](index)