+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