Add doctests
[kaleidoscope-hs-old.git] / Main.hs
diff --git a/Main.hs b/Main.hs
index 2d838d339da3d1a04c5354fc8e920085aa565d0e..eba1ce1c7ae6e8072b4e78862c2daf750280bdd4 100644 (file)
--- a/Main.hs
+++ b/Main.hs
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RecursiveDo #-}
 
 module Main where
 
 import qualified AST
 
 module Main where
 
 import qualified AST
+import Control.Monad
+import Control.Monad.Trans.Class
+import qualified Data.Map as Map
 import qualified Data.Text.Lazy.IO as Text
 import qualified Data.Text.Lazy.IO as Text
+import Data.String
 import Foreign.Ptr
 import Foreign.Ptr
+import System.Exit
 import System.IO
 import LLVM.Context
 import System.IO
 import LLVM.Context
-import LLVM.CodeModel
 import LLVM.ExecutionEngine
 import LLVM.Module
 import LLVM.ExecutionEngine
 import LLVM.Module
+import LLVM.PassManager
 import LLVM.IRBuilder
 import LLVM.IRBuilder
+import LLVM.AST.AddrSpace
 import LLVM.AST.Constant
 import LLVM.AST.Float
 import LLVM.AST.Constant
 import LLVM.AST.Float
+import LLVM.AST.FloatingPointPredicate hiding (False, True)
 import LLVM.AST.Operand
 import LLVM.AST.Operand
-import LLVM.AST.Type
+import LLVM.AST.Type as Type
+import LLVM.AST.Typed
 import LLVM.Pretty
 
 import LLVM.Pretty
 
+type ModuleBuilderE = ModuleBuilderT (Either String)
+
 foreign import ccall "dynamic" exprFun :: FunPtr (IO Float) -> IO Float
 
 main :: IO ()
 main = do
 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
+  AST.Program asts <- read <$> getContents
+  let eitherMdl = buildModuleT "main" $ mapM buildAST asts
+  case eitherMdl of
+    Left err -> die err
+    Right mdl -> withContext $ \ctx -> do
+      hPutStrLn stderr "Before optimisation:"
       Text.hPutStrLn stderr (ppllvm mdl)
       Text.hPutStrLn stderr (ppllvm mdl)
-  withContext $ \ctx ->
       withMCJIT ctx Nothing Nothing Nothing Nothing $ \mcjit ->
         withModuleFromAST ctx mdl $ \mdl' ->
       withMCJIT ctx Nothing Nothing Nothing Nothing $ \mcjit ->
         withModuleFromAST ctx mdl $ \mdl' ->
+          withPassManager defaultCuratedPassSetSpec $ \pm -> do
+            runPassManager pm mdl' >>= guard
+            hPutStrLn stderr "After optimisation:"
+            Text.hPutStrLn stderr . ppllvm =<< moduleAST mdl'
             withModuleInEngine mcjit mdl' $ \emdl -> do
               Just f <- getFunction emdl "expr"
               let f' = castFunPtr f :: FunPtr (IO Float)
               exprFun f' >>= print
 
             withModuleInEngine mcjit mdl' $ \emdl -> do
               Just f <- getFunction emdl "expr"
               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.Add a b) = do
-  va <- build a
-  vb <- build b
-  fadd va vb
+evalProg :: AST.Program -> IO (Maybe Float)
+evalProg (AST.Program asts) = do
+  let eitherMdl = buildModuleT "main" $ mapM buildAST asts
+  case eitherMdl of
+    Left _ -> return Nothing
+    Right mdl -> withContext $ \ctx ->
+      withMCJIT ctx Nothing Nothing Nothing Nothing $ \mcjit ->
+        withModuleFromAST ctx mdl $ \mdl' ->
+          withModuleInEngine mcjit mdl' $ \emdl -> do
+            Just f <- getFunction emdl "expr"
+            let f' = castFunPtr f :: FunPtr (IO Float)
+            Just <$> exprFun f'
+
+-- | Builds up programs at the top-level of an LLVM Module
+-- >>> evalProg (read "31 - 5")
+-- Just 26.0
+buildAST :: AST.AST -> ModuleBuilderE Operand
+buildAST (AST.Function nameStr paramStrs body) = do
+  let n = fromString nameStr
+  function n 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
+
+-- | Builds up expressions, which are operands in LLVM IR
+-- >>> evalProg (read "def foo(x) x * 2; foo(6)")
+-- Just 12.0
+-- >>> evalProg (read "if 3 > 2 then 42 else 12")
+-- Just 42.0
+buildExpr :: Map.Map String Operand -> AST.Expr -> IRBuilderT ModuleBuilderE Operand
+buildExpr _ (AST.Num a) = pure $ ConstantOperand (Float (Single a))
+buildExpr binds (AST.Var n) = case binds Map.!? n of
+  Just x -> pure x
+  Nothing -> lift $ lift $ Left $ "'" <> n <> "' doesn't exist in scope"
+
+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
+                AST.Mul -> fmul
+                AST.Cmp GT -> fcmp OGT
+                AST.Cmp LT -> fcmp OLT
+                AST.Cmp EQ -> fcmp OEQ
+  instr va vb
+
+buildExpr binds (AST.If cond thenE elseE) = mdo
+  _ifB <- block `named` "if"
+
+  condV <- buildExpr binds cond
+  when (typeOf condV /= i1) $ lift $ lift $ Left "Not a boolean"
+  condBr condV thenB elseB
+
+  thenB <- block `named` "then"
+  thenOp <- buildExpr binds thenE
+  br mergeB
+
+  elseB <- block `named` "else"
+  elseOp <- buildExpr binds elseE
+  br mergeB
+
+  mergeB <- block `named` "ifcont"
+  phi [(thenOp, thenB), (elseOp, elseB)]