module CodeGen.RiscV.Runner (compileToRiscVAsm) where

import CodeGen.Module (compileToModule)
import CodeGen.RiscV.AsmGen (ppRiscVAsm)
import CodeGen.TimedValue (TimedValue, measureTimedValue)
import Control.Monad.Except (runExcept)
import Data.Text (Text)
import qualified Data.Text.IO as Txt
import System.IO (IOMode (WriteMode), withFile)

compileToRiscVAsm :: Text -> FilePath -> IO (TimedValue (Either Text ()))
compileToRiscVAsm :: Text -> FilePath -> IO (TimedValue (Either Text ()))
compileToRiscVAsm Text
text FilePath
outputFilePath = IO (Either Text ()) -> IO (TimedValue (Either Text ()))
forall a. IO a -> IO (TimedValue a)
measureTimedValue (IO (Either Text ()) -> IO (TimedValue (Either Text ())))
-> IO (Either Text ()) -> IO (TimedValue (Either Text ()))
forall a b. (a -> b) -> a -> b
$
  Either Text (IO ()) -> IO (Either Text ())
forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
forall (f :: * -> *) a.
Applicative f =>
Either Text (f a) -> f (Either Text a)
sequenceA (Either Text (IO ()) -> IO (Either Text ()))
-> Either Text (IO ()) -> IO (Either Text ())
forall a b. (a -> b) -> a -> b
$
    Except Text (IO ()) -> Either Text (IO ())
forall e a. Except e a -> Either e a
runExcept (Except Text (IO ()) -> Either Text (IO ()))
-> Except Text (IO ()) -> Either Text (IO ())
forall a b. (a -> b) -> a -> b
$ do
      Module
m <- Text -> Except Text Module
compileToModule Text
text
      let riscVText :: Text
riscVText = Module -> Text
ppRiscVAsm Module
m
      IO () -> Except Text (IO ())
forall a. a -> ExceptT Text Identity a
forall (m :: * -> *) a. Monad m => a -> m a
return (IO () -> Except Text (IO ())) -> IO () -> Except Text (IO ())
forall a b. (a -> b) -> a -> b
$
        FilePath -> IOMode -> (Handle -> IO ()) -> IO ()
forall r. FilePath -> IOMode -> (Handle -> IO r) -> IO r
withFile FilePath
outputFilePath IOMode
WriteMode ((Handle -> IO ()) -> IO ()) -> (Handle -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \Handle
handle -> do
          Handle -> Text -> IO ()
Txt.hPutStrLn Handle
handle Text
riscVText