Start parsing expressions
[kaleidoscope-hs.git] / AST.hs
diff --git a/AST.hs b/AST.hs
new file mode 100644 (file)
index 0000000..5628e7c
--- /dev/null
+++ b/AST.hs
@@ -0,0 +1,23 @@
+module AST where
+
+import Text.Read 
+import Text.ParserCombinators.ReadP hiding ((+++))
+
+data Expr = Num Float
+          | Add Expr Expr
+  deriving Show
+
+instance Read Expr where
+  readPrec = parseNum +++ parseAdd
+    where parseNum = Num <$> readPrec
+          -- use 'prec 1' and 'step' so that parsing 'a'
+          -- can only go one step deep, to prevent ininfite
+          -- recursion
+          parseAdd = prec 1 $ do
+            a <- step readPrec
+            lift $ do
+              skipSpaces
+              char '+'
+              skipSpaces
+            b <- readPrec
+            return (Add a b)