change table to array (thx ElegantBeef)

This commit is contained in:
prod2 2022-01-29 06:22:52 +01:00
parent 6d7337e6f7
commit 3ff351100e
1 changed files with 9 additions and 16 deletions

View File

@ -1,8 +1,6 @@
import strformat
import strutils
import sugar
import tables
import options
import scanner
import chunk
@ -177,7 +175,7 @@ proc markInitialized(comp: Compiler) =
# PARSE RULE/PRECEDENCE MISC
proc nop(comp: Compiler) = discard
var rules: Table[TokenType, ParseRule]
var rules: array[TokenType, ParseRule]
template genRule(ttype: TokenType, tprefix: (Compiler) -> void, tinfix: (Compiler) -> void, tprec: Precedence) =
if tprec == pcUnary:
raise newException(Exception, "pcUnary cannot be used as a rule precedence! Use pcNone for unary-only rules!")
@ -187,11 +185,8 @@ template genRule(ttype: TokenType, tprefix: (Compiler) -> void, tinfix: (Compile
raise newException(Exception, "Invalid rule: pcNone only allowed for unary operators and primary values, not for infix ones!")
rules[ttype] = ParseRule(name: $ttype, prefix: tprefix, infix: tinfix, prec: tprec)
proc getRule(opType: TokenType): Option[ParseRule] =
if rules.hasKey(opType):
some(rules[opType])
else:
none(ParseRule)
proc getRule(opType: TokenType): ParseRule =
rules[opType]
proc applyRule(rule: ParseRule): Precedence =
# returns the rule's precedence
@ -309,29 +304,27 @@ proc endScope(comp: Compiler) =
# EXPRESSIONS
proc parsePrecedence(comp: Compiler, prec: Precedence) =
comp.advance()
let rule = comp.previous.tokenType.getRule
let rule = comp.previous.tokenType.getRule()
if rule.isSome and rule.get.prefix != nop:
if rule.prefix != nop:
comp.canAssign = prec <= pcAssignment
let rule = rule.get
when debugCompiler:
debugEcho &"parsePrecedence call, valid prefix op found, rule used: {rule.name}, precedence: {prec}"
rule.prefix(comp)
while comp.current.tokenType.getRule.isSome and
prec <= comp.current.tokenType.getRule.get.prec:
while prec <= comp.current.tokenType.getRule().prec:
comp.advance()
# checked for isSome in the loop
# since advance moves current to previous
if comp.previous.tokenType.getRule.get.infix == nop:
if comp.previous.tokenType.getRule().infix == nop:
# should never happen, as having a precedence set
# means that it is a binary op
comp.error("Invalid rule table.")
return
else:
let infixRule = comp.previous.tokenType.getRule.get.infix
let infixRule = comp.previous.tokenType.getRule().infix
infixRule(comp)
else:
comp.error("Expect expression.")
@ -476,7 +469,7 @@ tkBang.genRule(unary, nop, pcNone)
proc binary(comp: Compiler) =
let opType = comp.previous.tokenType
# safety checked in parsePrecedence
let rule = opType.getRule.get
let rule = opType.getRule()
comp.parsePrecedence(rule.applyRule.increment)
case opType: