forked from nirum-lang/nirum
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Generalize CodeGen to use it for other targets (nirum-lang#67)
* [WIP] * Replace CodeGen with StateT to contain context properly * Fix 'fail' method of (CodeGen a) * [WIP] * Generalize CodeGen
- Loading branch information
Showing
5 changed files
with
290 additions
and
260 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-} | ||
module Nirum.CodeGen ( CodeGen | ||
, Failure | ||
, fromString | ||
, runCodeGen | ||
) where | ||
|
||
import Control.Applicative (Applicative) | ||
import Control.Monad (Monad) | ||
import Control.Monad.Except (MonadError, ExceptT(ExceptT), mapExceptT, runExceptT) | ||
import Control.Monad.State (MonadState, State, mapState, runState) | ||
import Data.Functor (Functor) | ||
|
||
|
||
newtype CodeGen s e a = CodeGen (ExceptT e (State s) a) | ||
deriving ( Applicative | ||
, Functor | ||
, MonadError e | ||
, MonadState s | ||
) | ||
|
||
class Failure s a where | ||
fromString :: MonadState s m => String -> m a | ||
|
||
instance (Failure s e) => Monad (CodeGen s e) where | ||
return a = CodeGen $ ExceptT $ return (Right a) | ||
{-# INLINE return #-} | ||
(CodeGen m) >>= k = CodeGen $ ExceptT $ do | ||
a <- runExceptT m | ||
case a of | ||
Left e -> return (Left e) | ||
Right x -> let CodeGen n = k x in runExceptT n | ||
{-# INLINE (>>=) #-} | ||
fail str = CodeGen $ mapExceptT mutate (fromString str) | ||
where | ||
mutate = mapState (\(a, s) -> case a of | ||
Left _ -> undefined | ||
Right e -> (Left e, s)) | ||
{-# INLINE fail #-} | ||
|
||
runCodeGen :: CodeGen s e a -> s -> (Either e a, s) | ||
runCodeGen (CodeGen a) = runState (runExceptT a) |
Oops, something went wrong.