projects
/
kaleidoscope-hs-old.git
/ blobdiff
commit
grep
author
committer
pickaxe
?
search:
re
summary
|
shortlog
|
log
|
commit
|
commitdiff
|
tree
raw
|
inline
| side by side
Extend AST for functions, calls and variables
[kaleidoscope-hs-old.git]
/
AST.hs
diff --git
a/AST.hs
b/AST.hs
index 424cfbe7b13010e0960e4b88a1675cdcfa3b3f0f..2bea0028cf47bb61f94c982f011ca24b72a612ac 100644
(file)
--- a/
AST.hs
+++ b/
AST.hs
@@
-1,21
+1,51
@@
module AST where
module AST where
+import Data.Char
import Text.Read
import Text.ParserCombinators.ReadP hiding ((+++), choice)
import Text.Read
import Text.ParserCombinators.ReadP hiding ((+++), choice)
-data BinOpType = Add | Sub | Mul
+data AST = Function String [String] Expr
+ | Eval Expr
deriving Show
data Expr = Num Float
| BinOp BinOpType Expr Expr
deriving Show
data Expr = Num Float
| BinOp BinOpType Expr Expr
+ | Var String
+ | Call String [Expr]
+ deriving Show
+data BinOpType = Add | Sub | Mul
deriving Show
deriving Show
+instance Read AST where
+ readPrec = parseFunction +++ (Eval <$> readPrec)
+ where parseFunction = lift $ do
+ skipSpaces
+ string "def"
+ skipSpaces
+ name <- munch1 isAlpha
+ params <- between (char '(') (char ')') $
+ sepBy (munch1 isAlpha) skipSpaces
+ skipSpaces
+ body <- between (char '{') (char '}') $
+ readS_to_P reads
+ skipSpaces
+ return (Function name params body)
+
instance Read Expr where
readPrec = choice [ parseNum
instance Read Expr where
readPrec = choice [ parseNum
+ , parseVar
+ , parseCall
, parseBinOp '+' Add
, parseBinOp '-' Sub
, parseBinOp '*' Mul
]
where parseNum = Num <$> readPrec
, parseBinOp '+' Add
, parseBinOp '-' Sub
, parseBinOp '*' Mul
]
where parseNum = Num <$> readPrec
+ parseVar = Var <$> lift (munch1 isAlpha)
+ parseCall = do
+ func <- lift (munch1 isAlpha)
+ params <- lift $ between (char '(') (char ')') $
+ sepBy (readS_to_P reads)
+ (skipSpaces >> char ',' >> skipSpaces)
+ return (Call func params)
parseBinOp c typ = step $ do
a <- prec 11 readPrec
lift $ do
parseBinOp c typ = step $ do
a <- prec 11 readPrec
lift $ do