Fixed minor bug in the interpreter

This commit is contained in:
nocturn9x 2020-08-10 18:39:53 +02:00
parent 14442a659f
commit 22e35b9a46
5 changed files with 22 additions and 10 deletions

View File

@ -243,9 +243,10 @@ proc getRule(kind: TokenType): ParseRule =
proc compile*(self: Compiler, source: string, chunk: Chunk): bool =
var scanner = initLexer(source)
var tokens = scanner.lex()
self.parser = initParser(tokens)
self.compilingChunk = chunk
self.expression()
self.parser.consume(EOF, "Expecting end of file")
self.endCompiler()
if len(tokens) > 1 and not scanner.errored:
self.parser = initParser(tokens)
self.compilingChunk = chunk
self.expression()
self.parser.consume(EOF, "Expecting end of file")
self.endCompiler()
return not self.parser.hadError

View File

@ -36,10 +36,11 @@ type Lexer* = object
line: int
start: int
current: int
errored*: bool
proc initLexer*(source: string): Lexer =
result = Lexer(source: source, tokens: @[], line: 1, start: 0, current: 0)
result = Lexer(source: source, tokens: @[], line: 1, start: 0, current: 0, errored: false)
proc done(self: Lexer): bool =
@ -90,7 +91,8 @@ proc parseString(self: var Lexer, delimiter: char) =
self.line = self.line + 1
discard self.step()
if self.done():
quit(&"Unterminated string literal at {self.line}")
echo &"SyntaxError: Unterminated string literal at line {self.line}"
self.errored = true
discard self.step()
let value = Value(kind: ValueTypes.OBJECT, obj: Obj(kind: ObjectTypes.STRING, str: self.source[self.start..<self.current - 1])) # Get the value between quotes
let token = self.createToken(STR, value)
@ -137,7 +139,8 @@ proc parseComment(self: var Lexer) =
break
discard self.step()
if self.done() and not closed:
quit(&"Unexpected EOF at line {self.line}")
self.errored = true
echo &"SyntaxError: Unexpected EOF at line {self.line}"
proc scanToken(self: var Lexer) =
@ -171,7 +174,8 @@ proc scanToken(self: var Lexer) =
else:
self.tokens.add(self.createToken(TOKENS[single], Value(kind: ValueTypes.OBJECT, obj: Obj(kind: ObjectTypes.STRING, str: &"{single}"))))
else:
quit(&"Unexpected character '{single}' at {self.line}")
self.errored = true
echo &"SyntaxError: Unexpected character '{single}' at {self.line}"
proc lex*(self: var Lexer): seq[Token] =

BIN
nim/main Executable file

Binary file not shown.

6
nim/types/exceptions.nim Normal file
View File

@ -0,0 +1,6 @@
import ../meta/valueobject
func newTypeError*(): Obj =
result = Obj(kind: ObjectTypes.EXCEPTION, errName: Obj(kind: STRING, str: "TypeError"))

View File

@ -124,7 +124,8 @@ proc interpret*(self: var VM, source: string, debug: bool = false): InterpretRes
return COMPILE_ERROR
self.chunk = chunk
self.ip = 0
result = self.run(debug)
if len(chunk.code) > 1:
result = self.run(debug)
chunk.freeChunk()