From 7a64aefac2efb718f58e299a12fa5fd895c1b657 Mon Sep 17 00:00:00 2001 From: Luke Lau Date: Sun, 10 Mar 2019 15:13:34 +0000 Subject: [PATCH] Add basic error handling --- Main.hs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/Main.hs b/Main.hs index f721911..29592b1 100644 --- a/Main.hs +++ b/Main.hs @@ -8,6 +8,7 @@ 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 @@ -20,14 +21,19 @@ 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 AST.Program asts <- read <$> getContents - let mdl = buildModule "main" $ mapM buildAST asts - withContext $ \ctx -> + 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 @@ -38,19 +44,21 @@ main = do 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 -- 2.30.2