module basics, function declarations

This commit is contained in:
prod2 2022-01-21 00:18:58 +01:00
parent e305f0fe69
commit e5f2e213f0
4 changed files with 22 additions and 10 deletions

View File

@ -21,11 +21,12 @@ type
code*: seq[uint8]
constants*: seq[KonValue]
lines*: seq[int]
name*: string # name of the module/chunk/files
Triple* = array[3, uint8]
proc initChunk*: Chunk =
Chunk(code: @[])
proc initChunk*(name: string): Chunk =
Chunk(code: @[], name: name, lines: @[], constants: @[])
proc writeChunk*(ch: var Chunk, code: uint8, line: int) =
ch.code.add(code)
@ -84,7 +85,7 @@ const argInstructions = {
const tripleMax*: int = 16777215
proc disassembleChunk*(ch: Chunk) =
echo "== Chunk begin =="
echo &"== Chunk {ch.name} begin =="
echo "index line instruction"
var c: int = 0
var lastLine = -1
@ -110,5 +111,5 @@ proc disassembleChunk*(ch: Chunk) =
except:
echo &"[{cFmt}] {lineFmt} Unknown opcode {instruction}"
c.inc
echo "== Chunk end =="
echo &"== Chunk {ch.name} end =="

View File

@ -72,8 +72,9 @@ proc newScope(comp: Compiler): Scope =
# HELPERS FOR THE COMPILER TYPE
proc newCompiler*(source: string): Compiler =
proc newCompiler*(name: string, source: string): Compiler =
result = new(Compiler)
result.chunk = initChunk(name)
result.source = source
result.hadError = false
result.panicMode = false

View File

@ -6,8 +6,8 @@ import config
type Result = enum
rsOK, rsCompileError, rsRuntimeError
proc interpret(source: string): Result =
let compiler = newCompiler(source)
proc interpret(name: string, source: string): Result =
let compiler = newCompiler(name, source)
compiler.compile()
if compiler.hadError:
return rsCompileError
@ -24,12 +24,12 @@ proc repl =
try:
let line = konLineEditor()
if line.len > 0:
discard interpret(line)
discard interpret("repl", line)
except ReadlineInterruptedException:
break
proc runFile(path: string) =
case interpret(readFile(path)):
case interpret(path, readFile(path)):
of rsCompileError:
quit 65
of rsRuntimeError:

View File

@ -3,7 +3,8 @@ import strformat
type
KonType* = enum
ktNil, ktBool, ktFloat, ktString,
ktTypeError
ktFunc,
ktTypeError,
const errorTypes = {ktTypeError}
@ -18,6 +19,10 @@ type
floatValue*: float64
of ktString:
stringValue*: string
of ktFunc:
module*: string # which chunk the function is compiled in
entryII*: int # entry instruction index
arity*: int # number of arguments
of errorTypes:
message*: string
@ -33,6 +38,8 @@ proc `$`*(val: KonValue): string =
return "nil"
of ktString:
return val.stringValue
of ktFunc:
return &"Function object: {val.module}/{val.entryII}"
of errorTypes:
let ename = $val.konType
return &"{ename[2..^1]}: {val.message}"
@ -59,6 +66,9 @@ proc equal*(val, right: KonValue): bool =
true
of ktString:
val.stringValue == right.stringValue
of ktFunc:
val.module == right.module and val.entryII == right.entryII
# same entry II/module but diff arity is a bug
of errorTypes:
false # error comparison is undefined