Update AST to match Kaleidoscope more closely
[kaleidoscope-hs-old.git] / Main.hs
diff --git a/Main.hs b/Main.hs
index 8f4610af8b249920f0b03e67091804ad70c34faa..fcfe5dfff83e36cdf16525069f89620bf581e9df 100644 (file)
--- a/Main.hs
+++ b/Main.hs
@@ -3,27 +3,28 @@
 module Main where
 
 import qualified AST
+import qualified Data.Map as Map
 import qualified Data.Text.Lazy.IO as Text
+import           Data.String
 import Foreign.Ptr
 import System.IO
 import LLVM.Context
-import LLVM.CodeModel
 import LLVM.ExecutionEngine
 import LLVM.Module
 import LLVM.IRBuilder
+import LLVM.AST.AddrSpace
 import LLVM.AST.Constant
 import LLVM.AST.Float
 import LLVM.AST.Operand
-import LLVM.AST.Type
+import LLVM.AST.Type as Type
 import LLVM.Pretty
 
 foreign import ccall "dynamic" exprFun :: FunPtr (IO Float) -> IO Float
 
 main :: IO ()
 main = do
-  ast <- read <$> getContents
-  let mdl = buildModule "main" $
-        function "expr" [] float $ \_ -> build ast >>= ret
+  program <- read <$> getContents
+  let mdl = buildModule "main" $ mapM buildAST program
   Text.hPutStrLn stderr (ppllvm mdl)
   withContext $ \ctx ->
     withMCJIT ctx Nothing Nothing Nothing Nothing $ \mcjit ->
@@ -33,11 +34,32 @@ main = do
           let f' = castFunPtr f :: FunPtr (IO Float)
           exprFun f' >>= print
 
-build :: AST.Expr -> IRBuilderT ModuleBuilder Operand
-build (AST.Num a) = pure $ ConstantOperand (Float (Single a))
-build (AST.BinOp op a b) = do
-  va <- build a
-  vb <- build b
+buildAST :: AST.AST -> ModuleBuilder Operand
+buildAST (AST.Function nameStr paramStrs body) = do
+  let name = fromString nameStr
+  function name params float $ \binds -> do
+    let bindMap = Map.fromList (zip paramStrs binds)
+    buildExpr bindMap body >>= ret
+  where params = zip (repeat float) (map fromString paramStrs)
+buildAST (AST.Eval e) =
+  function "expr" [] float $ \_ -> buildExpr mempty e >>= ret
+
+buildExpr :: Map.Map String Operand -> AST.Expr -> IRBuilderT ModuleBuilder Operand
+buildExpr _ (AST.Num a) = pure $ ConstantOperand (Float (Single a))
+buildExpr binds (AST.Var name) = pure $ binds Map.! name
+
+buildExpr binds (AST.Call nameStr params) = do
+  paramOps <- mapM (buildExpr binds) params
+  let name = fromString nameStr
+      -- get a pointer to the function
+      typ = FunctionType float (replicate (length params) float) False
+      ptrTyp = Type.PointerType typ (AddrSpace 0)
+      ref = GlobalReference ptrTyp name
+  call (ConstantOperand ref) (zip paramOps (repeat []))
+
+buildExpr binds (AST.BinOp op a b) = do
+  va <- buildExpr binds a
+  vb <- buildExpr binds b
   let instr = case op of
                 AST.Add -> fadd
                 AST.Sub -> fsub