]> git.mdlowis.com Git - proto/sclpl-rb.git/commitdiff
added basic arithmetic operators with proper precedence
authorMichael D. Lowis <mike@mdlowis.com>
Sat, 3 Aug 2019 02:43:01 +0000 (22:43 -0400)
committerMichael D. Lowis <mike@mdlowis.com>
Sat, 3 Aug 2019 02:43:01 +0000 (22:43 -0400)
compile.rb
example.src

index 399c6f3de0c6b8400cf9c96c31caa6bf2b971158..4f65af2311dd18ffe1a4e99e41f5c8eb2eed3d8e 100755 (executable)
@@ -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
index dd68e444b48d19259048b45d20b2779448c54b8c..8e99f2761e6179a7913a37d06a9b25d81042a55f 100644 (file)
@@ -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()