diff --git a/src/backend/vm.nim b/src/backend/vm.nim index ae21d45..e9b63a3 100644 --- a/src/backend/vm.nim +++ b/src/backend/vm.nim @@ -21,6 +21,7 @@ import std/math import ../config import ../frontend/meta/bytecode import ../util/multibyte +import ../memory/allocator import strutils @@ -306,6 +307,18 @@ proc constReadFloat64(self: PeonVM, idx: int): float = self.chunk.consts[idx + 4], self.chunk.consts[idx + 5], self.chunk.consts[idx + 6], self.chunk.consts[idx + 7]] copyMem(result.addr, arr.addr, sizeof(arr)) + + +proc constReadString(self: PeonVM, size, idx: int): ptr UncheckedArray[char] = + ## Reads a constant from the + ## chunk's constant table and + ## returns it as a pointer to + ## a heap-allocated string + let str = self.chunk.consts[idx.. 1: echo &"DEBUG - Memory manager: Deallocating {oldSize} bytes" @@ -33,10 +33,7 @@ proc reallocate*(p: pointer, oldSize: int, newSize: int): pointer = echo "DEBUG - Memory manager: Deallocating 1 byte" dealloc(p) return nil - when debugMem: - if pointr == nil and newSize == 0: - echo &"DEBUG - Memory manager: Warning, asked to dealloc() nil pointer from {oldSize} to {newSize} bytes, ignoring request" - if oldSize > 0 and p != nil or oldSize == 0: + if oldSize > 0 and not p.isNil() or oldSize == 0: when debugMem: if oldSize == 0: if newSize > 1: @@ -46,22 +43,40 @@ proc reallocate*(p: pointer, oldSize: int, newSize: int): pointer = else: echo &"DEBUG - Memory manager: Resizing {oldSize} bytes of memory to {newSize} bytes" result = realloc(p, newSize) + when debugMem: - if oldSize > 0 and pointr == nil: + if p.isNil() and newSize == 0: + echo &"DEBUG - Memory manager: Warning, asked to dealloc() nil pointer from {oldSize} to {newSize} bytes, ignoring request" + elif oldSize > 0 and p.isNil(): echo &"DEBUG - Memory manager: Warning, asked to realloc() nil pointer from {oldSize} to {newSize} bytes, ignoring request" except NilAccessDefect: stderr.write("Peon: could not manage memory, segmentation fault\n") quit(139) # For now, there's not much we can do if we can't get the memory we need, so we exit +type + ObjectKind* = enum + String, List, + Dict, Tuple, + CustomType + HeapObject* = object + ## A tag for a heap-allocated + ## peon object + case kind*: ObjectKind + of String: + str*: ptr UncheckedArray[char] + len*: uint64 + else: + discard # TODO + template resizeArray*(kind: untyped, p: pointer, oldCount, newCount: int): untyped = ## Handy template to resize a dynamic array cast[ptr UncheckedArray[kind]](reallocate(p, sizeof(kind) * oldCount, sizeof(kind) * newCount)) -template freeArray*(kind: untyped, p: pointer, oldCount: int): untyped = +template freeArray*(kind: untyped, p: pointer, size: int): untyped = ## Frees a dynamic array - reallocate(p, sizeof(kind) * oldCount, 0) + reallocate(p, sizeof(kind) * size, 0) template free*(kind: untyped, p: pointer): untyped =