X-Git-Url: https://git.lukelau.me/?p=kaleidoscope-hs-old.git;a=blobdiff_plain;f=Main.hs;h=29592b18b0d3a4612c7d034bfae4822e12ef04d9;hp=fcfe5dfff83e36cdf16525069f89620bf581e9df;hb=7a64aefac2efb718f58e299a12fa5fd895c1b657;hpb=808a6ae35fb1f2ff61a84991af1e7722298a4d62 diff --git a/Main.hs b/Main.hs index fcfe5df..29592b1 100644 --- a/Main.hs +++ b/Main.hs @@ -8,9 +8,11 @@ import qualified Data.Text.Lazy.IO as Text import Data.String import Foreign.Ptr import System.IO +import System.Exit import LLVM.Context import LLVM.ExecutionEngine import LLVM.Module +import LLVM.PassManager import LLVM.IRBuilder import LLVM.AST.AddrSpace import LLVM.AST.Constant @@ -18,35 +20,45 @@ import LLVM.AST.Float import LLVM.AST.Operand import LLVM.AST.Type as Type import LLVM.Pretty +import Control.Monad +import Control.Monad.Trans.Class + +type ModuleBuilderE = ModuleBuilderT (Either String) foreign import ccall "dynamic" exprFun :: FunPtr (IO Float) -> IO Float main :: IO () main = do - program <- read <$> getContents - let mdl = buildModule "main" $ mapM buildAST program - Text.hPutStrLn stderr (ppllvm mdl) - withContext $ \ctx -> + AST.Program asts <- read <$> getContents + let eitherMdl = buildModuleT "main" $ mapM buildAST asts + case eitherMdl of + Left err -> die err + Right mdl -> withContext $ \ctx -> withMCJIT ctx Nothing Nothing Nothing Nothing $ \mcjit -> withModuleFromAST ctx mdl $ \mdl' -> + withPassManager defaultCuratedPassSetSpec $ \pm -> do + runPassManager pm mdl' >>= guard + 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 -buildAST :: AST.AST -> ModuleBuilder Operand +buildAST :: AST.AST -> ModuleBuilderE Operand buildAST (AST.Function nameStr paramStrs body) = do - let name = fromString nameStr - function name params float $ \binds -> 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 -buildExpr :: Map.Map String Operand -> AST.Expr -> IRBuilderT ModuleBuilder Operand +buildExpr :: Map.Map String Operand -> AST.Expr -> IRBuilderT ModuleBuilderE Operand buildExpr _ (AST.Num a) = pure $ ConstantOperand (Float (Single a)) -buildExpr binds (AST.Var name) = pure $ binds Map.! name +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