Parse more binary ops
[kaleidoscope-hs.git] / AST.hs
1 module AST where
2
3 import Text.Read 
4 import Text.ParserCombinators.ReadP hiding ((+++), choice)
5
6 data Expr = Num Float
7           | BinOp BinOp Expr Expr
8   deriving Show
9
10 data BinOp = Add | Sub | Mul | Cmp Ordering
11   deriving Show
12
13 instance Read Expr where
14   readPrec = choice [ parseNum
15                     , parseBinOp "<" 10 (Cmp LT)
16                     , parseBinOp "+" 20 Add
17                     , parseBinOp "-" 20 Sub
18                     , parseBinOp "*" 40 Mul
19                     ]
20     where parseNum = Num <$> readPrec
21           -- use 'prec 1' and 'step' so that parsing 'a'
22           -- can only go one step deep, to prevent ininfite
23           -- recursion
24           parseBinOp s prc op = prec prc $ do
25             a <- step readPrec
26             lift $ do
27               skipSpaces
28               string s
29               skipSpaces
30             b <- readPrec
31             return (BinOp op a b)
32