Parse if expressions
authorLuke Lau <luke_lau@icloud.com>
Wed, 5 Jun 2019 21:09:41 +0000 (22:09 +0100)
committerLuke Lau <luke_lau@icloud.com>
Fri, 8 Nov 2019 15:07:25 +0000 (15:07 +0000)
Back to the AST.

AST.hs

diff --git a/AST.hs b/AST.hs
index 9ff555a74d10c6d970fc8b7df0a37c1d98fdbffc..1e505af4f47116e401e2523f10c90ac1c466c360 100644 (file)
--- a/AST.hs
+++ b/AST.hs
@@ -8,6 +8,7 @@ data Expr = Num Double
           | Var String
           | BinOp BinOp Expr Expr
           | Call String [Expr]
+          | If Expr Expr Expr
   deriving Show
 
 data BinOp = Add | Sub | Mul | Cmp Ordering
@@ -17,6 +18,7 @@ instance Read Expr where
   readPrec = parens $ choice [ parseNum
                              , parseVar
                              , parseCall
+                             , parseIf
                              , parseBinOp "<" 10 (Cmp LT)
                              , parseBinOp ">" 10 (Cmp GT)
                              , parseBinOp "==" 10 (Cmp EQ)
@@ -40,6 +42,14 @@ instance Read Expr where
                         sepBy (readS_to_P reads)
                               (skipSpaces >> char ',' >> skipSpaces)
             return (Call func params)
+          parseIf = do
+            lift $ skipSpaces >> string "if" >> skipSpaces
+            cond <- readPrec
+            lift $ skipSpaces >> string "then" >> skipSpaces
+            thenE <- readPrec
+            lift $ skipSpaces >> string "else" >> skipSpaces
+            elseE <- readPrec
+            return (If cond thenE elseE)
             
 data Prototype = Prototype String [String]
   deriving Show