X-Git-Url: http://git.lukelau.me/?a=blobdiff_plain;f=AST.hs;h=ae18a52347ce91c37336a06f891bae690ba691ec;hb=0d4ed473c520786af90ab70dac51451ea2b8b941;hp=7dad3a19e91eab9f12657101bd224b5c81742d07;hpb=310a2212dfb2014e8ac7efd1a5d7599a7f9d4057;p=kaleidoscope-hs.git diff --git a/AST.hs b/AST.hs index 7dad3a1..ae18a52 100644 --- a/AST.hs +++ b/AST.hs @@ -4,18 +4,24 @@ import Data.Char import Text.Read import Text.ParserCombinators.ReadP hiding ((+++), choice) -data Expr = Num Float +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 deriving Show instance Read Expr where - readPrec = choice [ parseNum + readPrec = parens $ choice [ parseNum , parseVar + , parseCall + , parseIf , parseBinOp "<" 10 (Cmp LT) + , parseBinOp ">" 10 (Cmp GT) + , parseBinOp "==" 10 (Cmp EQ) , parseBinOp "+" 20 Add , parseBinOp "-" 20 Sub , parseBinOp "*" 40 Mul @@ -24,12 +30,24 @@ instance Read Expr where parseVar = Var <$> lift (munch1 isAlpha) parseBinOp s prc op = prec prc $ do a <- step readPrec - lift $ do - skipSpaces - string s - skipSpaces + spaced $ string s b <- readPrec return (BinOp op a b) + parseCall = do + func <- lift (munch1 isAlpha) + params <- lift $ between (char '(') (char ')') $ + sepBy (readS_to_P reads) + (skipSpaces >> char ',' >> skipSpaces) + return (Call func params) + parseIf = do + spaced $ string "if" + cond <- readPrec + spaced $ string "then" + thenE <- readPrec + spaced $ string "else" + elseE <- readPrec + return (If cond thenE elseE) + spaced f = lift $ skipSpaces >> f >> skipSpaces data Prototype = Prototype String [String] deriving Show