From 1c4653479cdcfe88102c07a509bb805cbf5e8830 Mon Sep 17 00:00:00 2001 From: "Michael D. Lowis" Date: Fri, 2 Aug 2019 22:43:01 -0400 Subject: [PATCH] added basic arithmetic operators with proper precedence --- compile.rb | 37 ++++++++++++++++++++++++++++++------- example.src | 2 +- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/compile.rb b/compile.rb index 399c6f3..4f65af2 100755 --- a/compile.rb +++ b/compile.rb @@ -104,7 +104,7 @@ class Lexer SPACE = /[ \t\v\n\r]+/ IDENT = /[_a-zA-Z][_a-zA-Z0-9]*/ BRACES = /[\(\)\[\]\{\}]/ - OPERATORS = /=/ + OPERATORS = /[*\/=+-]/ INTEGER = /[0-9]+/ ID_TYPES = { "requires" => :requires, @@ -158,12 +158,18 @@ class Parser unary: 8, call: 9, primary: 10, - eof: 11 + eof: 11, } + LVLNAMES = LEVELS.keys + RULES = { - "(" => { prefix: :grouping, infix: :func_call, level: :call }, - :int => { prefix: :constant, infix: nil, level: :none }, + "(" => { prefix: :grouping, infix: :func_call, level: :call }, + "+" => { prefix: :unary, infix: :binary, level: :term }, + "-" => { prefix: :unary, infix: :binary, level: :term }, + "*" => { prefix: nil, infix: :binary, level: :factor }, + "/" => { prefix: nil, infix: :binary, level: :factor }, + :int => { prefix: :constant, infix: nil, level: :none }, } def initialize(path) @@ -213,7 +219,7 @@ class Parser expect("=") value = expression() end - p "value", value + pp value end def declaration(syms) @@ -293,7 +299,25 @@ class Parser def func_call(ast) expect(")") - ast + AST::Apply.new(nil, ast, []) + end + + def unary() + type = @prev.type + AST::Apply.new(nil, @prev.type, [parseLevel(:unary)]) + end + + def nextLevel(tok) + level = getRule(@prev)[:level] + index = LVLNAMES.find_index(level) + LVLNAMES[index + 1] + end + + def binary(left) + type = @prev.type + nlvl = nextLevel(type) + right = parseLevel(nlvl) + AST::Apply.new(nil, type, [left, right]) end def error(str) @@ -356,7 +380,6 @@ class Package end def dump - require 'pp' pp @definitions end end diff --git a/example.src b/example.src index dd68e44..8e99f27 100644 --- a/example.src +++ b/example.src @@ -4,7 +4,7 @@ provides { fun main(args string[]) int } -let foo int = (42) +let foo int = 1 * 2 + 3 fun main(args string[]) int { 42() -- 2.52.0