-- | Small operations missing from the public free-foil API.
--
-- This is the only module in the new checker that uses
-- "Control.Monad.Foil.Internal". These operations are candidates for
-- upstreaming to free-foil; callers should not use the underlying 'IntMap'
-- representations of 'NameMap' or 'Substitution'.
module Rzk.Check.Foil.Extras
  ( replaceName
  , nameMapFromList
  , singletonSubstitution
  ) where

import           Control.Monad.Foil          (Name, NameMap, Substitution)
import qualified Control.Monad.Foil          as Foil
import           Control.Monad.Foil.Internal (NameMap (..), Substitution (..))
import qualified Data.IntMap                 as IntMap

-- | Replace the value at an existing key in a total name map. The caller
-- guarantees that the key is present, as in the entry map of a context.
replaceName :: Name n -> a -> NameMap n a -> NameMap n a
replaceName :: forall (n :: S) a. Name n -> a -> NameMap n a -> NameMap n a
replaceName Name n
name a
value (NameMap IntMap a
m) = IntMap a -> NameMap n a
forall (n :: S) a. IntMap a -> NameMap n a
NameMap (Key -> a -> IntMap a -> IntMap a
forall a. Key -> a -> IntMap a -> IntMap a
IntMap.insert (Name n -> Key
forall (l :: S). Name l -> Key
Foil.nameId Name n
name) a
value IntMap a
m)

-- | Build a total name map from all scoped names and their values. Later
-- duplicate entries win; the caller supplies every name in the scope.
nameMapFromList :: [(Name n, a)] -> NameMap n a
nameMapFromList :: forall (n :: S) a. [(Name n, a)] -> NameMap n a
nameMapFromList [(Name n, a)]
entries = IntMap a -> NameMap n a
forall (n :: S) a. IntMap a -> NameMap n a
NameMap ([(Key, a)] -> IntMap a
forall a. [(Key, a)] -> IntMap a
IntMap.fromList [ (Name n -> Key
forall (l :: S). Name l -> Key
Foil.nameId Name n
name, a
value) | (Name n
name, a
value) <- [(Name n, a)]
entries ])

-- | A substitution with one free name mapped to one value.
singletonSubstitution :: Name i -> e o -> Substitution e i o
singletonSubstitution :: forall (i :: S) (e :: S -> *) (o :: S).
Name i -> e o -> Substitution e i o
singletonSubstitution Name i
name e o
value = IntMap (e o) -> Substitution e i o
forall (e :: S -> *) (i :: S) (o :: S).
IntMap (e o) -> Substitution e i o
UnsafeSubstitution (Key -> e o -> IntMap (e o)
forall a. Key -> a -> IntMap a
IntMap.singleton (Name i -> Key
forall (l :: S). Name l -> Key
Foil.nameId Name i
name) e o
value)