- ast <- read <$> getContents
- let mdl = buildModule "main" $
- function "expr" [] float $ \_ -> do
- build ast
- return ()
- Text.putStrLn (ppllvm mdl)
-
-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
+ 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 -> 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
+
+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
+ instr va vb