|
| 1 | +-- | Monad for declaring Huddle constructs |
| 2 | +module Codec.CBOR.Cuddle.Huddle.HuddleM |
| 3 | + ( module Huddle, |
| 4 | + (=:=), |
| 5 | + (=:~), |
| 6 | + (=::=), |
| 7 | + binding, |
| 8 | + setRootRules, |
| 9 | + huddleDef, |
| 10 | + huddleDef', |
| 11 | + include, |
| 12 | + ) |
| 13 | +where |
| 14 | + |
| 15 | +import Codec.CBOR.Cuddle.Huddle hiding (binding, (=:=), (=:~)) |
| 16 | +import Codec.CBOR.Cuddle.Huddle qualified as Huddle |
| 17 | +import Control.Monad.State.Strict (State, modify, runState) |
| 18 | +import Data.Default.Class (def) |
| 19 | +import Data.Generics.Product (HasField (..)) |
| 20 | +import Data.Text qualified as T |
| 21 | +import Optics.Core (Field2 (..), set, (%), (%~)) |
| 22 | + |
| 23 | +type HuddleM = State Huddle |
| 24 | + |
| 25 | +-- | Overridden version of assignment which also adds the rule to the state |
| 26 | +(=:=) :: (IsType0 a) => T.Text -> a -> HuddleM Rule |
| 27 | +n =:= b = let r = n Huddle.=:= b in include r |
| 28 | + |
| 29 | +infixl 1 =:= |
| 30 | + |
| 31 | +-- | Overridden version of group assignment which adds the rule to the state |
| 32 | +(=:~) :: T.Text -> Group -> HuddleM (Named Group) |
| 33 | +n =:~ b = let r = n Huddle.=:~ b in include r |
| 34 | + |
| 35 | +infixl 1 =:~ |
| 36 | + |
| 37 | +binding :: |
| 38 | + forall t0. |
| 39 | + (IsType0 t0) => |
| 40 | + (GRef -> Rule) -> |
| 41 | + HuddleM (t0 -> GRuleCall) |
| 42 | +binding fRule = include (Huddle.binding fRule) |
| 43 | + |
| 44 | +-- | Renamed version of Huddle's underlying '=:=' for use in generic bindings |
| 45 | +(=::=) :: (IsType0 a) => T.Text -> a -> Rule |
| 46 | +n =::= b = n Huddle.=:= b |
| 47 | + |
| 48 | +infixl 1 =::= |
| 49 | + |
| 50 | +setRootRules :: [Rule] -> HuddleM () |
| 51 | +setRootRules = modify . set (field @"roots") |
| 52 | + |
| 53 | +huddleDef :: HuddleM a -> Huddle |
| 54 | +huddleDef = snd . huddleDef' |
| 55 | + |
| 56 | +huddleDef' :: HuddleM a -> (a, Huddle) |
| 57 | +huddleDef' mh = (_2 % field @"items") %~ reverse $ runState mh def |
| 58 | + |
| 59 | +class Includable a where |
| 60 | + -- | Include a rule, group, or generic rule defined elsewhere |
| 61 | + include :: a -> HuddleM a |
| 62 | + |
| 63 | +instance Includable Rule where |
| 64 | + include r = modify (field @"items" %~ (HIRule r :)) >> pure r |
| 65 | + |
| 66 | +instance Includable (Named Group) where |
| 67 | + include r = modify ((field @"items") %~ (HIGroup r :)) >> pure r |
| 68 | + |
| 69 | +instance (IsType0 t0) => Includable (t0 -> GRuleCall) where |
| 70 | + include gr = |
| 71 | + let fakeT0 = error "Attempting to unwrap fake value in generic call" |
| 72 | + grDef = callToDef <$> gr fakeT0 |
| 73 | + in do |
| 74 | + modify (field @"items" %~ (HIGRule grDef :)) |
| 75 | + pure gr |
0 commit comments