{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | See <https://github.com/ezyang/ghc-proposals/blob/backpack/proposals/0000-backpack.rst>
module Distribution.Backpack.UnifyM (
    -- * Unification monad
    UnifyM,
    runUnifyM,
    failWith,
    addErr,
    failIfErrs,
    tryM,
    addErrContext,
    addErrContextM,
    liftST,

    UnifEnv(..),
    getUnifEnv,

    -- * Modules and unit IDs
    ModuleU,
    ModuleU'(..),
    convertModule,
    convertModuleU,

    UnitIdU,
    UnitIdU'(..),
    convertUnitId,
    convertUnitIdU,

    ModuleSubstU,
    convertModuleSubstU,
    convertModuleSubst,

    ModuleScopeU,
    emptyModuleScopeU,
    convertModuleScopeU,

    ModuleWithSourceU,

    convertInclude,
    convertModuleProvides,
    convertModuleProvidesU,

) where

import Prelude ()
import Distribution.Compat.Prelude hiding (mod)

import Distribution.Backpack.ModuleShape
import Distribution.Backpack.ModuleScope
import Distribution.Backpack.ModSubst
import Distribution.Backpack.FullUnitId
import Distribution.Backpack

import qualified Distribution.Utils.UnionFind as UnionFind
import Distribution.ModuleName
import Distribution.Package
import Distribution.PackageDescription
import Distribution.Pretty
import Distribution.Types.ComponentInclude
import Distribution.Types.AnnotatedId
import Distribution.Verbosity

import Data.STRef
import Data.Traversable
import Control.Monad.ST
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Text.PrettyPrint

-- TODO: more detailed trace output on high verbosity would probably
-- be appreciated by users debugging unification errors.  Collect
-- some good examples!

data ErrMsg = ErrMsg {
        ErrMsg -> Doc
err_msg :: Doc,
        ErrMsg -> [Doc]
err_ctx :: [Doc]
    }
type MsgDoc = Doc

renderErrMsg :: ErrMsg -> MsgDoc
renderErrMsg :: ErrMsg -> Doc
renderErrMsg ErrMsg { err_msg :: ErrMsg -> Doc
err_msg = Doc
msg, err_ctx :: ErrMsg -> [Doc]
err_ctx = [Doc]
ctx } =
    Doc
msg Doc -> Doc -> Doc
$$ [Doc] -> Doc
vcat [Doc]
ctx

-- | The unification monad, this monad encapsulates imperative
-- unification.
newtype UnifyM s a = UnifyM { forall s a. UnifyM s a -> UnifEnv s -> ST s (Maybe a)
unUnifyM :: UnifEnv s -> ST s (Maybe a) }

-- | Run a computation in the unification monad.
runUnifyM :: Verbosity -> ComponentId -> FullDb -> (forall s. UnifyM s a) -> Either [MsgDoc] a
runUnifyM :: forall a.
Verbosity
-> ComponentId
-> FullDb
-> (forall s. UnifyM s a)
-> Either [Doc] a
runUnifyM Verbosity
verbosity ComponentId
self_cid FullDb
db forall s. UnifyM s a
m
    = forall a. (forall s. ST s a) -> a
runST forall a b. (a -> b) -> a -> b
$ do STRef s Int
i    <- forall a s. a -> ST s (STRef s a)
newSTRef Int
0
                 STRef s (Map ModuleName (ModuleU s))
hmap <- forall a s. a -> ST s (STRef s a)
newSTRef forall k a. Map k a
Map.empty
                 STRef s [ErrMsg]
errs <- forall a s. a -> ST s (STRef s a)
newSTRef []
                 Maybe a
mb_r <- forall s a. UnifyM s a -> UnifEnv s -> ST s (Maybe a)
unUnifyM forall s. UnifyM s a
m UnifEnv {
                            unify_uniq :: STRef s Int
unify_uniq = STRef s Int
i,
                            unify_reqs :: STRef s (Map ModuleName (ModuleU s))
unify_reqs = STRef s (Map ModuleName (ModuleU s))
hmap,
                            unify_self_cid :: ComponentId
unify_self_cid = ComponentId
self_cid,
                            unify_verbosity :: Verbosity
unify_verbosity = Verbosity
verbosity,
                            unify_ctx :: [Doc]
unify_ctx = [],
                            unify_db :: FullDb
unify_db = FullDb
db,
                            unify_errs :: STRef s [ErrMsg]
unify_errs = STRef s [ErrMsg]
errs }
                 [ErrMsg]
final_errs <- forall s a. STRef s a -> ST s a
readSTRef STRef s [ErrMsg]
errs
                 case Maybe a
mb_r of
                    Just a
x | forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ErrMsg]
final_errs -> forall (m :: * -> *) a. Monad m => a -> m a
return (forall a b. b -> Either a b
Right a
x)
                    Maybe a
_ -> forall (m :: * -> *) a. Monad m => a -> m a
return (forall a b. a -> Either a b
Left (forall a b. (a -> b) -> [a] -> [b]
map ErrMsg -> Doc
renderErrMsg (forall a. [a] -> [a]
reverse [ErrMsg]
final_errs)))
-- NB: GHC 7.6 throws a hissy fit if you pattern match on 'm'.

type ErrCtx s = MsgDoc

-- | The unification environment.
data UnifEnv s = UnifEnv {
        -- | A supply of unique integers to label 'UnitIdU'
        -- cells.  This is used to determine loops in unit
        -- identifiers (which can happen with mutual recursion.)
        forall s. UnifEnv s -> UnifRef s Int
unify_uniq :: UnifRef s UnitIdUnique,
        -- | The set of requirements in scope.  When
        -- a provision is brought into scope, we unify with
        -- the requirement at the same module name to fill it.
        -- This mapping grows monotonically.
        forall s. UnifEnv s -> UnifRef s (Map ModuleName (ModuleU s))
unify_reqs :: UnifRef s (Map ModuleName (ModuleU s)),
        -- | Component id of the unit we're linking.  We use this
        -- to detect if we fill a requirement with a local module,
        -- which in principle should be OK but is not currently
        -- supported by GHC.
        forall s. UnifEnv s -> ComponentId
unify_self_cid :: ComponentId,
        -- | How verbose the error message should be
        forall s. UnifEnv s -> Verbosity
unify_verbosity :: Verbosity,
        -- | The error reporting context
        forall s. UnifEnv s -> [Doc]
unify_ctx :: [ErrCtx s],
        -- | The package index for expanding unit identifiers
        forall s. UnifEnv s -> FullDb
unify_db :: FullDb,
        -- | Accumulated errors
        forall s. UnifEnv s -> UnifRef s [ErrMsg]
unify_errs :: UnifRef s [ErrMsg]
    }

instance Functor (UnifyM s) where
    fmap :: forall a b. (a -> b) -> UnifyM s a -> UnifyM s b
fmap a -> b
f (UnifyM UnifEnv s -> ST s (Maybe a)
m) = forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> b
f)) UnifEnv s -> ST s (Maybe a)
m)

instance Applicative (UnifyM s) where
    pure :: forall a. a -> UnifyM s a
pure = forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (f :: * -> *) a. Applicative f => a -> f a
pure forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (f :: * -> *) a. Applicative f => a -> f a
pure forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (f :: * -> *) a. Applicative f => a -> f a
pure
    UnifyM UnifEnv s -> ST s (Maybe (a -> b))
f <*> :: forall a b. UnifyM s (a -> b) -> UnifyM s a -> UnifyM s b
<*> UnifyM UnifEnv s -> ST s (Maybe a)
x = forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM forall a b. (a -> b) -> a -> b
$ \UnifEnv s
r -> do
        Maybe (a -> b)
f' <- UnifEnv s -> ST s (Maybe (a -> b))
f UnifEnv s
r
        case Maybe (a -> b)
f' of
          Maybe (a -> b)
Nothing -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
          Just a -> b
f'' -> do
              Maybe a
x' <- UnifEnv s -> ST s (Maybe a)
x UnifEnv s
r
              case Maybe a
x' of
                  Maybe a
Nothing -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
                  Just a
x'' -> forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. a -> Maybe a
Just (a -> b
f'' a
x''))

instance Monad (UnifyM s) where
    return :: forall a. a -> UnifyM s a
return = forall (f :: * -> *) a. Applicative f => a -> f a
pure
    UnifyM UnifEnv s -> ST s (Maybe a)
m >>= :: forall a b. UnifyM s a -> (a -> UnifyM s b) -> UnifyM s b
>>= a -> UnifyM s b
f = forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM forall a b. (a -> b) -> a -> b
$ \UnifEnv s
r -> do
        Maybe a
x <- UnifEnv s -> ST s (Maybe a)
m UnifEnv s
r
        case Maybe a
x of
            Maybe a
Nothing -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing
            Just a
x' -> forall s a. UnifyM s a -> UnifEnv s -> ST s (Maybe a)
unUnifyM (a -> UnifyM s b
f a
x') UnifEnv s
r

-- | Lift a computation from 'ST' monad to 'UnifyM' monad.
-- Internal use only.
liftST :: ST s a -> UnifyM s a
liftST :: forall s a. ST s a -> UnifyM s a
liftST ST s a
m = forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM forall a b. (a -> b) -> a -> b
$ \UnifEnv s
_ -> forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a. a -> Maybe a
Just ST s a
m

addErr :: MsgDoc -> UnifyM s ()
addErr :: forall s. Doc -> UnifyM s ()
addErr Doc
msg = do
    UnifEnv s
env <- forall s. UnifyM s (UnifEnv s)
getUnifEnv
    let err :: ErrMsg
err = ErrMsg {
                err_msg :: Doc
err_msg = Doc
msg,
                err_ctx :: [Doc]
err_ctx = forall s. UnifEnv s -> [Doc]
unify_ctx UnifEnv s
env
              }
    forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall s a. STRef s a -> (a -> a) -> ST s ()
modifySTRef (forall s. UnifEnv s -> UnifRef s [ErrMsg]
unify_errs UnifEnv s
env) (\[ErrMsg]
errs -> ErrMsg
errforall a. a -> [a] -> [a]
:[ErrMsg]
errs)

failWith :: MsgDoc -> UnifyM s a
failWith :: forall s a. Doc -> UnifyM s a
failWith Doc
msg = do
    forall s. Doc -> UnifyM s ()
addErr Doc
msg
    forall s a. UnifyM s a
failM

failM :: UnifyM s a
failM :: forall s a. UnifyM s a
failM = forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM forall a b. (a -> b) -> a -> b
$ \UnifEnv s
_ -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a. Maybe a
Nothing

failIfErrs :: UnifyM s ()
failIfErrs :: forall s. UnifyM s ()
failIfErrs = do
    UnifEnv s
env <- forall s. UnifyM s (UnifEnv s)
getUnifEnv
    [ErrMsg]
errs <- forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall s a. STRef s a -> ST s a
readSTRef (forall s. UnifEnv s -> UnifRef s [ErrMsg]
unify_errs UnifEnv s
env)
    forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ErrMsg]
errs)) forall s a. UnifyM s a
failM

tryM :: UnifyM s a -> UnifyM s (Maybe a)
tryM :: forall s a. UnifyM s a -> UnifyM s (Maybe a)
tryM UnifyM s a
m =
    forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM (\UnifEnv s
env -> do
        Maybe a
mb_r <- forall s a. UnifyM s a -> UnifEnv s -> ST s (Maybe a)
unUnifyM UnifyM s a
m UnifEnv s
env
        forall (m :: * -> *) a. Monad m => a -> m a
return (forall a. a -> Maybe a
Just Maybe a
mb_r))

{-
otherFail :: ErrMsg -> UnifyM s a
otherFail s = UnifyM $ \_ -> return (Left s)

unifyFail :: ErrMsg -> UnifyM s a
unifyFail err = do
    env <- getUnifEnv
    msg <- case unify_ctx env of
        Nothing -> return (text "Unspecified unification error:" <+> err)
        Just (ctx, mod1, mod2)
            | unify_verbosity env > normal
            -> do mod1' <- convertModuleU mod1
                  mod2' <- convertModuleU mod2
                  let extra = " (was unifying " ++ display mod1'
                                     ++ " and " ++ display mod2' ++ ")"
                  return (ctx ++ err ++ extra)
            | otherwise
            -> return (ctx ++ err ++ " (for more information, pass -v flag)")
    UnifyM $ \_ -> return (Left msg)
-}

-- | A convenient alias for mutable references in the unification monad.
type UnifRef s a = STRef s a

-- | Imperatively read a 'UnifRef'.
readUnifRef :: UnifRef s a -> UnifyM s a
readUnifRef :: forall s a. UnifRef s a -> UnifyM s a
readUnifRef = forall s a. ST s a -> UnifyM s a
liftST forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s a. STRef s a -> ST s a
readSTRef

-- | Imperatively write a 'UnifRef'.
writeUnifRef :: UnifRef s a -> a -> UnifyM s ()
writeUnifRef :: forall s a. UnifRef s a -> a -> UnifyM s ()
writeUnifRef UnifRef s a
x = forall s a. ST s a -> UnifyM s a
liftST forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s a. STRef s a -> a -> ST s ()
writeSTRef UnifRef s a
x

-- | Get the current unification environment.
getUnifEnv :: UnifyM s (UnifEnv s)
getUnifEnv :: forall s. UnifyM s (UnifEnv s)
getUnifEnv = forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM forall a b. (a -> b) -> a -> b
$ \UnifEnv s
r -> forall (m :: * -> *) a. Monad m => a -> m a
return (forall (m :: * -> *) a. Monad m => a -> m a
return UnifEnv s
r)

-- | Add a fixed message to the error context.
addErrContext :: Doc -> UnifyM s a -> UnifyM s a
addErrContext :: forall s a. Doc -> UnifyM s a -> UnifyM s a
addErrContext Doc
ctx UnifyM s a
m = forall s a. Doc -> UnifyM s a -> UnifyM s a
addErrContextM Doc
ctx UnifyM s a
m

-- | Add a message to the error context.  It may make monadic queries.
addErrContextM :: ErrCtx s -> UnifyM s a -> UnifyM s a
addErrContextM :: forall s a. Doc -> UnifyM s a -> UnifyM s a
addErrContextM Doc
ctx UnifyM s a
m =
    forall s a. (UnifEnv s -> ST s (Maybe a)) -> UnifyM s a
UnifyM forall a b. (a -> b) -> a -> b
$ \UnifEnv s
r -> forall s a. UnifyM s a -> UnifEnv s -> ST s (Maybe a)
unUnifyM UnifyM s a
m UnifEnv s
r { unify_ctx :: [Doc]
unify_ctx = Doc
ctx forall a. a -> [a] -> [a]
: forall s. UnifEnv s -> [Doc]
unify_ctx UnifEnv s
r }


-----------------------------------------------------------------------
-- The "unifiable" variants of the data types
--
-- In order to properly do unification over infinite trees, we
-- need to union find over 'Module's and 'UnitId's.  The pure
-- representation is ill-equipped to do this, so we convert
-- from the pure representation into one which is indirected
-- through union-find.  'ModuleU' handles hole variables;
-- 'UnitIdU' handles mu-binders.

-- | Contents of a mutable 'ModuleU' reference.
data ModuleU' s
    = ModuleU (UnitIdU s) ModuleName
    | ModuleVarU ModuleName

-- | Contents of a mutable 'UnitIdU' reference.
data UnitIdU' s
    = UnitIdU UnitIdUnique ComponentId (Map ModuleName (ModuleU s))
    | UnitIdThunkU DefUnitId

-- | A mutable version of 'Module' which can be imperatively unified.
type ModuleU s = UnionFind.Point s (ModuleU' s)

-- | A mutable version of 'UnitId' which can be imperatively unified.
type UnitIdU s = UnionFind.Point s (UnitIdU' s)

-- | An integer for uniquely labeling 'UnitIdU' nodes.  We need
-- these labels in order to efficiently serialize 'UnitIdU's into
-- 'UnitId's (we use the label to check if any parent is the
-- node in question, and if so insert a deBruijn index instead.)
-- These labels must be unique across all 'UnitId's/'Module's which
-- participate in unification!
type UnitIdUnique = Int


-----------------------------------------------------------------------
-- Conversion to the unifiable data types

-- An environment for tracking the mu-bindings in scope.
-- The invariant for a state @(m, i)@ is that [0..i] are
-- keys of @m@; in fact, the @i-k@th entry is the @k@th
-- de Bruijn index (this saves us from having to shift as
-- we enter mu-binders.)
type MuEnv s = (IntMap (UnitIdU s), Int)

extendMuEnv :: MuEnv s -> UnitIdU s -> MuEnv s
extendMuEnv :: forall s. MuEnv s -> UnitIdU s -> MuEnv s
extendMuEnv (IntMap (UnitIdU s)
m, Int
i) UnitIdU s
x =
    (forall a. Int -> a -> IntMap a -> IntMap a
IntMap.insert (Int
i forall a. Num a => a -> a -> a
+ Int
1) UnitIdU s
x IntMap (UnitIdU s)
m, Int
i forall a. Num a => a -> a -> a
+ Int
1)

{-
lookupMuEnv :: MuEnv s -> Int {- de Bruijn index -} -> UnitIdU s
lookupMuEnv (m, i) k =
    case IntMap.lookup (i - k) m of
        -- Technically a user can trigger this by giving us a
        -- bad 'UnitId', so handle this better.
        Nothing -> error "lookupMuEnv: out of bounds (malformed de Bruijn index)"
        Just v -> v
-}

emptyMuEnv :: MuEnv s
emptyMuEnv :: forall s. MuEnv s
emptyMuEnv = (forall a. IntMap a
IntMap.empty, -Int
1)

-- The workhorse functions.  These share an environment:
--   * @UnifRef s UnitIdUnique@ - the unique label supply for 'UnitIdU' nodes
--   * @UnifRef s (Map ModuleName moduleU)@ - the (lazily initialized)
--     environment containing the implicitly universally quantified
--     @hole:A@ binders.
--   * @MuEnv@ - the environment for mu-binders.

convertUnitId' :: MuEnv s
               -> OpenUnitId
               -> UnifyM s (UnitIdU s)
-- TODO: this could be more lazy if we know there are no internal
-- references
convertUnitId' :: forall s. MuEnv s -> OpenUnitId -> UnifyM s (UnitIdU s)
convertUnitId' MuEnv s
_ (DefiniteUnitId DefUnitId
uid) =
    forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall a s. a -> ST s (Point s a)
UnionFind.fresh (forall s. DefUnitId -> UnitIdU' s
UnitIdThunkU DefUnitId
uid)
convertUnitId' MuEnv s
stk (IndefFullUnitId ComponentId
cid OpenModuleSubst
insts) = do
    UnifRef s Int
fs <- forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall s. UnifEnv s -> UnifRef s Int
unify_uniq forall s. UnifyM s (UnifEnv s)
getUnifEnv
    UnitIdU s
x <- forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall a s. a -> ST s (Point s a)
UnionFind.fresh (forall a. HasCallStack => [Char] -> a
error [Char]
"convertUnitId") -- tie the knot later
    Map ModuleName (ModuleU s)
insts_u <- forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
t a -> (a -> f b) -> f (t b)
for OpenModuleSubst
insts forall a b. (a -> b) -> a -> b
$ forall s. MuEnv s -> OpenModule -> UnifyM s (ModuleU s)
convertModule' (forall s. MuEnv s -> UnitIdU s -> MuEnv s
extendMuEnv MuEnv s
stk UnitIdU s
x)
    Int
u <- forall s a. UnifRef s a -> UnifyM s a
readUnifRef UnifRef s Int
fs
    forall s a. UnifRef s a -> a -> UnifyM s ()
writeUnifRef UnifRef s Int
fs (Int
uforall a. Num a => a -> a -> a
+Int
1)
    UnitIdU s
y <- forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall a s. a -> ST s (Point s a)
UnionFind.fresh (forall s.
Int -> ComponentId -> Map ModuleName (ModuleU s) -> UnitIdU' s
UnitIdU Int
u ComponentId
cid Map ModuleName (ModuleU s)
insts_u)
    forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall s a. Point s a -> Point s a -> ST s ()
UnionFind.union UnitIdU s
x UnitIdU s
y
    forall (m :: * -> *) a. Monad m => a -> m a
return UnitIdU s
y
-- convertUnitId' stk (UnitIdVar i) = return (lookupMuEnv stk i)

convertModule' :: MuEnv s
               -> OpenModule -> UnifyM s (ModuleU s)
convertModule' :: forall s. MuEnv s -> OpenModule -> UnifyM s (ModuleU s)
convertModule' MuEnv s
_stk (OpenModuleVar ModuleName
mod_name) = do
    UnifRef s (Map ModuleName (ModuleU s))
hmap <- forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall s. UnifEnv s -> UnifRef s (Map ModuleName (ModuleU s))
unify_reqs forall s. UnifyM s (UnifEnv s)
getUnifEnv
    Map ModuleName (ModuleU s)
hm <- forall s a. UnifRef s a -> UnifyM s a
readUnifRef UnifRef s (Map ModuleName (ModuleU s))
hmap
    case forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ModuleName
mod_name Map ModuleName (ModuleU s)
hm of
        Maybe (ModuleU s)
Nothing -> do ModuleU s
mod <- forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall a s. a -> ST s (Point s a)
UnionFind.fresh (forall s. ModuleName -> ModuleU' s
ModuleVarU ModuleName
mod_name)
                      forall s a. UnifRef s a -> a -> UnifyM s ()
writeUnifRef UnifRef s (Map ModuleName (ModuleU s))
hmap (forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert ModuleName
mod_name ModuleU s
mod Map ModuleName (ModuleU s)
hm)
                      forall (m :: * -> *) a. Monad m => a -> m a
return ModuleU s
mod
        Just ModuleU s
mod -> forall (m :: * -> *) a. Monad m => a -> m a
return ModuleU s
mod
convertModule' MuEnv s
stk (OpenModule OpenUnitId
uid ModuleName
mod_name) = do
    UnitIdU s
uid_u <- forall s. MuEnv s -> OpenUnitId -> UnifyM s (UnitIdU s)
convertUnitId' MuEnv s
stk OpenUnitId
uid
    forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall a s. a -> ST s (Point s a)
UnionFind.fresh (forall s. UnitIdU s -> ModuleName -> ModuleU' s
ModuleU UnitIdU s
uid_u ModuleName
mod_name)

convertUnitId :: OpenUnitId -> UnifyM s (UnitIdU s)
convertUnitId :: forall s. OpenUnitId -> UnifyM s (UnitIdU s)
convertUnitId = forall s. MuEnv s -> OpenUnitId -> UnifyM s (UnitIdU s)
convertUnitId' forall s. MuEnv s
emptyMuEnv

convertModule :: OpenModule -> UnifyM s (ModuleU s)
convertModule :: forall s. OpenModule -> UnifyM s (ModuleU s)
convertModule = forall s. MuEnv s -> OpenModule -> UnifyM s (ModuleU s)
convertModule' forall s. MuEnv s
emptyMuEnv



-----------------------------------------------------------------------
-- Substitutions

-- | The mutable counterpart of a 'ModuleSubst' (not defined here).
type ModuleSubstU s = Map ModuleName (ModuleU s)

-- | Conversion of 'ModuleSubst' to 'ModuleSubstU'
convertModuleSubst :: Map ModuleName OpenModule -> UnifyM s (Map ModuleName (ModuleU s))
convertModuleSubst :: forall s. OpenModuleSubst -> UnifyM s (Map ModuleName (ModuleU s))
convertModuleSubst = forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse forall s. OpenModule -> UnifyM s (ModuleU s)
convertModule

-- | Conversion of 'ModuleSubstU' to 'ModuleSubst'
convertModuleSubstU :: ModuleSubstU s -> UnifyM s OpenModuleSubst
convertModuleSubstU :: forall s. ModuleSubstU s -> UnifyM s OpenModuleSubst
convertModuleSubstU = forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse forall s. ModuleU s -> UnifyM s OpenModule
convertModuleU

-----------------------------------------------------------------------
-- Conversion from the unifiable data types

-- An environment for tracking candidates for adding a mu-binding.
-- The invariant for a state @(m, i)@, is that if we encounter a node
-- labeled @k@ such that @m[k -> v]@, then we can replace this
-- node with the de Bruijn index @i-v@ referring to an enclosing
-- mu-binder; furthermore, @range(m) = [0..i]@.
type MooEnv = (IntMap Int, Int)

emptyMooEnv :: MooEnv
emptyMooEnv :: MooEnv
emptyMooEnv = (forall a. IntMap a
IntMap.empty, -Int
1)

extendMooEnv :: MooEnv -> UnitIdUnique -> MooEnv
extendMooEnv :: MooEnv -> Int -> MooEnv
extendMooEnv (IntMap Int
m, Int
i) Int
k = (forall a. Int -> a -> IntMap a -> IntMap a
IntMap.insert Int
k (Int
i forall a. Num a => a -> a -> a
+ Int
1) IntMap Int
m, Int
i forall a. Num a => a -> a -> a
+ Int
1)

lookupMooEnv :: MooEnv -> UnitIdUnique -> Maybe Int
lookupMooEnv :: MooEnv -> Int -> Maybe Int
lookupMooEnv (IntMap Int
m, Int
i) Int
k =
    case forall a. Int -> IntMap a -> Maybe a
IntMap.lookup Int
k IntMap Int
m of
        Maybe Int
Nothing -> forall a. Maybe a
Nothing
        Just Int
v -> forall a. a -> Maybe a
Just (Int
iforall a. Num a => a -> a -> a
-Int
v) -- de Bruijn indexize

-- The workhorse functions

-- | Returns `OpenUnitId` if there is no a mutually recursive unit.
-- | Otherwise returns a list of signatures instantiated by given `UnitIdU`.
convertUnitIdU' :: MooEnv -> UnitIdU s -> Doc -> UnifyM s OpenUnitId
convertUnitIdU' :: forall s. MooEnv -> UnitIdU s -> Doc -> UnifyM s OpenUnitId
convertUnitIdU' MooEnv
stk UnitIdU s
uid_u Doc
required_mod_name = do
    UnitIdU' s
x <- forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall s a. Point s a -> ST s a
UnionFind.find UnitIdU s
uid_u
    case UnitIdU' s
x of
        UnitIdThunkU DefUnitId
uid -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ DefUnitId -> OpenUnitId
DefiniteUnitId DefUnitId
uid
        UnitIdU Int
u ComponentId
cid Map ModuleName (ModuleU s)
insts_u ->
            case MooEnv -> Int -> Maybe Int
lookupMooEnv MooEnv
stk Int
u of
                Just Int
_ ->
                    let mod_names :: [ModuleName]
mod_names = forall k a. Map k a -> [k]
Map.keys Map ModuleName (ModuleU s)
insts_u
                    in forall s a. Doc -> [ModuleName] -> UnifyM s a
failWithMutuallyRecursiveUnitsError Doc
required_mod_name [ModuleName]
mod_names
                Maybe Int
Nothing -> do
                    OpenModuleSubst
insts <- forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
t a -> (a -> f b) -> f (t b)
for Map ModuleName (ModuleU s)
insts_u forall a b. (a -> b) -> a -> b
$ forall s. MooEnv -> ModuleU s -> UnifyM s OpenModule
convertModuleU' (MooEnv -> Int -> MooEnv
extendMooEnv MooEnv
stk Int
u)
                    forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ ComponentId -> OpenModuleSubst -> OpenUnitId
IndefFullUnitId ComponentId
cid OpenModuleSubst
insts

convertModuleU' :: MooEnv -> ModuleU s -> UnifyM s OpenModule
convertModuleU' :: forall s. MooEnv -> ModuleU s -> UnifyM s OpenModule
convertModuleU' MooEnv
stk ModuleU s
mod_u = do
    ModuleU' s
mod <- forall s a. ST s a -> UnifyM s a
liftST forall a b. (a -> b) -> a -> b
$ forall s a. Point s a -> ST s a
UnionFind.find ModuleU s
mod_u
    case ModuleU' s
mod of
        ModuleVarU ModuleName
mod_name -> forall (m :: * -> *) a. Monad m => a -> m a
return (ModuleName -> OpenModule
OpenModuleVar ModuleName
mod_name)
        ModuleU UnitIdU s
uid_u ModuleName
mod_name -> do
            OpenUnitId
uid <- forall s. MooEnv -> UnitIdU s -> Doc -> UnifyM s OpenUnitId
convertUnitIdU' MooEnv
stk UnitIdU s
uid_u (forall a. Pretty a => a -> Doc
pretty ModuleName
mod_name)
            forall (m :: * -> *) a. Monad m => a -> m a
return (OpenUnitId -> ModuleName -> OpenModule
OpenModule OpenUnitId
uid ModuleName
mod_name)

failWithMutuallyRecursiveUnitsError :: Doc -> [ModuleName] -> UnifyM s a
failWithMutuallyRecursiveUnitsError :: forall s a. Doc -> [ModuleName] -> UnifyM s a
failWithMutuallyRecursiveUnitsError Doc
required_mod_name [ModuleName]
mod_names =
    let sigsList :: Doc
sigsList = [Doc] -> Doc
hcat forall a b. (a -> b) -> a -> b
$ Doc -> [Doc] -> [Doc]
punctuate ([Char] -> Doc
text [Char]
", ") forall a b. (a -> b) -> a -> b
$ forall a b. (a -> b) -> [a] -> [b]
map (Doc -> Doc
quotes forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Pretty a => a -> Doc
pretty) [ModuleName]
mod_names in
    forall s a. Doc -> UnifyM s a
failWith forall a b. (a -> b) -> a -> b
$
        [Char] -> Doc
text [Char]
"Cannot instantiate requirement" Doc -> Doc -> Doc
<+> Doc -> Doc
quotes Doc
required_mod_name Doc -> Doc -> Doc
$$
        [Char] -> Doc
text [Char]
"Ensure \"build-depends:\" doesn't include any library with signatures:" Doc -> Doc -> Doc
<+> Doc
sigsList Doc -> Doc -> Doc
$$
        [Char] -> Doc
text [Char]
"as this creates a cyclic dependency, which GHC does not support."

-- Helper functions

convertUnitIdU :: UnitIdU s -> Doc -> UnifyM s OpenUnitId
convertUnitIdU :: forall s. UnitIdU s -> Doc -> UnifyM s OpenUnitId
convertUnitIdU = forall s. MooEnv -> UnitIdU s -> Doc -> UnifyM s OpenUnitId
convertUnitIdU' MooEnv
emptyMooEnv

convertModuleU :: ModuleU s -> UnifyM s OpenModule
convertModuleU :: forall s. ModuleU s -> UnifyM s OpenModule
convertModuleU = forall s. MooEnv -> ModuleU s -> UnifyM s OpenModule
convertModuleU' MooEnv
emptyMooEnv

-- | An empty 'ModuleScopeU'.
emptyModuleScopeU :: ModuleScopeU s
emptyModuleScopeU :: forall s. ModuleScopeU s
emptyModuleScopeU = (forall k a. Map k a
Map.empty, forall k a. Map k a
Map.empty)


-- | The mutable counterpart of 'ModuleScope'.
type ModuleScopeU s = (ModuleProvidesU s, ModuleRequiresU s)
-- | The mutable counterpart of 'ModuleProvides'
type ModuleProvidesU s = Map ModuleName [ModuleWithSourceU s]
type ModuleRequiresU s = ModuleProvidesU s
type ModuleWithSourceU s = WithSource (ModuleU s)

-- TODO: Deduplicate this with Distribution.Backpack.MixLink.dispSource
ci_msg :: ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming -> Doc
ci_msg :: ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming -> Doc
ci_msg ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci
  | forall id rn. ComponentInclude id rn -> Bool
ci_implicit ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci = [Char] -> Doc
text [Char]
"build-depends:" Doc -> Doc -> Doc
<+> Doc
pp_pn
  | Bool
otherwise = [Char] -> Doc
text [Char]
"mixins:" Doc -> Doc -> Doc
<+> Doc
pp_pn Doc -> Doc -> Doc
<+> forall a. Pretty a => a -> Doc
pretty (forall id rn. ComponentInclude id rn -> rn
ci_renaming ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci)
  where
    pn :: PackageName
pn = PackageIdentifier -> PackageName
pkgName (forall id rn. ComponentInclude id rn -> PackageIdentifier
ci_pkgid ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci)
    pp_pn :: Doc
pp_pn =
        case forall id rn. ComponentInclude id rn -> ComponentName
ci_cname ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci of
            CLibName LibraryName
LMainLibName -> forall a. Pretty a => a -> Doc
pretty PackageName
pn
            CLibName (LSubLibName UnqualComponentName
cn) -> forall a. Pretty a => a -> Doc
pretty PackageName
pn Doc -> Doc -> Doc
<<>> Doc
colon Doc -> Doc -> Doc
<<>> forall a. Pretty a => a -> Doc
pretty UnqualComponentName
cn
            -- Shouldn't happen
            ComponentName
cn -> forall a. Pretty a => a -> Doc
pretty PackageName
pn Doc -> Doc -> Doc
<+> Doc -> Doc
parens (forall a. Pretty a => a -> Doc
pretty ComponentName
cn)

-- | Convert a 'ModuleShape' into a 'ModuleScopeU', so we can do
-- unification on it.
convertInclude
    :: ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
    -> UnifyM s (ModuleScopeU s,
                 Either (ComponentInclude (UnitIdU s) ModuleRenaming) {- normal -}
                        (ComponentInclude (UnitIdU s) ModuleRenaming) {- sig -})
convertInclude :: forall s.
ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
-> UnifyM
     s
     (ModuleScopeU s,
      Either
        (ComponentInclude (UnitIdU s) ModuleRenaming)
        (ComponentInclude (UnitIdU s) ModuleRenaming))
convertInclude ci :: ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci@(ComponentInclude {
                    ci_ann_id :: forall id rn. ComponentInclude id rn -> AnnotatedId id
ci_ann_id = AnnotatedId {
                            ann_id :: forall id. AnnotatedId id -> id
ann_id = (OpenUnitId
uid, ModuleShape OpenModuleSubst
provs Set ModuleName
reqs),
                            ann_pid :: forall id. AnnotatedId id -> PackageIdentifier
ann_pid = PackageIdentifier
pid,
                            ann_cname :: forall id. AnnotatedId id -> ComponentName
ann_cname = ComponentName
compname
                        },
                    ci_renaming :: forall id rn. ComponentInclude id rn -> rn
ci_renaming = incl :: IncludeRenaming
incl@(IncludeRenaming ModuleRenaming
prov_rns ModuleRenaming
req_rns),
                    ci_implicit :: forall id rn. ComponentInclude id rn -> Bool
ci_implicit = Bool
implicit
               }) = forall s a. Doc -> UnifyM s a -> UnifyM s a
addErrContext ([Char] -> Doc
text [Char]
"In" Doc -> Doc -> Doc
<+> ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming -> Doc
ci_msg ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci) forall a b. (a -> b) -> a -> b
$ do
    let pn :: PackageName
pn = forall pkg. Package pkg => pkg -> PackageName
packageName PackageIdentifier
pid
        the_source :: ModuleSource
the_source | Bool
implicit
                   = PackageName -> ComponentName -> ModuleSource
FromBuildDepends PackageName
pn ComponentName
compname
                   | Bool
otherwise
                   = PackageName -> ComponentName -> IncludeRenaming -> ModuleSource
FromMixins PackageName
pn ComponentName
compname IncludeRenaming
incl
        source :: a -> WithSource a
source = forall a. ModuleSource -> a -> WithSource a
WithSource ModuleSource
the_source

    -- Suppose our package has two requirements A and B, and
    -- we include it with @requires (A as X)@
    -- There are three closely related things we compute based
    -- off of @reqs@ and @reqs_rns@:
    --
    --      1. The requirement renaming (A -> X)
    --      2. The requirement substitution (A -> <X>, B -> <B>)

    -- Requirement renaming.  This is read straight off the syntax:
    --
    --      [nothing]          ==>  [empty]
    --      requires (B as Y)  ==>  B -> Y
    --
    -- Requirement renamings are NOT injective: if two requirements
    -- are mapped to the same name, the intent is to merge them
    -- together.  But they are *functions*, so @B as X, B as Y@ is
    -- illegal.

    [(ModuleName, ModuleName)]
req_rename_list <-
      case ModuleRenaming
req_rns of
        ModuleRenaming
DefaultRenaming -> forall (m :: * -> *) a. Monad m => a -> m a
return []
        HidingRenaming [ModuleName]
_ -> do
            -- Not valid here for requires!
            forall s. Doc -> UnifyM s ()
addErr forall a b. (a -> b) -> a -> b
$ [Char] -> Doc
text [Char]
"Unsupported syntax" Doc -> Doc -> Doc
<+>
                     Doc -> Doc
quotes ([Char] -> Doc
text [Char]
"requires hiding (...)")
            forall (m :: * -> *) a. Monad m => a -> m a
return []
        ModuleRenaming [(ModuleName, ModuleName)]
rns -> forall (m :: * -> *) a. Monad m => a -> m a
return [(ModuleName, ModuleName)]
rns

    let req_rename_listmap :: Map ModuleName [ModuleName]
        req_rename_listmap :: Map ModuleName [ModuleName]
req_rename_listmap =
            forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith forall a. [a] -> [a] -> [a]
(++) [ (ModuleName
k,[ModuleName
v]) | (ModuleName
k,ModuleName
v) <- [(ModuleName, ModuleName)]
req_rename_list ]
    Map ModuleName ModuleName
req_rename <- forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
sequenceA forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b c. (a -> b -> c) -> b -> a -> c
flip forall k a b. (k -> a -> b) -> Map k a -> Map k b
Map.mapWithKey Map ModuleName [ModuleName]
req_rename_listmap forall a b. (a -> b) -> a -> b
$ \ModuleName
k [ModuleName]
vs0 ->
      case [ModuleName]
vs0 of
        []  -> forall a. HasCallStack => [Char] -> a
error [Char]
"req_rename"
        [ModuleName
v] -> forall (m :: * -> *) a. Monad m => a -> m a
return ModuleName
v
        ModuleName
v:[ModuleName]
vs -> do forall s. Doc -> UnifyM s ()
addErr forall a b. (a -> b) -> a -> b
$
                    [Char] -> Doc
text [Char]
"Conflicting renamings of requirement" Doc -> Doc -> Doc
<+> Doc -> Doc
quotes (forall a. Pretty a => a -> Doc
pretty ModuleName
k) Doc -> Doc -> Doc
$$
                    [Char] -> Doc
text [Char]
"Renamed to: " Doc -> Doc -> Doc
<+> [Doc] -> Doc
vcat (forall a b. (a -> b) -> [a] -> [b]
map forall a. Pretty a => a -> Doc
pretty (ModuleName
vforall a. a -> [a] -> [a]
:[ModuleName]
vs))
                   forall (m :: * -> *) a. Monad m => a -> m a
return ModuleName
v

    let req_rename_fn :: ModuleName -> ModuleName
req_rename_fn ModuleName
k = case forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ModuleName
k Map ModuleName ModuleName
req_rename of
                            Maybe ModuleName
Nothing -> ModuleName
k
                            Just ModuleName
v  -> ModuleName
v

    -- Requirement substitution.
    --
    --      A -> X      ==>     A -> <X>
    let req_subst :: OpenModuleSubst
req_subst = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ModuleName -> OpenModule
OpenModuleVar Map ModuleName ModuleName
req_rename

    UnitIdU s
uid_u <- forall s. OpenUnitId -> UnifyM s (UnitIdU s)
convertUnitId (forall a. ModSubst a => OpenModuleSubst -> a -> a
modSubst OpenModuleSubst
req_subst OpenUnitId
uid)

    -- Requirement mapping.  This is just taking the range of the
    -- requirement substitution, and making a mapping so that it is
    -- convenient to merge things together.  It INCLUDES the implicit
    -- mappings.
    --
    --      A -> X      ==>     X -> <X>, B -> <B>
    ModuleRequiresU s
reqs_u <- forall s. ModuleRequires -> UnifyM s (ModuleRequiresU s)
convertModuleRequires forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList forall a b. (a -> b) -> a -> b
$
                [ (ModuleName
k, [forall {a}. a -> WithSource a
source (ModuleName -> OpenModule
OpenModuleVar ModuleName
k)])
                | ModuleName
k <- forall a b. (a -> b) -> [a] -> [b]
map ModuleName -> ModuleName
req_rename_fn (forall a. Set a -> [a]
Set.toList Set ModuleName
reqs)
                ]

    -- Report errors if there were unused renamings
    let leftover :: Set ModuleName
leftover = forall k a. Map k a -> Set k
Map.keysSet Map ModuleName ModuleName
req_rename forall a. Ord a => Set a -> Set a -> Set a
`Set.difference` Set ModuleName
reqs
    forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (forall a. Set a -> Bool
Set.null Set ModuleName
leftover) forall a b. (a -> b) -> a -> b
$
        forall s. Doc -> UnifyM s ()
addErr forall a b. (a -> b) -> a -> b
$
            Doc -> Int -> Doc -> Doc
hang ([Char] -> Doc
text [Char]
"The" Doc -> Doc -> Doc
<+> [Char] -> Doc
text (ComponentName -> [Char]
showComponentName ComponentName
compname) Doc -> Doc -> Doc
<+>
                  [Char] -> Doc
text [Char]
"from package" Doc -> Doc -> Doc
<+> Doc -> Doc
quotes (forall a. Pretty a => a -> Doc
pretty PackageIdentifier
pid)
                  Doc -> Doc -> Doc
<+> [Char] -> Doc
text [Char]
"does not require:") Int
4
                 ([Doc] -> Doc
vcat (forall a b. (a -> b) -> [a] -> [b]
map forall a. Pretty a => a -> Doc
pretty (forall a. Set a -> [a]
Set.toList Set ModuleName
leftover)))

    -- Provision computation is more complex.
    -- For example, if we have:
    --
    --      include p (A as X) requires (B as Y)
    --          where A -> q[B=<B>]:A
    --
    -- Then we need:
    --
    --      X -> [("p", q[B=<B>]:A)]
    --
    -- There are a bunch of clever ways to present the algorithm
    -- but here is the simple one:
    --
    --      1. If we have a default renaming, apply req_subst
    --      to provs and use that.
    --
    --      2. Otherwise, build a map by successively looking
    --      up the referenced modules in the renaming in provs.
    --
    -- Importantly, overlapping rename targets get accumulated
    -- together.  It's not an (immediate) error.
    ([(ModuleName, OpenModule)]
pre_prov_scope, ModuleRenaming
prov_rns') <-
        case ModuleRenaming
prov_rns of
            ModuleRenaming
DefaultRenaming -> forall (m :: * -> *) a. Monad m => a -> m a
return (forall k a. Map k a -> [(k, a)]
Map.toList OpenModuleSubst
provs, ModuleRenaming
prov_rns)
            HidingRenaming [ModuleName]
hides ->
                let hides_set :: Set ModuleName
hides_set = forall a. Ord a => [a] -> Set a
Set.fromList [ModuleName]
hides
                in let r :: [(ModuleName, OpenModule)]
r = [ (ModuleName
k,OpenModule
v)
                           | (ModuleName
k,OpenModule
v) <- forall k a. Map k a -> [(k, a)]
Map.toList OpenModuleSubst
provs
                           , Bool -> Bool
not (ModuleName
k forall a. Ord a => a -> Set a -> Bool
`Set.member` Set ModuleName
hides_set) ]
                   -- GHC doesn't understand hiding, so expand it out!
                   in forall (m :: * -> *) a. Monad m => a -> m a
return ([(ModuleName, OpenModule)]
r, [(ModuleName, ModuleName)] -> ModuleRenaming
ModuleRenaming (forall a b. (a -> b) -> [a] -> [b]
map ((\ModuleName
x -> (ModuleName
x,ModuleName
x))forall b c a. (b -> c) -> (a -> b) -> a -> c
.forall a b. (a, b) -> a
fst) [(ModuleName, OpenModule)]
r))
            ModuleRenaming [(ModuleName, ModuleName)]
rns -> do
              [(ModuleName, OpenModule)]
r <- forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
sequence
                [ case forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ModuleName
from OpenModuleSubst
provs of
                    Just OpenModule
m -> forall (m :: * -> *) a. Monad m => a -> m a
return (ModuleName
to, OpenModule
m)
                    Maybe OpenModule
Nothing -> forall s a. Doc -> UnifyM s a
failWith forall a b. (a -> b) -> a -> b
$
                        [Char] -> Doc
text [Char]
"Package" Doc -> Doc -> Doc
<+> Doc -> Doc
quotes (forall a. Pretty a => a -> Doc
pretty PackageIdentifier
pid) Doc -> Doc -> Doc
<+>
                        [Char] -> Doc
text [Char]
"does not expose the module" Doc -> Doc -> Doc
<+> Doc -> Doc
quotes (forall a. Pretty a => a -> Doc
pretty ModuleName
from)
                | (ModuleName
from, ModuleName
to) <- [(ModuleName, ModuleName)]
rns ]
              forall (m :: * -> *) a. Monad m => a -> m a
return ([(ModuleName, OpenModule)]
r, ModuleRenaming
prov_rns)
    let prov_scope :: ModuleRequires
prov_scope = forall a. ModSubst a => OpenModuleSubst -> a -> a
modSubst OpenModuleSubst
req_subst
                   forall a b. (a -> b) -> a -> b
$ forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith forall a. [a] -> [a] -> [a]
(++)
                   [ (ModuleName
k, [forall {a}. a -> WithSource a
source OpenModule
v])
                   | (ModuleName
k, OpenModule
v) <- [(ModuleName, OpenModule)]
pre_prov_scope ]

    ModuleRequiresU s
provs_u <- forall s. ModuleRequires -> UnifyM s (ModuleRequiresU s)
convertModuleProvides ModuleRequires
prov_scope

    -- TODO: Assert that provs_u is empty if provs was empty
    forall (m :: * -> *) a. Monad m => a -> m a
return ((ModuleRequiresU s
provs_u, ModuleRequiresU s
reqs_u),
                -- NB: We test that requirements is not null so that
                -- users can create packages with zero module exports
                -- that cause some C library to linked in, etc.
                (if forall k a. Map k a -> Bool
Map.null OpenModuleSubst
provs Bool -> Bool -> Bool
&& Bool -> Bool
not (forall a. Set a -> Bool
Set.null Set ModuleName
reqs)
                    then forall a b. b -> Either a b
Right -- is sig
                    else forall a b. a -> Either a b
Left) (ComponentInclude {
                                    ci_ann_id :: AnnotatedId (UnitIdU s)
ci_ann_id = AnnotatedId {
                                            ann_id :: UnitIdU s
ann_id = UnitIdU s
uid_u,
                                            ann_pid :: PackageIdentifier
ann_pid = PackageIdentifier
pid,
                                            ann_cname :: ComponentName
ann_cname = ComponentName
compname
                                        },
                                    ci_renaming :: ModuleRenaming
ci_renaming = ModuleRenaming
prov_rns',
                                    ci_implicit :: Bool
ci_implicit = forall id rn. ComponentInclude id rn -> Bool
ci_implicit ComponentInclude (OpenUnitId, ModuleShape) IncludeRenaming
ci
                                    }))

-- | Convert a 'ModuleScopeU' to a 'ModuleScope'.
convertModuleScopeU :: ModuleScopeU s -> UnifyM s ModuleScope
convertModuleScopeU :: forall s. ModuleScopeU s -> UnifyM s ModuleScope
convertModuleScopeU (ModuleProvidesU s
provs_u, ModuleProvidesU s
reqs_u) = do
    ModuleRequires
provs <- forall s. ModuleProvidesU s -> UnifyM s ModuleRequires
convertModuleProvidesU ModuleProvidesU s
provs_u
    ModuleRequires
reqs  <- forall s. ModuleProvidesU s -> UnifyM s ModuleRequires
convertModuleRequiresU ModuleProvidesU s
reqs_u
    -- TODO: Test that the requirements are still free. If they
    -- are not, they got unified, and that's dodgy at best.
    forall (m :: * -> *) a. Monad m => a -> m a
return (ModuleRequires -> ModuleRequires -> ModuleScope
ModuleScope ModuleRequires
provs ModuleRequires
reqs)

-- | Convert a 'ModuleProvides' to a 'ModuleProvidesU'
convertModuleProvides :: ModuleProvides -> UnifyM s (ModuleProvidesU s)
convertModuleProvides :: forall s. ModuleRequires -> UnifyM s (ModuleRequiresU s)
convertModuleProvides = forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse forall s. OpenModule -> UnifyM s (ModuleU s)
convertModule))

-- | Convert a 'ModuleProvidesU' to a 'ModuleProvides'
convertModuleProvidesU :: ModuleProvidesU s -> UnifyM s ModuleProvides
convertModuleProvidesU :: forall s. ModuleProvidesU s -> UnifyM s ModuleRequires
convertModuleProvidesU = forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse forall s. ModuleU s -> UnifyM s OpenModule
convertModuleU))

convertModuleRequires :: ModuleRequires -> UnifyM s (ModuleRequiresU s)
convertModuleRequires :: forall s. ModuleRequires -> UnifyM s (ModuleRequiresU s)
convertModuleRequires = forall s. ModuleRequires -> UnifyM s (ModuleRequiresU s)
convertModuleProvides

convertModuleRequiresU :: ModuleRequiresU s -> UnifyM s ModuleRequires
convertModuleRequiresU :: forall s. ModuleProvidesU s -> UnifyM s ModuleRequires
convertModuleRequiresU = forall s. ModuleProvidesU s -> UnifyM s ModuleRequires
convertModuleProvidesU