-- (c) The University of Glasgow 2006

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}

module Unify (
        tcMatchTy, tcMatchTyKi,
        tcMatchTys, tcMatchTyKis,
        tcMatchTyX, tcMatchTysX, tcMatchTyKisX,
        tcMatchTyX_BM, ruleMatchTyKiX,

        -- * Rough matching
        roughMatchTcs, instanceCantMatch,
        typesCantMatch,

        -- Side-effect free unification
        tcUnifyTy, tcUnifyTyKi, tcUnifyTys, tcUnifyTyKis,
        tcUnifyTysFG, tcUnifyTyWithTFs,
        BindFlag(..),
        UnifyResult, UnifyResultM(..),

        -- Matching a type against a lifted type (coercion)
        liftCoMatch
   ) where

#include "HsVersions.h"

import GhcPrelude

import Var
import VarEnv
import VarSet
import Name( Name )
import Type hiding ( getTvSubstEnv )
import Coercion hiding ( getCvSubstEnv )
import TyCon
import TyCoRep hiding ( getTvSubstEnv, getCvSubstEnv )
import FV( FV, fvVarSet, fvVarList )
import Util
import Pair
import Outputable
import UniqFM
import UniqSet

import Control.Monad
import qualified Control.Monad.Fail as MonadFail
import Control.Applicative hiding ( empty )
import qualified Control.Applicative

{-

Unification is much tricker than you might think.

1. The substitution we generate binds the *template type variables*
   which are given to us explicitly.

2. We want to match in the presence of foralls;
        e.g     (forall a. t1) ~ (forall b. t2)

   That is what the RnEnv2 is for; it does the alpha-renaming
   that makes it as if a and b were the same variable.
   Initialising the RnEnv2, so that it can generate a fresh
   binder when necessary, entails knowing the free variables of
   both types.

3. We must be careful not to bind a template type variable to a
   locally bound variable.  E.g.
        (forall a. x) ~ (forall b. b)
   where x is the template type variable.  Then we do not want to
   bind x to a/b!  This is a kind of occurs check.
   The necessary locals accumulate in the RnEnv2.

Note [tcMatchTy vs tcMatchTyKi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module offers two variants of matching: with kinds and without.
The TyKi variant takes two types, of potentially different kinds,
and matches them. Along the way, it necessarily also matches their
kinds. The Ty variant instead assumes that the kinds are already
eqType and so skips matching up the kinds.

How do you choose between them?

1. If you know that the kinds of the two types are eqType, use
   the Ty variant. It is more efficient, as it does less work.

2. If the kinds of variables in the template type might mention type families,
   use the Ty variant (and do other work to make sure the kinds
   work out). These pure unification functions do a straightforward
   syntactic unification and do no complex reasoning about type
   families. Note that the types of the variables in instances can indeed
   mention type families, so instance lookup must use the Ty variant.

   (Nothing goes terribly wrong -- no panics -- if there might be type
   families in kinds in the TyKi variant. You just might get match
   failure even though a reducing a type family would lead to success.)

3. Otherwise, if you're sure that the variable kinds do not mention
   type families and you're not already sure that the kind of the template
   equals the kind of the target, then use the TyKi version.
-}

-- | @tcMatchTy t1 t2@ produces a substitution (over fvs(t1))
-- @s@ such that @s(t1)@ equals @t2@.
-- The returned substitution might bind coercion variables,
-- if the variable is an argument to a GADT constructor.
--
-- Precondition: typeKind ty1 `eqType` typeKind ty2
--
-- We don't pass in a set of "template variables" to be bound
-- by the match, because tcMatchTy (and similar functions) are
-- always used on top-level types, so we can bind any of the
-- free variables of the LHS.
-- See also Note [tcMatchTy vs tcMatchTyKi]
tcMatchTy :: Type -> Type -> Maybe TCvSubst
tcMatchTy :: Type -> Type -> Maybe TCvSubst
tcMatchTy ty1 :: Type
ty1 ty2 :: Type
ty2 = [Type] -> [Type] -> Maybe TCvSubst
tcMatchTys [Type
ty1] [Type
ty2]

tcMatchTyX_BM :: (TyVar -> BindFlag) -> TCvSubst
              -> Type -> Type -> Maybe TCvSubst
tcMatchTyX_BM :: (TyVar -> BindFlag) -> TCvSubst -> Type -> Type -> Maybe TCvSubst
tcMatchTyX_BM bind_me :: TyVar -> BindFlag
bind_me subst :: TCvSubst
subst ty1 :: Type
ty1 ty2 :: Type
ty2
  = (TyVar -> BindFlag)
-> Bool -> TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys_x TyVar -> BindFlag
bind_me Bool
False TCvSubst
subst [Type
ty1] [Type
ty2]

-- | Like 'tcMatchTy', but allows the kinds of the types to differ,
-- and thus matches them as well.
-- See also Note [tcMatchTy vs tcMatchTyKi]
tcMatchTyKi :: Type -> Type -> Maybe TCvSubst
tcMatchTyKi :: Type -> Type -> Maybe TCvSubst
tcMatchTyKi ty1 :: Type
ty1 ty2 :: Type
ty2
  = (TyVar -> BindFlag) -> Bool -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) Bool
True [Type
ty1] [Type
ty2]

-- | This is similar to 'tcMatchTy', but extends a substitution
-- See also Note [tcMatchTy vs tcMatchTyKi]
tcMatchTyX :: TCvSubst            -- ^ Substitution to extend
           -> Type                -- ^ Template
           -> Type                -- ^ Target
           -> Maybe TCvSubst
tcMatchTyX :: TCvSubst -> Type -> Type -> Maybe TCvSubst
tcMatchTyX subst :: TCvSubst
subst ty1 :: Type
ty1 ty2 :: Type
ty2
  = (TyVar -> BindFlag)
-> Bool -> TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys_x (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) Bool
False TCvSubst
subst [Type
ty1] [Type
ty2]

-- | Like 'tcMatchTy' but over a list of types.
-- See also Note [tcMatchTy vs tcMatchTyKi]
tcMatchTys :: [Type]         -- ^ Template
           -> [Type]         -- ^ Target
           -> Maybe TCvSubst -- ^ One-shot; in principle the template
                             -- variables could be free in the target
tcMatchTys :: [Type] -> [Type] -> Maybe TCvSubst
tcMatchTys tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = (TyVar -> BindFlag) -> Bool -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) Bool
False [Type]
tys1 [Type]
tys2

-- | Like 'tcMatchTyKi' but over a list of types.
-- See also Note [tcMatchTy vs tcMatchTyKi]
tcMatchTyKis :: [Type]         -- ^ Template
             -> [Type]         -- ^ Target
             -> Maybe TCvSubst -- ^ One-shot substitution
tcMatchTyKis :: [Type] -> [Type] -> Maybe TCvSubst
tcMatchTyKis tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = (TyVar -> BindFlag) -> Bool -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) Bool
True [Type]
tys1 [Type]
tys2

-- | Like 'tcMatchTys', but extending a substitution
-- See also Note [tcMatchTy vs tcMatchTyKi]
tcMatchTysX :: TCvSubst       -- ^ Substitution to extend
            -> [Type]         -- ^ Template
            -> [Type]         -- ^ Target
            -> Maybe TCvSubst -- ^ One-shot substitution
tcMatchTysX :: TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tcMatchTysX subst :: TCvSubst
subst tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = (TyVar -> BindFlag)
-> Bool -> TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys_x (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) Bool
False TCvSubst
subst [Type]
tys1 [Type]
tys2

-- | Like 'tcMatchTyKis', but extending a substitution
-- See also Note [tcMatchTy vs tcMatchTyKi]
tcMatchTyKisX :: TCvSubst        -- ^ Substitution to extend
              -> [Type]          -- ^ Template
              -> [Type]          -- ^ Target
              -> Maybe TCvSubst  -- ^ One-shot substitution
tcMatchTyKisX :: TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tcMatchTyKisX subst :: TCvSubst
subst tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = (TyVar -> BindFlag)
-> Bool -> TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys_x (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) Bool
True TCvSubst
subst [Type]
tys1 [Type]
tys2

-- | Same as tc_match_tys_x, but starts with an empty substitution
tc_match_tys :: (TyVar -> BindFlag)
               -> Bool          -- ^ match kinds?
               -> [Type]
               -> [Type]
               -> Maybe TCvSubst
tc_match_tys :: (TyVar -> BindFlag) -> Bool -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys bind_me :: TyVar -> BindFlag
bind_me match_kis :: Bool
match_kis tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = (TyVar -> BindFlag)
-> Bool -> TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys_x TyVar -> BindFlag
bind_me Bool
match_kis (InScopeSet -> TCvSubst
mkEmptyTCvSubst InScopeSet
in_scope) [Type]
tys1 [Type]
tys2
  where
    in_scope :: InScopeSet
in_scope = VarSet -> InScopeSet
mkInScopeSet ([Type] -> VarSet
tyCoVarsOfTypes [Type]
tys1 VarSet -> VarSet -> VarSet
`unionVarSet` [Type] -> VarSet
tyCoVarsOfTypes [Type]
tys2)

-- | Worker for 'tcMatchTysX' and 'tcMatchTyKisX'
tc_match_tys_x :: (TyVar -> BindFlag)
               -> Bool          -- ^ match kinds?
               -> TCvSubst
               -> [Type]
               -> [Type]
               -> Maybe TCvSubst
tc_match_tys_x :: (TyVar -> BindFlag)
-> Bool -> TCvSubst -> [Type] -> [Type] -> Maybe TCvSubst
tc_match_tys_x bind_me :: TyVar -> BindFlag
bind_me match_kis :: Bool
match_kis (TCvSubst in_scope :: InScopeSet
in_scope tv_env :: TvSubstEnv
tv_env cv_env :: CvSubstEnv
cv_env) tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = case (TyVar -> BindFlag)
-> Bool
-> Bool
-> Bool
-> RnEnv2
-> TvSubstEnv
-> CvSubstEnv
-> [Type]
-> [Type]
-> UnifyResultM (TvSubstEnv, CvSubstEnv)
tc_unify_tys TyVar -> BindFlag
bind_me
                      Bool
False  -- Matching, not unifying
                      Bool
False  -- Not an injectivity check
                      Bool
match_kis
                      (InScopeSet -> RnEnv2
mkRnEnv2 InScopeSet
in_scope) TvSubstEnv
tv_env CvSubstEnv
cv_env [Type]
tys1 [Type]
tys2 of
      Unifiable (tv_env' :: TvSubstEnv
tv_env', cv_env' :: CvSubstEnv
cv_env')
        -> TCvSubst -> Maybe TCvSubst
forall a. a -> Maybe a
Just (TCvSubst -> Maybe TCvSubst) -> TCvSubst -> Maybe TCvSubst
forall a b. (a -> b) -> a -> b
$ InScopeSet -> TvSubstEnv -> CvSubstEnv -> TCvSubst
TCvSubst InScopeSet
in_scope TvSubstEnv
tv_env' CvSubstEnv
cv_env'
      _ -> Maybe TCvSubst
forall a. Maybe a
Nothing

-- | This one is called from the expression matcher,
-- which already has a MatchEnv in hand
ruleMatchTyKiX
  :: TyCoVarSet          -- ^ template variables
  -> RnEnv2
  -> TvSubstEnv          -- ^ type substitution to extend
  -> Type                -- ^ Template
  -> Type                -- ^ Target
  -> Maybe TvSubstEnv
ruleMatchTyKiX :: VarSet -> RnEnv2 -> TvSubstEnv -> Type -> Type -> Maybe TvSubstEnv
ruleMatchTyKiX tmpl_tvs :: VarSet
tmpl_tvs rn_env :: RnEnv2
rn_env tenv :: TvSubstEnv
tenv tmpl :: Type
tmpl target :: Type
target
-- See Note [Kind coercions in Unify]
  = case (TyVar -> BindFlag)
-> Bool
-> Bool
-> Bool
-> RnEnv2
-> TvSubstEnv
-> CvSubstEnv
-> [Type]
-> [Type]
-> UnifyResultM (TvSubstEnv, CvSubstEnv)
tc_unify_tys (VarSet -> TyVar -> BindFlag
matchBindFun VarSet
tmpl_tvs) Bool
False Bool
False
                      Bool
True -- <-- this means to match the kinds
                      RnEnv2
rn_env TvSubstEnv
tenv CvSubstEnv
emptyCvSubstEnv [Type
tmpl] [Type
target] of
      Unifiable (tenv' :: TvSubstEnv
tenv', _) -> TvSubstEnv -> Maybe TvSubstEnv
forall a. a -> Maybe a
Just TvSubstEnv
tenv'
      _                    -> Maybe TvSubstEnv
forall a. Maybe a
Nothing

matchBindFun :: TyCoVarSet -> TyVar -> BindFlag
matchBindFun :: VarSet -> TyVar -> BindFlag
matchBindFun tvs :: VarSet
tvs tv :: TyVar
tv = if TyVar
tv TyVar -> VarSet -> Bool
`elemVarSet` VarSet
tvs then BindFlag
BindMe else BindFlag
Skolem


{- *********************************************************************
*                                                                      *
                Rough matching
*                                                                      *
********************************************************************* -}

-- See Note [Rough match] field in InstEnv

roughMatchTcs :: [Type] -> [Maybe Name]
roughMatchTcs :: [Type] -> [Maybe Name]
roughMatchTcs tys :: [Type]
tys = (Type -> Maybe Name) -> [Type] -> [Maybe Name]
forall a b. (a -> b) -> [a] -> [b]
map Type -> Maybe Name
rough [Type]
tys
  where
    rough :: Type -> Maybe Name
rough ty :: Type
ty
      | Just (ty' :: Type
ty', _) <- Type -> Maybe (Type, Coercion)
splitCastTy_maybe Type
ty   = Type -> Maybe Name
rough Type
ty'
      | Just (tc :: TyCon
tc,_)   <- HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe Type
ty = Name -> Maybe Name
forall a. a -> Maybe a
Just (TyCon -> Name
tyConName TyCon
tc)
      | Bool
otherwise                               = Maybe Name
forall a. Maybe a
Nothing

instanceCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
-- (instanceCantMatch tcs1 tcs2) returns True if tcs1 cannot
-- possibly be instantiated to actual, nor vice versa;
-- False is non-committal
instanceCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
instanceCantMatch (mt :: Maybe Name
mt : ts :: [Maybe Name]
ts) (ma :: Maybe Name
ma : as :: [Maybe Name]
as) = Maybe Name -> Maybe Name -> Bool
itemCantMatch Maybe Name
mt Maybe Name
ma Bool -> Bool -> Bool
|| [Maybe Name] -> [Maybe Name] -> Bool
instanceCantMatch [Maybe Name]
ts [Maybe Name]
as
instanceCantMatch _         _         =  Bool
False  -- Safe

itemCantMatch :: Maybe Name -> Maybe Name -> Bool
itemCantMatch :: Maybe Name -> Maybe Name -> Bool
itemCantMatch (Just t :: Name
t) (Just a :: Name
a) = Name
t Name -> Name -> Bool
forall a. Eq a => a -> a -> Bool
/= Name
a
itemCantMatch _        _        = Bool
False


{-
************************************************************************
*                                                                      *
                GADTs
*                                                                      *
************************************************************************

Note [Pruning dead case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider        data T a where
                   T1 :: T Int
                   T2 :: T a

                newtype X = MkX Int
                newtype Y = MkY Char

                type family F a
                type instance F Bool = Int

Now consider    case x of { T1 -> e1; T2 -> e2 }

The question before the house is this: if I know something about the type
of x, can I prune away the T1 alternative?

Suppose x::T Char.  It's impossible to construct a (T Char) using T1,
        Answer = YES we can prune the T1 branch (clearly)

Suppose x::T (F a), where 'a' is in scope.  Then 'a' might be instantiated
to 'Bool', in which case x::T Int, so
        ANSWER = NO (clearly)

We see here that we want precisely the apartness check implemented within
tcUnifyTysFG. So that's what we do! Two types cannot match if they are surely
apart. Note that since we are simply dropping dead code, a conservative test
suffices.
-}

-- | Given a list of pairs of types, are any two members of a pair surely
-- apart, even after arbitrary type function evaluation and substitution?
typesCantMatch :: [(Type,Type)] -> Bool
-- See Note [Pruning dead case alternatives]
typesCantMatch :: [(Type, Type)] -> Bool
typesCantMatch prs :: [(Type, Type)]
prs = ((Type, Type) -> Bool) -> [(Type, Type)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ((Type -> Type -> Bool) -> (Type, Type) -> Bool
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Type -> Type -> Bool
cant_match) [(Type, Type)]
prs
  where
    cant_match :: Type -> Type -> Bool
    cant_match :: Type -> Type -> Bool
cant_match t1 :: Type
t1 t2 :: Type
t2 = case (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tcUnifyTysFG (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) [Type
t1] [Type
t2] of
      SurelyApart -> Bool
True
      _           -> Bool
False

{-
************************************************************************
*                                                                      *
             Unification
*                                                                      *
************************************************************************

Note [Fine-grained unification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do the types (x, x) and ([y], y) unify? The answer is seemingly "no" --
no substitution to finite types makes these match. But, a substitution to
*infinite* types can unify these two types: [x |-> [[[...]]], y |-> [[[...]]] ].
Why do we care? Consider these two type family instances:

type instance F x x   = Int
type instance F [y] y = Bool

If we also have

type instance Looper = [Looper]

then the instances potentially overlap. The solution is to use unification
over infinite terms. This is possible (see [1] for lots of gory details), but
a full algorithm is a little more power than we need. Instead, we make a
conservative approximation and just omit the occurs check.

[1]: http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/axioms-extended.pdf

tcUnifyTys considers an occurs-check problem as the same as general unification
failure.

tcUnifyTysFG ("fine-grained") returns one of three results: success, occurs-check
failure ("MaybeApart"), or general failure ("SurelyApart").

See also Trac #8162.

It's worth noting that unification in the presence of infinite types is not
complete. This means that, sometimes, a closed type family does not reduce
when it should. See test case indexed-types/should_fail/Overlap15 for an
example.

Note [The substitution in MaybeApart]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The constructor MaybeApart carries data with it, typically a TvSubstEnv. Why?
Because consider unifying these:

(a, a, Int) ~ (b, [b], Bool)

If we go left-to-right, we start with [a |-> b]. Then, on the middle terms, we
apply the subst we have so far and discover that we need [b |-> [b]]. Because
this fails the occurs check, we say that the types are MaybeApart (see above
Note [Fine-grained unification]). But, we can't stop there! Because if we
continue, we discover that Int is SurelyApart from Bool, and therefore the
types are apart. This has practical consequences for the ability for closed
type family applications to reduce. See test case
indexed-types/should_compile/Overlap14.

Note [Unifying with skolems]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we discover that two types unify if and only if a skolem variable is
substituted, we can't properly unify the types. But, that skolem variable
may later be instantiated with a unifyable type. So, we return maybeApart
in these cases.
-}

-- | Simple unification of two types; all type variables are bindable
-- Precondition: the kinds are already equal
tcUnifyTy :: Type -> Type       -- All tyvars are bindable
          -> Maybe TCvSubst
                       -- A regular one-shot (idempotent) substitution
tcUnifyTy :: Type -> Type -> Maybe TCvSubst
tcUnifyTy t1 :: Type
t1 t2 :: Type
t2 = (TyVar -> BindFlag) -> [Type] -> [Type] -> Maybe TCvSubst
tcUnifyTys (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) [Type
t1] [Type
t2]

-- | Like 'tcUnifyTy', but also unifies the kinds
tcUnifyTyKi :: Type -> Type -> Maybe TCvSubst
tcUnifyTyKi :: Type -> Type -> Maybe TCvSubst
tcUnifyTyKi t1 :: Type
t1 t2 :: Type
t2 = (TyVar -> BindFlag) -> [Type] -> [Type] -> Maybe TCvSubst
tcUnifyTyKis (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) [Type
t1] [Type
t2]

-- | Unify two types, treating type family applications as possibly unifying
-- with anything and looking through injective type family applications.
-- Precondition: kinds are the same
tcUnifyTyWithTFs :: Bool  -- ^ True <=> do two-way unification;
                          --   False <=> do one-way matching.
                          --   See end of sec 5.2 from the paper
                 -> Type -> Type -> Maybe TCvSubst
-- This algorithm is an implementation of the "Algorithm U" presented in
-- the paper "Injective type families for Haskell", Figures 2 and 3.
-- The code is incorporated with the standard unifier for convenience, but
-- its operation should match the specification in the paper.
tcUnifyTyWithTFs :: Bool -> Type -> Type -> Maybe TCvSubst
tcUnifyTyWithTFs twoWay :: Bool
twoWay t1 :: Type
t1 t2 :: Type
t2
  = case (TyVar -> BindFlag)
-> Bool
-> Bool
-> Bool
-> RnEnv2
-> TvSubstEnv
-> CvSubstEnv
-> [Type]
-> [Type]
-> UnifyResultM (TvSubstEnv, CvSubstEnv)
tc_unify_tys (BindFlag -> TyVar -> BindFlag
forall a b. a -> b -> a
const BindFlag
BindMe) Bool
twoWay Bool
True Bool
False
                       RnEnv2
rn_env TvSubstEnv
emptyTvSubstEnv CvSubstEnv
emptyCvSubstEnv
                       [Type
t1] [Type
t2] of
      Unifiable  (subst :: TvSubstEnv
subst, _) -> TCvSubst -> Maybe TCvSubst
forall a. a -> Maybe a
Just (TCvSubst -> Maybe TCvSubst) -> TCvSubst -> Maybe TCvSubst
forall a b. (a -> b) -> a -> b
$ TvSubstEnv -> TCvSubst
niFixTCvSubst TvSubstEnv
subst
      MaybeApart (subst :: TvSubstEnv
subst, _) -> TCvSubst -> Maybe TCvSubst
forall a. a -> Maybe a
Just (TCvSubst -> Maybe TCvSubst) -> TCvSubst -> Maybe TCvSubst
forall a b. (a -> b) -> a -> b
$ TvSubstEnv -> TCvSubst
niFixTCvSubst TvSubstEnv
subst
      -- we want to *succeed* in questionable cases. This is a
      -- pre-unification algorithm.
      SurelyApart      -> Maybe TCvSubst
forall a. Maybe a
Nothing
  where
    rn_env :: RnEnv2
rn_env = InScopeSet -> RnEnv2
mkRnEnv2 (InScopeSet -> RnEnv2) -> InScopeSet -> RnEnv2
forall a b. (a -> b) -> a -> b
$ VarSet -> InScopeSet
mkInScopeSet (VarSet -> InScopeSet) -> VarSet -> InScopeSet
forall a b. (a -> b) -> a -> b
$ [Type] -> VarSet
tyCoVarsOfTypes [Type
t1, Type
t2]

-----------------
tcUnifyTys :: (TyCoVar -> BindFlag)
           -> [Type] -> [Type]
           -> Maybe TCvSubst
                                -- ^ A regular one-shot (idempotent) substitution
                                -- that unifies the erased types. See comments
                                -- for 'tcUnifyTysFG'

-- The two types may have common type variables, and indeed do so in the
-- second call to tcUnifyTys in FunDeps.checkClsFD
tcUnifyTys :: (TyVar -> BindFlag) -> [Type] -> [Type] -> Maybe TCvSubst
tcUnifyTys bind_fn :: TyVar -> BindFlag
bind_fn tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = case (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tcUnifyTysFG TyVar -> BindFlag
bind_fn [Type]
tys1 [Type]
tys2 of
      Unifiable result :: TCvSubst
result -> TCvSubst -> Maybe TCvSubst
forall a. a -> Maybe a
Just TCvSubst
result
      _                -> Maybe TCvSubst
forall a. Maybe a
Nothing

-- | Like 'tcUnifyTys' but also unifies the kinds
tcUnifyTyKis :: (TyCoVar -> BindFlag)
             -> [Type] -> [Type]
             -> Maybe TCvSubst
tcUnifyTyKis :: (TyVar -> BindFlag) -> [Type] -> [Type] -> Maybe TCvSubst
tcUnifyTyKis bind_fn :: TyVar -> BindFlag
bind_fn tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = case (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tcUnifyTyKisFG TyVar -> BindFlag
bind_fn [Type]
tys1 [Type]
tys2 of
      Unifiable result :: TCvSubst
result -> TCvSubst -> Maybe TCvSubst
forall a. a -> Maybe a
Just TCvSubst
result
      _                -> Maybe TCvSubst
forall a. Maybe a
Nothing

-- This type does double-duty. It is used in the UM (unifier monad) and to
-- return the final result. See Note [Fine-grained unification]
type UnifyResult = UnifyResultM TCvSubst
data UnifyResultM a = Unifiable a        -- the subst that unifies the types
                    | MaybeApart a       -- the subst has as much as we know
                                         -- it must be part of a most general unifier
                                         -- See Note [The substitution in MaybeApart]
                    | SurelyApart
                    deriving a -> UnifyResultM b -> UnifyResultM a
(a -> b) -> UnifyResultM a -> UnifyResultM b
(forall a b. (a -> b) -> UnifyResultM a -> UnifyResultM b)
-> (forall a b. a -> UnifyResultM b -> UnifyResultM a)
-> Functor UnifyResultM
forall a b. a -> UnifyResultM b -> UnifyResultM a
forall a b. (a -> b) -> UnifyResultM a -> UnifyResultM b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
<$ :: a -> UnifyResultM b -> UnifyResultM a
$c<$ :: forall a b. a -> UnifyResultM b -> UnifyResultM a
fmap :: (a -> b) -> UnifyResultM a -> UnifyResultM b
$cfmap :: forall a b. (a -> b) -> UnifyResultM a -> UnifyResultM b
Functor

instance Applicative UnifyResultM where
  pure :: a -> UnifyResultM a
pure  = a -> UnifyResultM a
forall a. a -> UnifyResultM a
Unifiable
  <*> :: UnifyResultM (a -> b) -> UnifyResultM a -> UnifyResultM b
(<*>) = UnifyResultM (a -> b) -> UnifyResultM a -> UnifyResultM b
forall (m :: * -> *) a b. Monad m => m (a -> b) -> m a -> m b
ap

instance Monad UnifyResultM where

  SurelyApart  >>= :: UnifyResultM a -> (a -> UnifyResultM b) -> UnifyResultM b
>>= _ = UnifyResultM b
forall a. UnifyResultM a
SurelyApart
  MaybeApart x :: a
x >>= f :: a -> UnifyResultM b
f = case a -> UnifyResultM b
f a
x of
                         Unifiable y :: b
y -> b -> UnifyResultM b
forall a. a -> UnifyResultM a
MaybeApart b
y
                         other :: UnifyResultM b
other       -> UnifyResultM b
other
  Unifiable x :: a
x  >>= f :: a -> UnifyResultM b
f = a -> UnifyResultM b
f a
x

instance Alternative UnifyResultM where
  empty :: UnifyResultM a
empty = UnifyResultM a
forall a. UnifyResultM a
SurelyApart

  a :: UnifyResultM a
a@(Unifiable {})  <|> :: UnifyResultM a -> UnifyResultM a -> UnifyResultM a
<|> _                 = UnifyResultM a
a
  _                 <|> b :: UnifyResultM a
b@(Unifiable {})  = UnifyResultM a
b
  a :: UnifyResultM a
a@(MaybeApart {}) <|> _                 = UnifyResultM a
a
  _                 <|> b :: UnifyResultM a
b@(MaybeApart {}) = UnifyResultM a
b
  SurelyApart       <|> SurelyApart       = UnifyResultM a
forall a. UnifyResultM a
SurelyApart

instance MonadPlus UnifyResultM

-- | @tcUnifyTysFG bind_tv tys1 tys2@ attepts to find a substitution @s@ (whose
-- domain elements all respond 'BindMe' to @bind_tv@) such that
-- @s(tys1)@ and that of @s(tys2)@ are equal, as witnessed by the returned
-- Coercions. This version requires that the kinds of the types are the same,
-- if you unify left-to-right.
tcUnifyTysFG :: (TyVar -> BindFlag)
             -> [Type] -> [Type]
             -> UnifyResult
tcUnifyTysFG :: (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tcUnifyTysFG bind_fn :: TyVar -> BindFlag
bind_fn tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = Bool -> (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tc_unify_tys_fg Bool
False TyVar -> BindFlag
bind_fn [Type]
tys1 [Type]
tys2

tcUnifyTyKisFG :: (TyVar -> BindFlag)
               -> [Type] -> [Type]
               -> UnifyResult
tcUnifyTyKisFG :: (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tcUnifyTyKisFG bind_fn :: TyVar -> BindFlag
bind_fn tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = Bool -> (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tc_unify_tys_fg Bool
True TyVar -> BindFlag
bind_fn [Type]
tys1 [Type]
tys2

tc_unify_tys_fg :: Bool
                -> (TyVar -> BindFlag)
                -> [Type] -> [Type]
                -> UnifyResult
tc_unify_tys_fg :: Bool -> (TyVar -> BindFlag) -> [Type] -> [Type] -> UnifyResult
tc_unify_tys_fg match_kis :: Bool
match_kis bind_fn :: TyVar -> BindFlag
bind_fn tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = do { (env :: TvSubstEnv
env, _) <- (TyVar -> BindFlag)
-> Bool
-> Bool
-> Bool
-> RnEnv2
-> TvSubstEnv
-> CvSubstEnv
-> [Type]
-> [Type]
-> UnifyResultM (TvSubstEnv, CvSubstEnv)
tc_unify_tys TyVar -> BindFlag
bind_fn Bool
True Bool
False Bool
match_kis RnEnv2
env
                                  TvSubstEnv
emptyTvSubstEnv CvSubstEnv
emptyCvSubstEnv
                                  [Type]
tys1 [Type]
tys2
       ; TCvSubst -> UnifyResult
forall (m :: * -> *) a. Monad m => a -> m a
return (TCvSubst -> UnifyResult) -> TCvSubst -> UnifyResult
forall a b. (a -> b) -> a -> b
$ TvSubstEnv -> TCvSubst
niFixTCvSubst TvSubstEnv
env }
  where
    vars :: VarSet
vars = [Type] -> VarSet
tyCoVarsOfTypes [Type]
tys1 VarSet -> VarSet -> VarSet
`unionVarSet` [Type] -> VarSet
tyCoVarsOfTypes [Type]
tys2
    env :: RnEnv2
env  = InScopeSet -> RnEnv2
mkRnEnv2 (InScopeSet -> RnEnv2) -> InScopeSet -> RnEnv2
forall a b. (a -> b) -> a -> b
$ VarSet -> InScopeSet
mkInScopeSet VarSet
vars

-- | This function is actually the one to call the unifier -- a little
-- too general for outside clients, though.
tc_unify_tys :: (TyVar -> BindFlag)
             -> AmIUnifying -- ^ True <=> unify; False <=> match
             -> Bool        -- ^ True <=> doing an injectivity check
             -> Bool        -- ^ True <=> treat the kinds as well
             -> RnEnv2
             -> TvSubstEnv  -- ^ substitution to extend
             -> CvSubstEnv
             -> [Type] -> [Type]
             -> UnifyResultM (TvSubstEnv, CvSubstEnv)
-- NB: It's tempting to ASSERT here that, if we're not matching kinds, then
-- the kinds of the types should be the same. However, this doesn't work,
-- as the types may be a dependent telescope, where later types have kinds
-- that mention variables occurring earlier in the list of types. Here's an
-- example (from typecheck/should_fail/T12709):
--   template: [rep :: RuntimeRep,       a :: TYPE rep]
--   target:   [LiftedRep :: RuntimeRep, Int :: TYPE LiftedRep]
-- We can see that matching the first pair will make the kinds of the second
-- pair equal. Yet, we still don't need a separate pass to unify the kinds
-- of these types, so it's appropriate to use the Ty variant of unification.
-- See also Note [tcMatchTy vs tcMatchTyKi].
tc_unify_tys :: (TyVar -> BindFlag)
-> Bool
-> Bool
-> Bool
-> RnEnv2
-> TvSubstEnv
-> CvSubstEnv
-> [Type]
-> [Type]
-> UnifyResultM (TvSubstEnv, CvSubstEnv)
tc_unify_tys bind_fn :: TyVar -> BindFlag
bind_fn unif :: Bool
unif inj_check :: Bool
inj_check match_kis :: Bool
match_kis rn_env :: RnEnv2
rn_env tv_env :: TvSubstEnv
tv_env cv_env :: CvSubstEnv
cv_env tys1 :: [Type]
tys1 tys2 :: [Type]
tys2
  = TvSubstEnv
-> CvSubstEnv
-> UM (TvSubstEnv, CvSubstEnv)
-> UnifyResultM (TvSubstEnv, CvSubstEnv)
forall a. TvSubstEnv -> CvSubstEnv -> UM a -> UnifyResultM a
initUM TvSubstEnv
tv_env CvSubstEnv
cv_env (UM (TvSubstEnv, CvSubstEnv)
 -> UnifyResultM (TvSubstEnv, CvSubstEnv))
-> UM (TvSubstEnv, CvSubstEnv)
-> UnifyResultM (TvSubstEnv, CvSubstEnv)
forall a b. (a -> b) -> a -> b
$
    do { Bool -> UM () -> UM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
match_kis (UM () -> UM ()) -> UM () -> UM ()
forall a b. (a -> b) -> a -> b
$
         UMEnv -> [Type] -> [Type] -> UM ()
unify_tys UMEnv
env [Type]
kis1 [Type]
kis2
       ; UMEnv -> [Type] -> [Type] -> UM ()
unify_tys UMEnv
env [Type]
tys1 [Type]
tys2
       ; (,) (TvSubstEnv -> CvSubstEnv -> (TvSubstEnv, CvSubstEnv))
-> UM TvSubstEnv -> UM (CvSubstEnv -> (TvSubstEnv, CvSubstEnv))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> UM TvSubstEnv
getTvSubstEnv UM (CvSubstEnv -> (TvSubstEnv, CvSubstEnv))
-> UM CvSubstEnv -> UM (TvSubstEnv, CvSubstEnv)
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> UM CvSubstEnv
getCvSubstEnv }
  where
    env :: UMEnv
env = UMEnv :: Bool -> Bool -> RnEnv2 -> VarSet -> (TyVar -> BindFlag) -> UMEnv
UMEnv { um_bind_fun :: TyVar -> BindFlag
um_bind_fun = TyVar -> BindFlag
bind_fn
                , um_skols :: VarSet
um_skols    = VarSet
emptyVarSet
                , um_unif :: Bool
um_unif     = Bool
unif
                , um_inj_tf :: Bool
um_inj_tf   = Bool
inj_check
                , um_rn_env :: RnEnv2
um_rn_env   = RnEnv2
rn_env }

    kis1 :: [Type]
kis1 = (Type -> Type) -> [Type] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map HasDebugCallStack => Type -> Type
Type -> Type
typeKind [Type]
tys1
    kis2 :: [Type]
kis2 = (Type -> Type) -> [Type] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map HasDebugCallStack => Type -> Type
Type -> Type
typeKind [Type]
tys2

instance Outputable a => Outputable (UnifyResultM a) where
  ppr :: UnifyResultM a -> SDoc
ppr SurelyApart    = String -> SDoc
text "SurelyApart"
  ppr (Unifiable x :: a
x)  = String -> SDoc
text "Unifiable" SDoc -> SDoc -> SDoc
<+> a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
x
  ppr (MaybeApart x :: a
x) = String -> SDoc
text "MaybeApart" SDoc -> SDoc -> SDoc
<+> a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
x

{-
************************************************************************
*                                                                      *
                Non-idempotent substitution
*                                                                      *
************************************************************************

Note [Non-idempotent substitution]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During unification we use a TvSubstEnv/CvSubstEnv pair that is
  (a) non-idempotent
  (b) loop-free; ie repeatedly applying it yields a fixed point

Note [Finding the substitution fixpoint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Finding the fixpoint of a non-idempotent substitution arising from a
unification is much trickier than it looks, because of kinds.  Consider
   T k (H k (f:k)) ~ T * (g:*)
If we unify, we get the substitution
   [ k -> *
   , g -> H k (f:k) ]
To make it idempotent we don't want to get just
   [ k -> *
   , g -> H * (f:k) ]
We also want to substitute inside f's kind, to get
   [ k -> *
   , g -> H k (f:*) ]
If we don't do this, we may apply the substitution to something,
and get an ill-formed type, i.e. one where typeKind will fail.
This happened, for example, in Trac #9106.

It gets worse.  In Trac #14164 we wanted to take the fixpoint of
this substitution
   [ xs_asV :-> F a_aY6 (z_aY7 :: a_aY6)
                        (rest_aWF :: G a_aY6 (z_aY7 :: a_aY6))
   , a_aY6  :-> a_aXQ ]

We have to apply the substitution for a_aY6 two levels deep inside
the invocation of F!  We don't have a function that recursively
applies substitutions inside the kinds of variable occurrences (and
probably rightly so).

So, we work as follows:

 1. Start with the current substitution (which we are
    trying to fixpoint
       [ xs :-> F a (z :: a) (rest :: G a (z :: a))
       , a  :-> b ]

 2. Take all the free vars of the range of the substitution:
       {a, z, rest, b}
    NB: the free variable finder closes over
    the kinds of variable occurrences

 3. If none are in the domain of the substitution, stop.
    We have found a fixpoint.

 4. Remove the variables that are bound by the substitution, leaving
       {z, rest, b}

 5. Do a topo-sort to put them in dependency order:
       [ b :: *, z :: a, rest :: G a z ]

 6. Apply the substitution left-to-right to the kinds of these
    tyvars, extending it each time with a new binding, so we
    finish up with
       [ xs   :-> ..as before..
       , a    :-> b
       , b    :-> b    :: *
       , z    :-> z    :: b
       , rest :-> rest :: G b (z :: b) ]
    Note that rest now has the right kind

 7. Apply this extended substitution (once) to the range of
    the /original/ substitution.  (Note that we do the
    extended substitution would go on forever if you tried
    to find its fixpoint, because it maps z to z.)

 8. And go back to step 1

In Step 6 we use the free vars from Step 2 as the initial
in-scope set, because all of those variables appear in the
range of the substitution, so they must all be in the in-scope
set.  But NB that the type substitution engine does not look up
variables in the in-scope set; it is used only to ensure no
shadowing.
-}

niFixTCvSubst :: TvSubstEnv -> TCvSubst
-- Find the idempotent fixed point of the non-idempotent substitution
-- This is surprisingly tricky:
--   see Note [Finding the substitution fixpoint]
-- ToDo: use laziness instead of iteration?
niFixTCvSubst :: TvSubstEnv -> TCvSubst
niFixTCvSubst tenv :: TvSubstEnv
tenv
  | Bool
not_fixpoint = TvSubstEnv -> TCvSubst
niFixTCvSubst ((Type -> Type) -> TvSubstEnv -> TvSubstEnv
forall a b. (a -> b) -> VarEnv a -> VarEnv b
mapVarEnv (HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst) TvSubstEnv
tenv)
  | Bool
otherwise    = TCvSubst
subst
  where
    range_fvs :: FV
    range_fvs :: FV
range_fvs = [Type] -> FV
tyCoFVsOfTypes (TvSubstEnv -> [Type]
forall elt. UniqFM elt -> [elt]
nonDetEltsUFM TvSubstEnv
tenv)
          -- It's OK to use nonDetEltsUFM here because the
          -- order of range_fvs, range_tvs is immaterial

    range_tvs :: [TyVar]
    range_tvs :: [TyVar]
range_tvs = FV -> [TyVar]
fvVarList FV
range_fvs

    not_fixpoint :: Bool
not_fixpoint  = (TyVar -> Bool) -> [TyVar] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any TyVar -> Bool
in_domain [TyVar]
range_tvs
    in_domain :: TyVar -> Bool
in_domain tv :: TyVar
tv  = TyVar
tv TyVar -> TvSubstEnv -> Bool
forall a. TyVar -> VarEnv a -> Bool
`elemVarEnv` TvSubstEnv
tenv

    free_tvs :: [TyVar]
free_tvs = [TyVar] -> [TyVar]
scopedSort ((TyVar -> Bool) -> [TyVar] -> [TyVar]
forall a. (a -> Bool) -> [a] -> [a]
filterOut TyVar -> Bool
in_domain [TyVar]
range_tvs)

    -- See Note [Finding the substitution fixpoint], Step 6
    init_in_scope :: InScopeSet
init_in_scope = VarSet -> InScopeSet
mkInScopeSet (FV -> VarSet
fvVarSet FV
range_fvs)
    subst :: TCvSubst
subst = (TCvSubst -> TyVar -> TCvSubst) -> TCvSubst -> [TyVar] -> TCvSubst
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' TCvSubst -> TyVar -> TCvSubst
add_free_tv
                  (InScopeSet -> TvSubstEnv -> TCvSubst
mkTvSubst InScopeSet
init_in_scope TvSubstEnv
tenv)
                  [TyVar]
free_tvs

    add_free_tv :: TCvSubst -> TyVar -> TCvSubst
    add_free_tv :: TCvSubst -> TyVar -> TCvSubst
add_free_tv subst :: TCvSubst
subst tv :: TyVar
tv
      = TCvSubst -> TyVar -> Type -> TCvSubst
extendTvSubst TCvSubst
subst TyVar
tv (TyVar -> Type
mkTyVarTy TyVar
tv')
     where
        tv' :: TyVar
tv' = (Type -> Type) -> TyVar -> TyVar
updateTyVarKind (HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst) TyVar
tv

niSubstTvSet :: TvSubstEnv -> TyCoVarSet -> TyCoVarSet
-- Apply the non-idempotent substitution to a set of type variables,
-- remembering that the substitution isn't necessarily idempotent
-- This is used in the occurs check, before extending the substitution
niSubstTvSet :: TvSubstEnv -> VarSet -> VarSet
niSubstTvSet tsubst :: TvSubstEnv
tsubst tvs :: VarSet
tvs
  = (TyVar -> VarSet -> VarSet) -> VarSet -> VarSet -> VarSet
forall elt a. (elt -> a -> a) -> a -> UniqSet elt -> a
nonDetFoldUniqSet (VarSet -> VarSet -> VarSet
unionVarSet (VarSet -> VarSet -> VarSet)
-> (TyVar -> VarSet) -> TyVar -> VarSet -> VarSet
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyVar -> VarSet
get) VarSet
emptyVarSet VarSet
tvs
  -- It's OK to nonDetFoldUFM here because we immediately forget the
  -- ordering by creating a set.
  where
    get :: TyVar -> VarSet
get tv :: TyVar
tv
      | Just ty :: Type
ty <- TvSubstEnv -> TyVar -> Maybe Type
forall a. VarEnv a -> TyVar -> Maybe a
lookupVarEnv TvSubstEnv
tsubst TyVar
tv
      = TvSubstEnv -> VarSet -> VarSet
niSubstTvSet TvSubstEnv
tsubst (Type -> VarSet
tyCoVarsOfType Type
ty)

      | Bool
otherwise
      = TyVar -> VarSet
unitVarSet TyVar
tv

{-
************************************************************************
*                                                                      *
                unify_ty: the main workhorse
*                                                                      *
************************************************************************

Note [Specification of unification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The pure unifier, unify_ty, defined in this module, tries to work out
a substitution to make two types say True to eqType. NB: eqType is
itself not purely syntactic; it accounts for CastTys;
see Note [Non-trivial definitional equality] in TyCoRep

Unlike the "impure unifiers" in the typechecker (the eager unifier in
TcUnify, and the constraint solver itself in TcCanonical), the pure
unifier It does /not/ work up to ~.

The algorithm implemented here is rather delicate, and we depend on it
to uphold certain properties. This is a summary of these required
properties. Any reference to "flattening" refers to the flattening
algorithm in FamInstEnv (See Note [Flattening] in FamInstEnv), not
the flattening algorithm in the solver.

Notation:
 θ,φ    substitutions
 ξ    type-function-free types
 τ,σ  other types
 τ♭   type τ, flattened

 ≡    eqType

(U1) Soundness.
     If (unify τ₁ τ₂) = Unifiable θ, then θ(τ₁) ≡ θ(τ₂).
     θ is a most general unifier for τ₁ and τ₂.

(U2) Completeness.
     If (unify ξ₁ ξ₂) = SurelyApart,
     then there exists no substitution θ such that θ(ξ₁) ≡ θ(ξ₂).

These two properties are stated as Property 11 in the "Closed Type Families"
paper (POPL'14). Below, this paper is called [CTF].

(U3) Apartness under substitution.
     If (unify ξ τ♭) = SurelyApart, then (unify ξ θ(τ)♭) = SurelyApart,
     for any θ. (Property 12 from [CTF])

(U4) Apart types do not unify.
     If (unify ξ τ♭) = SurelyApart, then there exists no θ
     such that θ(ξ) = θ(τ). (Property 13 from [CTF])

THEOREM. Completeness w.r.t ~
    If (unify τ₁♭ τ₂♭) = SurelyApart,
    then there exists no proof that (τ₁ ~ τ₂).

PROOF. See appendix of [CTF].


The unification algorithm is used for type family injectivity, as described
in the "Injective Type Families" paper (Haskell'15), called [ITF]. When run
in this mode, it has the following properties.

(I1) If (unify σ τ) = SurelyApart, then σ and τ are not unifiable, even
     after arbitrary type family reductions. Note that σ and τ are
     not flattened here.

(I2) If (unify σ τ) = MaybeApart θ, and if some
     φ exists such that φ(σ) ~ φ(τ), then φ extends θ.


Furthermore, the RULES matching algorithm requires this property,
but only when using this algorithm for matching:

(M1) If (match σ τ) succeeds with θ, then all matchable tyvars
     in σ are bound in θ.

     Property M1 means that we must extend the substitution with,
     say (a ↦ a) when appropriate during matching.
     See also Note [Self-substitution when matching].

(M2) Completeness of matching.
     If θ(σ) = τ, then (match σ τ) = Unifiable φ,
     where θ is an extension of φ.

Sadly, property M2 and I2 conflict. Consider

type family F1 a b where
  F1 Int    Bool   = Char
  F1 Double String = Char

Consider now two matching problems:

P1. match (F1 a Bool) (F1 Int Bool)
P2. match (F1 a Bool) (F1 Double String)

In case P1, we must find (a ↦ Int) to satisfy M2.
In case P2, we must /not/ find (a ↦ Double), in order to satisfy I2. (Note
that the correct mapping for I2 is (a ↦ Int). There is no way to discover
this, but we musn't map a to anything else!)

We thus must parameterize the algorithm over whether it's being used
for an injectivity check (refrain from looking at non-injective arguments
to type families) or not (do indeed look at those arguments).  This is
implemented  by the uf_inj_tf field of UmEnv.

(It's all a question of whether or not to include equation (7) from Fig. 2
of [ITF].)

This extra parameter is a bit fiddly, perhaps, but seemingly less so than
having two separate, almost-identical algorithms.

Note [Self-substitution when matching]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What should happen when we're *matching* (not unifying) a1 with a1? We
should get a substitution [a1 |-> a1]. A successful match should map all
the template variables (except ones that disappear when expanding synonyms).
But when unifying, we don't want to do this, because we'll then fall into
a loop.

This arrangement affects the code in three places:
 - If we're matching a refined template variable, don't recur. Instead, just
   check for equality. That is, if we know [a |-> Maybe a] and are matching
   (a ~? Maybe Int), we want to just fail.

 - Skip the occurs check when matching. This comes up in two places, because
   matching against variables is handled separately from matching against
   full-on types.

Note that this arrangement was provoked by a real failure, where the same
unique ended up in the template as in the target. (It was a rule firing when
compiling Data.List.NonEmpty.)

Note [Matching coercion variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:

   type family F a

   data G a where
     MkG :: F a ~ Bool => G a

   type family Foo (x :: G a) :: F a
   type instance Foo MkG = False

We would like that to be accepted. For that to work, we need to introduce
a coercion variable on the left and then use it on the right. Accordingly,
at use sites of Foo, we need to be able to use matching to figure out the
value for the coercion. (See the desugared version:

   axFoo :: [a :: *, c :: F a ~ Bool]. Foo (MkG c) = False |> (sym c)

) We never want this action to happen during *unification* though, when
all bets are off.

Note [Kind coercions in Unify]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We wish to match/unify while ignoring casts. But, we can't just ignore
them completely, or we'll end up with ill-kinded substitutions. For example,
say we're matching `a` with `ty |> co`. If we just drop the cast, we'll
return [a |-> ty], but `a` and `ty` might have different kinds. We can't
just match/unify their kinds, either, because this might gratuitously
fail. After all, `co` is the witness that the kinds are the same -- they
may look nothing alike.

So, we pass a kind coercion to the match/unify worker. This coercion witnesses
the equality between the substed kind of the left-hand type and the substed
kind of the right-hand type. Note that we do not unify kinds at the leaves
(as we did previously). We thus have

INVARIANT: In the call
    unify_ty ty1 ty2 kco
it must be that subst(kco) :: subst(kind(ty1)) ~N subst(kind(ty2)), where
`subst` is the ambient substitution in the UM monad.

To get this coercion, we first have to match/unify
the kinds before looking at the types. Happily, we need look only one level
up, as all kinds are guaranteed to have kind *.

When we're working with type applications (either TyConApp or AppTy) we
need to worry about establishing INVARIANT, as the kinds of the function
& arguments aren't (necessarily) included in the kind of the result.
When unifying two TyConApps, this is easy, because the two TyCons are
the same. Their kinds are thus the same. As long as we unify left-to-right,
we'll be sure to unify types' kinds before the types themselves. (For example,
think about Proxy :: forall k. k -> *. Unifying the first args matches up
the kinds of the second args.)

For AppTy, we must unify the kinds of the functions, but once these are
unified, we can continue unifying arguments without worrying further about
kinds.

The interface to this module includes both "...Ty" functions and
"...TyKi" functions. The former assume that INVARIANT is already
established, either because the kinds are the same or because the
list of types being passed in are the well-typed arguments to some
type constructor (see two paragraphs above). The latter take a separate
pre-pass over the kinds to establish INVARIANT. Sometimes, it's important
not to take the second pass, as it caused #12442.

We thought, at one point, that this was all unnecessary: why should
casts be in types in the first place? But they are sometimes. In
dependent/should_compile/KindEqualities2, we see, for example the
constraint Num (Int |> (blah ; sym blah)).  We naturally want to find
a dictionary for that constraint, which requires dealing with
coercions in this manner.

Note [Matching in the presence of casts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When matching, it is crucial that no variables from the template
end up in the range of the matching substitution (obviously!).
When unifying, that's not a constraint; instead we take the fixpoint
of the substitution at the end.

So what should we do with this, when matching?
   unify_ty (tmpl |> co) tgt kco

Previously, wrongly, we pushed 'co' in the (horrid) accumulating
'kco' argument like this:
   unify_ty (tmpl |> co) tgt kco
     = unify_ty tmpl tgt (kco ; co)

But that is obviously wrong because 'co' (from the template) ends
up in 'kco', which in turn ends up in the range of the substitution.

This all came up in Trac #13910.  Because we match tycon arguments
left-to-right, the ambient substitution will already have a matching
substitution for any kinds; so there is an easy fix: just apply
the substitution-so-far to the coercion from the LHS.

Note that

* When matching, the first arg of unify_ty is always the template;
  we never swap round.

* The above argument is distressingly indirect. We seek a
  better way.

* One better way is to ensure that type patterns (the template
  in the matching process) have no casts.  See Trac #14119.

Note [Polykinded tycon applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose  T :: forall k. Type -> K
and we are unifying
  ty1:  T @Type         Int       :: Type
  ty2:  T @(Type->Type) Int Int   :: Type

These two TyConApps have the same TyCon at the front but they
(legitimately) have different numbers of arguments.  They
are surelyApart, so we can report that without looking any
further (see Trac #15704).
-}

-------------- unify_ty: the main workhorse -----------

type AmIUnifying = Bool   -- True  <=> Unifying
                          -- False <=> Matching

unify_ty :: UMEnv
         -> Type -> Type  -- Types to be unified and a co
         -> CoercionN     -- A coercion between their kinds
                          -- See Note [Kind coercions in Unify]
         -> UM ()
-- See Note [Specification of unification]
-- Respects newtypes, PredTypes

unify_ty :: UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty env :: UMEnv
env ty1 :: Type
ty1 ty2 :: Type
ty2 kco :: Coercion
kco
    -- TODO: More commentary needed here
  | Just ty1' :: Type
ty1' <- Type -> Maybe Type
tcView Type
ty1   = UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env Type
ty1' Type
ty2 Coercion
kco
  | Just ty2' :: Type
ty2' <- Type -> Maybe Type
tcView Type
ty2   = UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env Type
ty1 Type
ty2' Coercion
kco
  | CastTy ty1' :: Type
ty1' co :: Coercion
co <- Type
ty1     = if UMEnv -> Bool
um_unif UMEnv
env
                                then UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env Type
ty1' Type
ty2 (Coercion
co Coercion -> Coercion -> Coercion
`mkTransCo` Coercion
kco)
                                else -- See Note [Matching in the presence of casts]
                                     do { TCvSubst
subst <- UMEnv -> UM TCvSubst
getSubst UMEnv
env
                                        ; let co' :: Coercion
co' = HasCallStack => TCvSubst -> Coercion -> Coercion
TCvSubst -> Coercion -> Coercion
substCo TCvSubst
subst Coercion
co
                                        ; UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env Type
ty1' Type
ty2 (Coercion
co' Coercion -> Coercion -> Coercion
`mkTransCo` Coercion
kco) }
  | CastTy ty2' :: Type
ty2' co :: Coercion
co <- Type
ty2     = UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env Type
ty1 Type
ty2' (Coercion
kco Coercion -> Coercion -> Coercion
`mkTransCo` Coercion -> Coercion
mkSymCo Coercion
co)

unify_ty env :: UMEnv
env (TyVarTy tv1 :: TyVar
tv1) ty2 :: Type
ty2 kco :: Coercion
kco
  = UMEnv -> TyVar -> Type -> Coercion -> UM ()
uVar UMEnv
env TyVar
tv1 Type
ty2 Coercion
kco
unify_ty env :: UMEnv
env ty1 :: Type
ty1 (TyVarTy tv2 :: TyVar
tv2) kco :: Coercion
kco
  | UMEnv -> Bool
um_unif UMEnv
env  -- If unifying, can swap args
  = UMEnv -> TyVar -> Type -> Coercion -> UM ()
uVar (UMEnv -> UMEnv
umSwapRn UMEnv
env) TyVar
tv2 Type
ty1 (Coercion -> Coercion
mkSymCo Coercion
kco)

unify_ty env :: UMEnv
env ty1 :: Type
ty1 ty2 :: Type
ty2 _kco :: Coercion
_kco
  | Just (tc1 :: TyCon
tc1, tys1 :: [Type]
tys1) <- Maybe (TyCon, [Type])
mb_tc_app1
  , Just (tc2 :: TyCon
tc2, tys2 :: [Type]
tys2) <- Maybe (TyCon, [Type])
mb_tc_app2
  , TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2 Bool -> Bool -> Bool
|| (Type -> Bool
tcIsLiftedTypeKind Type
ty1 Bool -> Bool -> Bool
&& Type -> Bool
tcIsLiftedTypeKind Type
ty2)
  = if TyCon -> Role -> Bool
isInjectiveTyCon TyCon
tc1 Role
Nominal
    then UMEnv -> [Type] -> [Type] -> UM ()
unify_tys UMEnv
env [Type]
tys1 [Type]
tys2
    else do { let inj :: [Bool]
inj | TyCon -> Bool
isTypeFamilyTyCon TyCon
tc1
                      = case TyCon -> Injectivity
tyConInjectivityInfo TyCon
tc1 of
                               NotInjective -> Bool -> [Bool]
forall a. a -> [a]
repeat Bool
False
                               Injective bs :: [Bool]
bs -> [Bool]
bs
                      | Bool
otherwise
                      = Bool -> [Bool]
forall a. a -> [a]
repeat Bool
False

                  (inj_tys1 :: [Type]
inj_tys1, noninj_tys1 :: [Type]
noninj_tys1) = [Bool] -> [Type] -> ([Type], [Type])
forall a. [Bool] -> [a] -> ([a], [a])
partitionByList [Bool]
inj [Type]
tys1
                  (inj_tys2 :: [Type]
inj_tys2, noninj_tys2 :: [Type]
noninj_tys2) = [Bool] -> [Type] -> ([Type], [Type])
forall a. [Bool] -> [a] -> ([a], [a])
partitionByList [Bool]
inj [Type]
tys2

            ; UMEnv -> [Type] -> [Type] -> UM ()
unify_tys UMEnv
env [Type]
inj_tys1 [Type]
inj_tys2
            ; Bool -> UM () -> UM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (UMEnv -> Bool
um_inj_tf UMEnv
env) (UM () -> UM ()) -> UM () -> UM ()
forall a b. (a -> b) -> a -> b
$ -- See (end of) Note [Specification of unification]
              UM () -> UM ()
don'tBeSoSure (UM () -> UM ()) -> UM () -> UM ()
forall a b. (a -> b) -> a -> b
$ UMEnv -> [Type] -> [Type] -> UM ()
unify_tys UMEnv
env [Type]
noninj_tys1 [Type]
noninj_tys2 }

  | Just (tc1 :: TyCon
tc1, _) <- Maybe (TyCon, [Type])
mb_tc_app1
  , Bool -> Bool
not (TyCon -> Role -> Bool
isGenerativeTyCon TyCon
tc1 Role
Nominal)
    -- E.g.   unify_ty (F ty1) b  =  MaybeApart
    --        because the (F ty1) behaves like a variable
    --        NB: if unifying, we have already dealt
    --            with the 'ty2 = variable' case
  = UM ()
maybeApart

  | Just (tc2 :: TyCon
tc2, _) <- Maybe (TyCon, [Type])
mb_tc_app2
  , Bool -> Bool
not (TyCon -> Role -> Bool
isGenerativeTyCon TyCon
tc2 Role
Nominal)
  , UMEnv -> Bool
um_unif UMEnv
env
    -- E.g.   unify_ty [a] (F ty2) =  MaybeApart, when unifying (only)
    --        because the (F ty2) behaves like a variable
    --        NB: we have already dealt with the 'ty1 = variable' case
  = UM ()
maybeApart

  where
    mb_tc_app1 :: Maybe (TyCon, [Type])
mb_tc_app1 = HasCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
tcSplitTyConApp_maybe Type
ty1
    mb_tc_app2 :: Maybe (TyCon, [Type])
mb_tc_app2 = HasCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
tcSplitTyConApp_maybe Type
ty2

        -- Applications need a bit of care!
        -- They can match FunTy and TyConApp, so use splitAppTy_maybe
        -- NB: we've already dealt with type variables,
        -- so if one type is an App the other one jolly well better be too
unify_ty env :: UMEnv
env (AppTy ty1a :: Type
ty1a ty1b :: Type
ty1b) ty2 :: Type
ty2 _kco :: Coercion
_kco
  | Just (ty2a :: Type
ty2a, ty2b :: Type
ty2b) <- Type -> Maybe (Type, Type)
tcRepSplitAppTy_maybe Type
ty2
  = UMEnv -> Type -> [Type] -> Type -> [Type] -> UM ()
unify_ty_app UMEnv
env Type
ty1a [Type
ty1b] Type
ty2a [Type
ty2b]

unify_ty env :: UMEnv
env ty1 :: Type
ty1 (AppTy ty2a :: Type
ty2a ty2b :: Type
ty2b) _kco :: Coercion
_kco
  | Just (ty1a :: Type
ty1a, ty1b :: Type
ty1b) <- Type -> Maybe (Type, Type)
tcRepSplitAppTy_maybe Type
ty1
  = UMEnv -> Type -> [Type] -> Type -> [Type] -> UM ()
unify_ty_app UMEnv
env Type
ty1a [Type
ty1b] Type
ty2a [Type
ty2b]

unify_ty _ (LitTy x :: TyLit
x) (LitTy y :: TyLit
y) _kco :: Coercion
_kco | TyLit
x TyLit -> TyLit -> Bool
forall a. Eq a => a -> a -> Bool
== TyLit
y = () -> UM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

unify_ty env :: UMEnv
env (ForAllTy (Bndr tv1 :: TyVar
tv1 _) ty1 :: Type
ty1) (ForAllTy (Bndr tv2 :: TyVar
tv2 _) ty2 :: Type
ty2) kco :: Coercion
kco
  = do { UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env (TyVar -> Type
varType TyVar
tv1) (TyVar -> Type
varType TyVar
tv2) (Type -> Coercion
mkNomReflCo Type
liftedTypeKind)
       ; let env' :: UMEnv
env' = UMEnv -> TyVar -> TyVar -> UMEnv
umRnBndr2 UMEnv
env TyVar
tv1 TyVar
tv2
       ; UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env' Type
ty1 Type
ty2 Coercion
kco }

-- See Note [Matching coercion variables]
unify_ty env :: UMEnv
env (CoercionTy co1 :: Coercion
co1) (CoercionTy co2 :: Coercion
co2) kco :: Coercion
kco
  = do { CvSubstEnv
c_subst <- UM CvSubstEnv
getCvSubstEnv
       ; case Coercion
co1 of
           CoVarCo cv :: TyVar
cv
             | Bool -> Bool
not (UMEnv -> Bool
um_unif UMEnv
env)
             , Bool -> Bool
not (TyVar
cv TyVar -> CvSubstEnv -> Bool
forall a. TyVar -> VarEnv a -> Bool
`elemVarEnv` CvSubstEnv
c_subst)
             , BindFlag
BindMe <- UMEnv -> TyVar -> BindFlag
tvBindFlag UMEnv
env TyVar
cv
             -> do { UMEnv -> VarSet -> UM ()
checkRnEnv UMEnv
env (Coercion -> VarSet
tyCoVarsOfCo Coercion
co2)
                   ; let (co_l :: Coercion
co_l, co_r :: Coercion
co_r) = HasDebugCallStack => Role -> Coercion -> (Coercion, Coercion)
Role -> Coercion -> (Coercion, Coercion)
decomposeFunCo Role
Nominal Coercion
kco
                      -- cv :: t1 ~ t2
                      -- co2 :: s1 ~ s2
                      -- co_l :: t1 ~ s1
                      -- co_r :: t2 ~ s2
                   ; TyVar -> Coercion -> UM ()
extendCvEnv TyVar
cv (Coercion
co_l Coercion -> Coercion -> Coercion
`mkTransCo`
                                     Coercion
co2 Coercion -> Coercion -> Coercion
`mkTransCo`
                                     Coercion -> Coercion
mkSymCo Coercion
co_r) }
           _ -> () -> UM ()
forall (m :: * -> *) a. Monad m => a -> m a
return () }

unify_ty _ _ _ _ = UM ()
forall a. UM a
surelyApart

unify_ty_app :: UMEnv -> Type -> [Type] -> Type -> [Type] -> UM ()
unify_ty_app :: UMEnv -> Type -> [Type] -> Type -> [Type] -> UM ()
unify_ty_app env :: UMEnv
env ty1 :: Type
ty1 ty1args :: [Type]
ty1args ty2 :: Type
ty2 ty2args :: [Type]
ty2args
  | Just (ty1' :: Type
ty1', ty1a :: Type
ty1a) <- HasDebugCallStack => Type -> Maybe (Type, Type)
Type -> Maybe (Type, Type)
repSplitAppTy_maybe Type
ty1
  , Just (ty2' :: Type
ty2', ty2a :: Type
ty2a) <- HasDebugCallStack => Type -> Maybe (Type, Type)
Type -> Maybe (Type, Type)
repSplitAppTy_maybe Type
ty2
  = UMEnv -> Type -> [Type] -> Type -> [Type] -> UM ()
unify_ty_app UMEnv
env Type
ty1' (Type
ty1a Type -> [Type] -> [Type]
forall a. a -> [a] -> [a]
: [Type]
ty1args) Type
ty2' (Type
ty2a Type -> [Type] -> [Type]
forall a. a -> [a] -> [a]
: [Type]
ty2args)

  | Bool
otherwise
  = do { let ki1 :: Type
ki1 = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty1
             ki2 :: Type
ki2 = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty2
           -- See Note [Kind coercions in Unify]
       ; UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty  UMEnv
env Type
ki1 Type
ki2 (Type -> Coercion
mkNomReflCo Type
liftedTypeKind)
       ; UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty  UMEnv
env Type
ty1 Type
ty2 (Type -> Coercion
mkNomReflCo Type
ki1)
       ; UMEnv -> [Type] -> [Type] -> UM ()
unify_tys UMEnv
env [Type]
ty1args [Type]
ty2args }

unify_tys :: UMEnv -> [Type] -> [Type] -> UM ()
unify_tys :: UMEnv -> [Type] -> [Type] -> UM ()
unify_tys env :: UMEnv
env orig_xs :: [Type]
orig_xs orig_ys :: [Type]
orig_ys
  = [Type] -> [Type] -> UM ()
go [Type]
orig_xs [Type]
orig_ys
  where
    go :: [Type] -> [Type] -> UM ()
go []     []     = () -> UM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    go (x :: Type
x:xs :: [Type]
xs) (y :: Type
y:ys :: [Type]
ys)
      -- See Note [Kind coercions in Unify]
      = do { UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env Type
x Type
y (Type -> Coercion
mkNomReflCo (Type -> Coercion) -> Type -> Coercion
forall a b. (a -> b) -> a -> b
$ HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
x)
           ; [Type] -> [Type] -> UM ()
go [Type]
xs [Type]
ys }
    go _ _ = UM ()
forall a. UM a
surelyApart
      -- Possibly different saturations of a polykinded tycon
      -- See Note [Polykinded tycon applications]

---------------------------------
uVar :: UMEnv
     -> InTyVar         -- Variable to be unified
     -> Type            -- with this Type
     -> Coercion        -- :: kind tv ~N kind ty
     -> UM ()

uVar :: UMEnv -> TyVar -> Type -> Coercion -> UM ()
uVar env :: UMEnv
env tv1 :: TyVar
tv1 ty :: Type
ty kco :: Coercion
kco
 = do { -- Apply the ambient renaming
        let tv1' :: TyVar
tv1' = UMEnv -> TyVar -> TyVar
umRnOccL UMEnv
env TyVar
tv1

        -- Check to see whether tv1 is refined by the substitution
      ; TvSubstEnv
subst <- UM TvSubstEnv
getTvSubstEnv
      ; case (TvSubstEnv -> TyVar -> Maybe Type
forall a. VarEnv a -> TyVar -> Maybe a
lookupVarEnv TvSubstEnv
subst TyVar
tv1') of
          Just ty' :: Type
ty' | UMEnv -> Bool
um_unif UMEnv
env                -- Unifying, so call
                   -> UMEnv -> Type -> Type -> Coercion -> UM ()
unify_ty UMEnv
env Type
ty' Type
ty Coercion
kco   -- back into unify
                   | Bool
otherwise
                   -> -- Matching, we don't want to just recur here.
                      -- this is because the range of the subst is the target
                      -- type, not the template type. So, just check for
                      -- normal type equality.
                      Bool -> UM ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard ((Type
ty' Type -> Coercion -> Type
`mkCastTy` Coercion
kco) Type -> Type -> Bool
`eqType` Type
ty)
          Nothing  -> UMEnv -> TyVar -> Type -> Type -> Coercion -> UM ()
uUnrefined UMEnv
env TyVar
tv1' Type
ty Type
ty Coercion
kco } -- No, continue

uUnrefined :: UMEnv
           -> OutTyVar          -- variable to be unified
           -> Type              -- with this Type
           -> Type              -- (version w/ expanded synonyms)
           -> Coercion          -- :: kind tv ~N kind ty
           -> UM ()

-- We know that tv1 isn't refined

uUnrefined :: UMEnv -> TyVar -> Type -> Type -> Coercion -> UM ()
uUnrefined env :: UMEnv
env tv1' :: TyVar
tv1' ty2 :: Type
ty2 ty2' :: Type
ty2' kco :: Coercion
kco
  | Just ty2'' :: Type
ty2'' <- Type -> Maybe Type
coreView Type
ty2'
  = UMEnv -> TyVar -> Type -> Type -> Coercion -> UM ()
uUnrefined UMEnv
env TyVar
tv1' Type
ty2 Type
ty2'' Coercion
kco    -- Unwrap synonyms
                -- This is essential, in case we have
                --      type Foo a = a
                -- and then unify a ~ Foo a

  | TyVarTy tv2 :: TyVar
tv2 <- Type
ty2'
  = do { let tv2' :: TyVar
tv2' = UMEnv -> TyVar -> TyVar
umRnOccR UMEnv
env TyVar
tv2
       ; Bool -> UM () -> UM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (TyVar
tv1' TyVar -> TyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TyVar
tv2' Bool -> Bool -> Bool
&& UMEnv -> Bool
um_unif UMEnv
env) (UM () -> UM ()) -> UM () -> UM ()
forall a b. (a -> b) -> a -> b
$ do
           -- If we are unifying a ~ a, just return immediately
           -- Do not extend the substitution
           -- See Note [Self-substitution when matching]

          -- Check to see whether tv2 is refined
       { TvSubstEnv
subst <- UM TvSubstEnv
getTvSubstEnv
       ; case TvSubstEnv -> TyVar -> Maybe Type
forall a. VarEnv a -> TyVar -> Maybe a
lookupVarEnv TvSubstEnv
subst TyVar
tv2 of
         {  Just ty' :: Type
ty' | UMEnv -> Bool
um_unif UMEnv
env -> UMEnv -> TyVar -> Type -> Type -> Coercion -> UM ()
uUnrefined UMEnv
env TyVar
tv1' Type
ty' Type
ty' Coercion
kco
         ;  _ ->

    do {   -- So both are unrefined
           -- Bind one or the other, depending on which is bindable
       ; let b1 :: BindFlag
b1  = UMEnv -> TyVar -> BindFlag
tvBindFlag UMEnv
env TyVar
tv1'
             b2 :: BindFlag
b2  = UMEnv -> TyVar -> BindFlag
tvBindFlag UMEnv
env TyVar
tv2'
             ty1 :: Type
ty1 = TyVar -> Type
mkTyVarTy TyVar
tv1'
       ; case (BindFlag
b1, BindFlag
b2) of
           (BindMe, _) -> UMEnv -> TyVar -> Type -> UM ()
bindTv UMEnv
env TyVar
tv1' (Type
ty2 Type -> Coercion -> Type
`mkCastTy` Coercion -> Coercion
mkSymCo Coercion
kco)
           (_, BindMe) | UMEnv -> Bool
um_unif UMEnv
env
                       -> UMEnv -> TyVar -> Type -> UM ()
bindTv (UMEnv -> UMEnv
umSwapRn UMEnv
env) TyVar
tv2 (Type
ty1 Type -> Coercion -> Type
`mkCastTy` Coercion
kco)

           _ | TyVar
tv1' TyVar -> TyVar -> Bool
forall a. Eq a => a -> a -> Bool
== TyVar
tv2' -> () -> UM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
             -- How could this happen? If we're only matching and if
             -- we're comparing forall-bound variables.

           _ -> UM ()
maybeApart -- See Note [Unification with skolems]
  }}}}

uUnrefined env :: UMEnv
env tv1' :: TyVar
tv1' ty2 :: Type
ty2 _ kco :: Coercion
kco -- ty2 is not a type variable
  = case UMEnv -> TyVar -> BindFlag
tvBindFlag UMEnv
env TyVar
tv1' of
      Skolem -> UM ()
maybeApart  -- See Note [Unification with skolems]
      BindMe -> UMEnv -> TyVar -> Type -> UM ()
bindTv UMEnv
env TyVar
tv1' (Type
ty2 Type -> Coercion -> Type
`mkCastTy` Coercion -> Coercion
mkSymCo Coercion
kco)

bindTv :: UMEnv -> OutTyVar -> Type -> UM ()
-- OK, so we want to extend the substitution with tv := ty
-- But first, we must do a couple of checks
bindTv :: UMEnv -> TyVar -> Type -> UM ()
bindTv env :: UMEnv
env tv1 :: TyVar
tv1 ty2 :: Type
ty2
  = do  { let free_tvs2 :: VarSet
free_tvs2 = Type -> VarSet
tyCoVarsOfType Type
ty2

        -- Make sure tys mentions no local variables
        -- E.g.  (forall a. b) ~ (forall a. [a])
        -- We should not unify b := [a]!
        ; UMEnv -> VarSet -> UM ()
checkRnEnv UMEnv
env VarSet
free_tvs2

        -- Occurs check, see Note [Fine-grained unification]
        -- Make sure you include 'kco' (which ty2 does) Trac #14846
        ; Bool
occurs <- UMEnv -> TyVar -> VarSet -> UM Bool
occursCheck UMEnv
env TyVar
tv1 VarSet
free_tvs2

        ; if Bool
occurs then UM ()
maybeApart
                    else TyVar -> Type -> UM ()
extendTvEnv TyVar
tv1 Type
ty2 }

occursCheck :: UMEnv -> TyVar -> VarSet -> UM Bool
occursCheck :: UMEnv -> TyVar -> VarSet -> UM Bool
occursCheck env :: UMEnv
env tv :: TyVar
tv free_tvs :: VarSet
free_tvs
  | UMEnv -> Bool
um_unif UMEnv
env
  = do { TvSubstEnv
tsubst <- UM TvSubstEnv
getTvSubstEnv
       ; Bool -> UM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (TyVar
tv TyVar -> VarSet -> Bool
`elemVarSet` TvSubstEnv -> VarSet -> VarSet
niSubstTvSet TvSubstEnv
tsubst VarSet
free_tvs) }

  | Bool
otherwise      -- Matching; no occurs check
  = Bool -> UM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False   -- See Note [Self-substitution when matching]

{-
%************************************************************************
%*                                                                      *
                Binding decisions
*                                                                      *
************************************************************************
-}

data BindFlag
  = BindMe      -- A regular type variable

  | Skolem      -- This type variable is a skolem constant
                -- Don't bind it; it only matches itself
  deriving BindFlag -> BindFlag -> Bool
(BindFlag -> BindFlag -> Bool)
-> (BindFlag -> BindFlag -> Bool) -> Eq BindFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: BindFlag -> BindFlag -> Bool
$c/= :: BindFlag -> BindFlag -> Bool
== :: BindFlag -> BindFlag -> Bool
$c== :: BindFlag -> BindFlag -> Bool
Eq

{-
************************************************************************
*                                                                      *
                Unification monad
*                                                                      *
************************************************************************
-}

data UMEnv
  = UMEnv { UMEnv -> Bool
um_unif :: AmIUnifying

          , UMEnv -> Bool
um_inj_tf :: Bool
            -- Checking for injectivity?
            -- See (end of) Note [Specification of unification]

          , UMEnv -> RnEnv2
um_rn_env :: RnEnv2
            -- Renaming InTyVars to OutTyVars; this eliminates
            -- shadowing, and lines up matching foralls on the left
            -- and right

          , UMEnv -> VarSet
um_skols :: TyVarSet
            -- OutTyVars bound by a forall in this unification;
            -- Do not bind these in the substitution!
            -- See the function tvBindFlag

          , UMEnv -> TyVar -> BindFlag
um_bind_fun :: TyVar -> BindFlag
            -- User-supplied BindFlag function,
            -- for variables not in um_skols
          }

data UMState = UMState
                   { UMState -> TvSubstEnv
um_tv_env   :: TvSubstEnv
                   , UMState -> CvSubstEnv
um_cv_env   :: CvSubstEnv }

newtype UM a = UM { UM a -> UMState -> UnifyResultM (UMState, a)
unUM :: UMState -> UnifyResultM (UMState, a) }

instance Functor UM where
      fmap :: (a -> b) -> UM a -> UM b
fmap = (a -> b) -> UM a -> UM b
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM

instance Applicative UM where
      pure :: a -> UM a
pure a :: a
a = (UMState -> UnifyResultM (UMState, a)) -> UM a
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM (\s :: UMState
s -> (UMState, a) -> UnifyResultM (UMState, a)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (UMState
s, a
a))
      <*> :: UM (a -> b) -> UM a -> UM b
(<*>)  = UM (a -> b) -> UM a -> UM b
forall (m :: * -> *) a b. Monad m => m (a -> b) -> m a -> m b
ap

instance Monad UM where
#if !MIN_VERSION_base(4,13,0)
  fail     = MonadFail.fail
#endif
  m :: UM a
m >>= :: UM a -> (a -> UM b) -> UM b
>>= k :: a -> UM b
k  = (UMState -> UnifyResultM (UMState, b)) -> UM b
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM (\state :: UMState
state ->
                  do { (state' :: UMState
state', v :: a
v) <- UM a -> UMState -> UnifyResultM (UMState, a)
forall a. UM a -> UMState -> UnifyResultM (UMState, a)
unUM UM a
m UMState
state
                     ; UM b -> UMState -> UnifyResultM (UMState, b)
forall a. UM a -> UMState -> UnifyResultM (UMState, a)
unUM (a -> UM b
k a
v) UMState
state' })

-- need this instance because of a use of 'guard' above
instance Alternative UM where
  empty :: UM a
empty     = (UMState -> UnifyResultM (UMState, a)) -> UM a
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM (\_ -> UnifyResultM (UMState, a)
forall (f :: * -> *) a. Alternative f => f a
Control.Applicative.empty)
  m1 :: UM a
m1 <|> :: UM a -> UM a -> UM a
<|> m2 :: UM a
m2 = (UMState -> UnifyResultM (UMState, a)) -> UM a
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM (\state :: UMState
state ->
                  UM a -> UMState -> UnifyResultM (UMState, a)
forall a. UM a -> UMState -> UnifyResultM (UMState, a)
unUM UM a
m1 UMState
state UnifyResultM (UMState, a)
-> UnifyResultM (UMState, a) -> UnifyResultM (UMState, a)
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|>
                  UM a -> UMState -> UnifyResultM (UMState, a)
forall a. UM a -> UMState -> UnifyResultM (UMState, a)
unUM UM a
m2 UMState
state)

instance MonadPlus UM

instance MonadFail.MonadFail UM where
    fail :: String -> UM a
fail _   = (UMState -> UnifyResultM (UMState, a)) -> UM a
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM (\_ -> UnifyResultM (UMState, a)
forall a. UnifyResultM a
SurelyApart) -- failed pattern match

initUM :: TvSubstEnv  -- subst to extend
       -> CvSubstEnv
       -> UM a -> UnifyResultM a
initUM :: TvSubstEnv -> CvSubstEnv -> UM a -> UnifyResultM a
initUM subst_env :: TvSubstEnv
subst_env cv_subst_env :: CvSubstEnv
cv_subst_env um :: UM a
um
  = case UM a -> UMState -> UnifyResultM (UMState, a)
forall a. UM a -> UMState -> UnifyResultM (UMState, a)
unUM UM a
um UMState
state of
      Unifiable (_, subst :: a
subst)  -> a -> UnifyResultM a
forall a. a -> UnifyResultM a
Unifiable a
subst
      MaybeApart (_, subst :: a
subst) -> a -> UnifyResultM a
forall a. a -> UnifyResultM a
MaybeApart a
subst
      SurelyApart           -> UnifyResultM a
forall a. UnifyResultM a
SurelyApart
  where
    state :: UMState
state = UMState :: TvSubstEnv -> CvSubstEnv -> UMState
UMState { um_tv_env :: TvSubstEnv
um_tv_env = TvSubstEnv
subst_env
                    , um_cv_env :: CvSubstEnv
um_cv_env = CvSubstEnv
cv_subst_env }

tvBindFlag :: UMEnv -> OutTyVar -> BindFlag
tvBindFlag :: UMEnv -> TyVar -> BindFlag
tvBindFlag env :: UMEnv
env tv :: TyVar
tv
  | TyVar
tv TyVar -> VarSet -> Bool
`elemVarSet` UMEnv -> VarSet
um_skols UMEnv
env = BindFlag
Skolem
  | Bool
otherwise                    = UMEnv -> TyVar -> BindFlag
um_bind_fun UMEnv
env TyVar
tv

getTvSubstEnv :: UM TvSubstEnv
getTvSubstEnv :: UM TvSubstEnv
getTvSubstEnv = (UMState -> UnifyResultM (UMState, TvSubstEnv)) -> UM TvSubstEnv
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM ((UMState -> UnifyResultM (UMState, TvSubstEnv)) -> UM TvSubstEnv)
-> (UMState -> UnifyResultM (UMState, TvSubstEnv)) -> UM TvSubstEnv
forall a b. (a -> b) -> a -> b
$ \state :: UMState
state -> (UMState, TvSubstEnv) -> UnifyResultM (UMState, TvSubstEnv)
forall a. a -> UnifyResultM a
Unifiable (UMState
state, UMState -> TvSubstEnv
um_tv_env UMState
state)

getCvSubstEnv :: UM CvSubstEnv
getCvSubstEnv :: UM CvSubstEnv
getCvSubstEnv = (UMState -> UnifyResultM (UMState, CvSubstEnv)) -> UM CvSubstEnv
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM ((UMState -> UnifyResultM (UMState, CvSubstEnv)) -> UM CvSubstEnv)
-> (UMState -> UnifyResultM (UMState, CvSubstEnv)) -> UM CvSubstEnv
forall a b. (a -> b) -> a -> b
$ \state :: UMState
state -> (UMState, CvSubstEnv) -> UnifyResultM (UMState, CvSubstEnv)
forall a. a -> UnifyResultM a
Unifiable (UMState
state, UMState -> CvSubstEnv
um_cv_env UMState
state)

getSubst :: UMEnv -> UM TCvSubst
getSubst :: UMEnv -> UM TCvSubst
getSubst env :: UMEnv
env = do { TvSubstEnv
tv_env <- UM TvSubstEnv
getTvSubstEnv
                  ; CvSubstEnv
cv_env <- UM CvSubstEnv
getCvSubstEnv
                  ; let in_scope :: InScopeSet
in_scope = RnEnv2 -> InScopeSet
rnInScopeSet (UMEnv -> RnEnv2
um_rn_env UMEnv
env)
                  ; TCvSubst -> UM TCvSubst
forall (m :: * -> *) a. Monad m => a -> m a
return (InScopeSet -> (TvSubstEnv, CvSubstEnv) -> TCvSubst
mkTCvSubst InScopeSet
in_scope (TvSubstEnv
tv_env, CvSubstEnv
cv_env)) }

extendTvEnv :: TyVar -> Type -> UM ()
extendTvEnv :: TyVar -> Type -> UM ()
extendTvEnv tv :: TyVar
tv ty :: Type
ty = (UMState -> UnifyResultM (UMState, ())) -> UM ()
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM ((UMState -> UnifyResultM (UMState, ())) -> UM ())
-> (UMState -> UnifyResultM (UMState, ())) -> UM ()
forall a b. (a -> b) -> a -> b
$ \state :: UMState
state ->
  (UMState, ()) -> UnifyResultM (UMState, ())
forall a. a -> UnifyResultM a
Unifiable (UMState
state { um_tv_env :: TvSubstEnv
um_tv_env = TvSubstEnv -> TyVar -> Type -> TvSubstEnv
forall a. VarEnv a -> TyVar -> a -> VarEnv a
extendVarEnv (UMState -> TvSubstEnv
um_tv_env UMState
state) TyVar
tv Type
ty }, ())

extendCvEnv :: CoVar -> Coercion -> UM ()
extendCvEnv :: TyVar -> Coercion -> UM ()
extendCvEnv cv :: TyVar
cv co :: Coercion
co = (UMState -> UnifyResultM (UMState, ())) -> UM ()
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM ((UMState -> UnifyResultM (UMState, ())) -> UM ())
-> (UMState -> UnifyResultM (UMState, ())) -> UM ()
forall a b. (a -> b) -> a -> b
$ \state :: UMState
state ->
  (UMState, ()) -> UnifyResultM (UMState, ())
forall a. a -> UnifyResultM a
Unifiable (UMState
state { um_cv_env :: CvSubstEnv
um_cv_env = CvSubstEnv -> TyVar -> Coercion -> CvSubstEnv
forall a. VarEnv a -> TyVar -> a -> VarEnv a
extendVarEnv (UMState -> CvSubstEnv
um_cv_env UMState
state) TyVar
cv Coercion
co }, ())

umRnBndr2 :: UMEnv -> TyCoVar -> TyCoVar -> UMEnv
umRnBndr2 :: UMEnv -> TyVar -> TyVar -> UMEnv
umRnBndr2 env :: UMEnv
env v1 :: TyVar
v1 v2 :: TyVar
v2
  = UMEnv
env { um_rn_env :: RnEnv2
um_rn_env = RnEnv2
rn_env', um_skols :: VarSet
um_skols = UMEnv -> VarSet
um_skols UMEnv
env VarSet -> TyVar -> VarSet
`extendVarSet` TyVar
v' }
  where
    (rn_env' :: RnEnv2
rn_env', v' :: TyVar
v') = RnEnv2 -> TyVar -> TyVar -> (RnEnv2, TyVar)
rnBndr2_var (UMEnv -> RnEnv2
um_rn_env UMEnv
env) TyVar
v1 TyVar
v2

checkRnEnv :: UMEnv -> VarSet -> UM ()
checkRnEnv :: UMEnv -> VarSet -> UM ()
checkRnEnv env :: UMEnv
env varset :: VarSet
varset
  | VarSet -> Bool
isEmptyVarSet VarSet
skol_vars           = () -> UM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  | VarSet
varset VarSet -> VarSet -> Bool
`disjointVarSet` VarSet
skol_vars = () -> UM ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  | Bool
otherwise                         = UM ()
maybeApart
               -- ToDo: why MaybeApart?
               -- I think SurelyApart would be right
  where
    skol_vars :: VarSet
skol_vars = UMEnv -> VarSet
um_skols UMEnv
env
    -- NB: That isEmptyVarSet guard is a critical optimization;
    -- it means we don't have to calculate the free vars of
    -- the type, often saving quite a bit of allocation.

-- | Converts any SurelyApart to a MaybeApart
don'tBeSoSure :: UM () -> UM ()
don'tBeSoSure :: UM () -> UM ()
don'tBeSoSure um :: UM ()
um = (UMState -> UnifyResultM (UMState, ())) -> UM ()
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM ((UMState -> UnifyResultM (UMState, ())) -> UM ())
-> (UMState -> UnifyResultM (UMState, ())) -> UM ()
forall a b. (a -> b) -> a -> b
$ \ state :: UMState
state ->
  case UM () -> UMState -> UnifyResultM (UMState, ())
forall a. UM a -> UMState -> UnifyResultM (UMState, a)
unUM UM ()
um UMState
state of
    SurelyApart -> (UMState, ()) -> UnifyResultM (UMState, ())
forall a. a -> UnifyResultM a
MaybeApart (UMState
state, ())
    other :: UnifyResultM (UMState, ())
other       -> UnifyResultM (UMState, ())
other

umRnOccL :: UMEnv -> TyVar -> TyVar
umRnOccL :: UMEnv -> TyVar -> TyVar
umRnOccL env :: UMEnv
env v :: TyVar
v = RnEnv2 -> TyVar -> TyVar
rnOccL (UMEnv -> RnEnv2
um_rn_env UMEnv
env) TyVar
v

umRnOccR :: UMEnv -> TyVar -> TyVar
umRnOccR :: UMEnv -> TyVar -> TyVar
umRnOccR env :: UMEnv
env v :: TyVar
v = RnEnv2 -> TyVar -> TyVar
rnOccR (UMEnv -> RnEnv2
um_rn_env UMEnv
env) TyVar
v

umSwapRn :: UMEnv -> UMEnv
umSwapRn :: UMEnv -> UMEnv
umSwapRn env :: UMEnv
env = UMEnv
env { um_rn_env :: RnEnv2
um_rn_env = RnEnv2 -> RnEnv2
rnSwap (UMEnv -> RnEnv2
um_rn_env UMEnv
env) }

maybeApart :: UM ()
maybeApart :: UM ()
maybeApart = (UMState -> UnifyResultM (UMState, ())) -> UM ()
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM (\state :: UMState
state -> (UMState, ()) -> UnifyResultM (UMState, ())
forall a. a -> UnifyResultM a
MaybeApart (UMState
state, ()))

surelyApart :: UM a
surelyApart :: UM a
surelyApart = (UMState -> UnifyResultM (UMState, a)) -> UM a
forall a. (UMState -> UnifyResultM (UMState, a)) -> UM a
UM (\_ -> UnifyResultM (UMState, a)
forall a. UnifyResultM a
SurelyApart)

{-
%************************************************************************
%*                                                                      *
            Matching a (lifted) type against a coercion
%*                                                                      *
%************************************************************************

This section defines essentially an inverse to liftCoSubst. It is defined
here to avoid a dependency from Coercion on this module.

-}

data MatchEnv = ME { MatchEnv -> VarSet
me_tmpls :: TyVarSet
                   , MatchEnv -> RnEnv2
me_env   :: RnEnv2 }

-- | 'liftCoMatch' is sort of inverse to 'liftCoSubst'.  In particular, if
--   @liftCoMatch vars ty co == Just s@, then @liftCoSubst s ty == co@,
--   where @==@ there means that the result of 'liftCoSubst' has the same
--   type as the original co; but may be different under the hood.
--   That is, it matches a type against a coercion of the same
--   "shape", and returns a lifting substitution which could have been
--   used to produce the given coercion from the given type.
--   Note that this function is incomplete -- it might return Nothing
--   when there does indeed exist a possible lifting context.
--
-- This function is incomplete in that it doesn't respect the equality
-- in `eqType`. That is, it's possible that this will succeed for t1 and
-- fail for t2, even when t1 `eqType` t2. That's because it depends on
-- there being a very similar structure between the type and the coercion.
-- This incompleteness shouldn't be all that surprising, especially because
-- it depends on the structure of the coercion, which is a silly thing to do.
--
-- The lifting context produced doesn't have to be exacting in the roles
-- of the mappings. This is because any use of the lifting context will
-- also require a desired role. Thus, this algorithm prefers mapping to
-- nominal coercions where it can do so.
liftCoMatch :: TyCoVarSet -> Type -> Coercion -> Maybe LiftingContext
liftCoMatch :: VarSet -> Type -> Coercion -> Maybe LiftingContext
liftCoMatch tmpls :: VarSet
tmpls ty :: Type
ty co :: Coercion
co
  = do { CvSubstEnv
cenv1 <- MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
forall a. VarEnv a
emptyVarEnv Type
ki Coercion
ki_co Coercion
ki_ki_co Coercion
ki_ki_co
       ; CvSubstEnv
cenv2 <- MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
cenv1       Type
ty Coercion
co
                              (Type -> Coercion
mkNomReflCo Type
co_lkind) (Type -> Coercion
mkNomReflCo Type
co_rkind)
       ; LiftingContext -> Maybe LiftingContext
forall (m :: * -> *) a. Monad m => a -> m a
return (TCvSubst -> CvSubstEnv -> LiftingContext
LC (InScopeSet -> TCvSubst
mkEmptyTCvSubst InScopeSet
in_scope) CvSubstEnv
cenv2) }
  where
    menv :: MatchEnv
menv     = ME :: VarSet -> RnEnv2 -> MatchEnv
ME { me_tmpls :: VarSet
me_tmpls = VarSet
tmpls, me_env :: RnEnv2
me_env = InScopeSet -> RnEnv2
mkRnEnv2 InScopeSet
in_scope }
    in_scope :: InScopeSet
in_scope = VarSet -> InScopeSet
mkInScopeSet (VarSet
tmpls VarSet -> VarSet -> VarSet
`unionVarSet` Coercion -> VarSet
tyCoVarsOfCo Coercion
co)
    -- Like tcMatchTy, assume all the interesting variables
    -- in ty are in tmpls

    ki :: Type
ki       = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty
    ki_co :: Coercion
ki_co    = Coercion -> Coercion
promoteCoercion Coercion
co
    ki_ki_co :: Coercion
ki_ki_co = Type -> Coercion
mkNomReflCo Type
liftedTypeKind

    Pair co_lkind :: Type
co_lkind co_rkind :: Type
co_rkind = Coercion -> Pair Type
coercionKind Coercion
ki_co

-- | 'ty_co_match' does all the actual work for 'liftCoMatch'.
ty_co_match :: MatchEnv   -- ^ ambient helpful info
            -> LiftCoEnv  -- ^ incoming subst
            -> Type       -- ^ ty, type to match
            -> Coercion   -- ^ co, coercion to match against
            -> Coercion   -- ^ :: kind of L type of substed ty ~N L kind of co
            -> Coercion   -- ^ :: kind of R type of substed ty ~N R kind of co
            -> Maybe LiftCoEnv
ty_co_match :: MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty :: Type
ty co :: Coercion
co lkco :: Coercion
lkco rkco :: Coercion
rkco
  | Just ty' :: Type
ty' <- Type -> Maybe Type
coreView Type
ty = MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ty' Coercion
co Coercion
lkco Coercion
rkco

  -- handle Refl case:
  | Type -> VarSet
tyCoVarsOfType Type
ty VarSet -> CvSubstEnv -> Bool
forall a. VarSet -> VarEnv a -> Bool
`isNotInDomainOf` CvSubstEnv
subst
  , Just (ty' :: Type
ty', _) <- Coercion -> Maybe (Type, Role)
isReflCo_maybe Coercion
co
  , Type
ty Type -> Type -> Bool
`eqType` Type
ty'
  = CvSubstEnv -> Maybe CvSubstEnv
forall a. a -> Maybe a
Just CvSubstEnv
subst

  where
    isNotInDomainOf :: VarSet -> VarEnv a -> Bool
    isNotInDomainOf :: VarSet -> VarEnv a -> Bool
isNotInDomainOf set :: VarSet
set env :: VarEnv a
env
      = (TyVar -> Bool) -> VarSet -> Bool
noneSet (\v :: TyVar
v -> TyVar -> VarEnv a -> Bool
forall a. TyVar -> VarEnv a -> Bool
elemVarEnv TyVar
v VarEnv a
env) VarSet
set

    noneSet :: (Var -> Bool) -> VarSet -> Bool
    noneSet :: (TyVar -> Bool) -> VarSet -> Bool
noneSet f :: TyVar -> Bool
f = (TyVar -> Bool) -> VarSet -> Bool
allVarSet (Bool -> Bool
not (Bool -> Bool) -> (TyVar -> Bool) -> TyVar -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyVar -> Bool
f)

ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty :: Type
ty co :: Coercion
co lkco :: Coercion
lkco rkco :: Coercion
rkco
  | CastTy ty' :: Type
ty' co' :: Coercion
co' <- Type
ty
     -- See Note [Matching in the presence of casts]
  = let empty_subst :: TCvSubst
empty_subst  = InScopeSet -> TCvSubst
mkEmptyTCvSubst (RnEnv2 -> InScopeSet
rnInScopeSet (MatchEnv -> RnEnv2
me_env MatchEnv
menv))
        substed_co_l :: Coercion
substed_co_l = HasCallStack => TCvSubst -> Coercion -> Coercion
TCvSubst -> Coercion -> Coercion
substCo (TCvSubst -> CvSubstEnv -> TCvSubst
liftEnvSubstLeft TCvSubst
empty_subst CvSubstEnv
subst)  Coercion
co'
        substed_co_r :: Coercion
substed_co_r = HasCallStack => TCvSubst -> Coercion -> Coercion
TCvSubst -> Coercion -> Coercion
substCo (TCvSubst -> CvSubstEnv -> TCvSubst
liftEnvSubstRight TCvSubst
empty_subst CvSubstEnv
subst) Coercion
co'
    in
    MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ty' Coercion
co (Coercion
substed_co_l Coercion -> Coercion -> Coercion
`mkTransCo` Coercion
lkco)
                                  (Coercion
substed_co_r Coercion -> Coercion -> Coercion
`mkTransCo` Coercion
rkco)

  | SymCo co' :: Coercion
co' <- Coercion
co
  = CvSubstEnv -> CvSubstEnv
swapLiftCoEnv (CvSubstEnv -> CvSubstEnv) -> Maybe CvSubstEnv -> Maybe CvSubstEnv
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv (CvSubstEnv -> CvSubstEnv
swapLiftCoEnv CvSubstEnv
subst) Type
ty Coercion
co' Coercion
rkco Coercion
lkco

  -- Match a type variable against a non-refl coercion
ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst (TyVarTy tv1 :: TyVar
tv1) co :: Coercion
co lkco :: Coercion
lkco rkco :: Coercion
rkco
  | Just co1' :: Coercion
co1' <- CvSubstEnv -> TyVar -> Maybe Coercion
forall a. VarEnv a -> TyVar -> Maybe a
lookupVarEnv CvSubstEnv
subst TyVar
tv1' -- tv1' is already bound to co1
  = if RnEnv2 -> Coercion -> Coercion -> Bool
eqCoercionX (RnEnv2 -> RnEnv2
nukeRnEnvL RnEnv2
rn_env) Coercion
co1' Coercion
co
    then CvSubstEnv -> Maybe CvSubstEnv
forall a. a -> Maybe a
Just CvSubstEnv
subst
    else Maybe CvSubstEnv
forall a. Maybe a
Nothing       -- no match since tv1 matches two different coercions

  | TyVar
tv1' TyVar -> VarSet -> Bool
`elemVarSet` MatchEnv -> VarSet
me_tmpls MatchEnv
menv           -- tv1' is a template var
  = if (TyVar -> Bool) -> [TyVar] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (RnEnv2 -> TyVar -> Bool
inRnEnvR RnEnv2
rn_env) (Coercion -> [TyVar]
tyCoVarsOfCoList Coercion
co)
    then Maybe CvSubstEnv
forall a. Maybe a
Nothing      -- occurs check failed
    else CvSubstEnv -> Maybe CvSubstEnv
forall a. a -> Maybe a
Just (CvSubstEnv -> Maybe CvSubstEnv) -> CvSubstEnv -> Maybe CvSubstEnv
forall a b. (a -> b) -> a -> b
$ CvSubstEnv -> TyVar -> Coercion -> CvSubstEnv
forall a. VarEnv a -> TyVar -> a -> VarEnv a
extendVarEnv CvSubstEnv
subst TyVar
tv1' (Coercion -> CvSubstEnv) -> Coercion -> CvSubstEnv
forall a b. (a -> b) -> a -> b
$
                Coercion -> Coercion -> Coercion -> Coercion
castCoercionKindI Coercion
co (Coercion -> Coercion
mkSymCo Coercion
lkco) (Coercion -> Coercion
mkSymCo Coercion
rkco)

  | Bool
otherwise
  = Maybe CvSubstEnv
forall a. Maybe a
Nothing

  where
    rn_env :: RnEnv2
rn_env = MatchEnv -> RnEnv2
me_env MatchEnv
menv
    tv1' :: TyVar
tv1' = RnEnv2 -> TyVar -> TyVar
rnOccL RnEnv2
rn_env TyVar
tv1

  -- just look through SubCo's. We don't really care about roles here.
ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty :: Type
ty (SubCo co :: Coercion
co) lkco :: Coercion
lkco rkco :: Coercion
rkco
  = MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ty Coercion
co Coercion
lkco Coercion
rkco

ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst (AppTy ty1a :: Type
ty1a ty1b :: Type
ty1b) co :: Coercion
co _lkco :: Coercion
_lkco _rkco :: Coercion
_rkco
  | Just (co2 :: Coercion
co2, arg2 :: Coercion
arg2) <- Coercion -> Maybe (Coercion, Coercion)
splitAppCo_maybe Coercion
co     -- c.f. Unify.match on AppTy
  = MatchEnv
-> CvSubstEnv
-> Type
-> [Type]
-> Coercion
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_app MatchEnv
menv CvSubstEnv
subst Type
ty1a [Type
ty1b] Coercion
co2 [Coercion
arg2]
ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty1 :: Type
ty1 (AppCo co2 :: Coercion
co2 arg2 :: Coercion
arg2) _lkco :: Coercion
_lkco _rkco :: Coercion
_rkco
  | Just (ty1a :: Type
ty1a, ty1b :: Type
ty1b) <- HasDebugCallStack => Type -> Maybe (Type, Type)
Type -> Maybe (Type, Type)
repSplitAppTy_maybe Type
ty1
       -- yes, the one from Type, not TcType; this is for coercion optimization
  = MatchEnv
-> CvSubstEnv
-> Type
-> [Type]
-> Coercion
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_app MatchEnv
menv CvSubstEnv
subst Type
ty1a [Type
ty1b] Coercion
co2 [Coercion
arg2]

ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst (TyConApp tc1 :: TyCon
tc1 tys :: [Type]
tys) (TyConAppCo _ tc2 :: TyCon
tc2 cos :: [Coercion]
cos) _lkco :: Coercion
_lkco _rkco :: Coercion
_rkco
  = MatchEnv
-> CvSubstEnv
-> TyCon
-> [Type]
-> TyCon
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_tc MatchEnv
menv CvSubstEnv
subst TyCon
tc1 [Type]
tys TyCon
tc2 [Coercion]
cos
ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst (FunTy ty1 :: Type
ty1 ty2 :: Type
ty2) co :: Coercion
co _lkco :: Coercion
_lkco _rkco :: Coercion
_rkco
    -- Despite the fact that (->) is polymorphic in four type variables (two
    -- runtime rep and two types), we shouldn't need to explicitly unify the
    -- runtime reps here; unifying the types themselves should be sufficient.
    -- See Note [Representation of function types].
  | Just (tc :: TyCon
tc, [_,_,co1 :: Coercion
co1,co2 :: Coercion
co2]) <- Coercion -> Maybe (TyCon, [Coercion])
splitTyConAppCo_maybe Coercion
co
  , TyCon
tc TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
funTyCon
  = let Pair lkcos :: [Coercion]
lkcos rkcos :: [Coercion]
rkcos = (Coercion -> Pair Coercion) -> [Coercion] -> Pair [Coercion]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse ((Type -> Coercion) -> Pair Type -> Pair Coercion
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Type -> Coercion
mkNomReflCo (Pair Type -> Pair Coercion)
-> (Coercion -> Pair Type) -> Coercion -> Pair Coercion
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Coercion -> Pair Type
coercionKind) [Coercion
co1,Coercion
co2]
    in MatchEnv
-> CvSubstEnv
-> [Type]
-> [Coercion]
-> [Coercion]
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_args MatchEnv
menv CvSubstEnv
subst [Type
ty1, Type
ty2] [Coercion
co1, Coercion
co2] [Coercion]
lkcos [Coercion]
rkcos

ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst (ForAllTy (Bndr tv1 :: TyVar
tv1 _) ty1 :: Type
ty1)
                       (ForAllCo tv2 :: TyVar
tv2 kind_co2 :: Coercion
kind_co2 co2 :: Coercion
co2)
                       lkco :: Coercion
lkco rkco :: Coercion
rkco
  | TyVar -> Bool
isTyVar TyVar
tv1 Bool -> Bool -> Bool
&& TyVar -> Bool
isTyVar TyVar
tv2
  = do { CvSubstEnv
subst1 <- MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst (TyVar -> Type
tyVarKind TyVar
tv1) Coercion
kind_co2
                               Coercion
ki_ki_co Coercion
ki_ki_co
       ; let rn_env0 :: RnEnv2
rn_env0 = MatchEnv -> RnEnv2
me_env MatchEnv
menv
             rn_env1 :: RnEnv2
rn_env1 = RnEnv2 -> TyVar -> TyVar -> RnEnv2
rnBndr2 RnEnv2
rn_env0 TyVar
tv1 TyVar
tv2
             menv' :: MatchEnv
menv'   = MatchEnv
menv { me_env :: RnEnv2
me_env = RnEnv2
rn_env1 }
       ; MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv' CvSubstEnv
subst1 Type
ty1 Coercion
co2 Coercion
lkco Coercion
rkco }
  where
    ki_ki_co :: Coercion
ki_ki_co = Type -> Coercion
mkNomReflCo Type
liftedTypeKind

-- ty_co_match menv subst (ForAllTy (Bndr cv1 _) ty1)
--                        (ForAllCo cv2 kind_co2 co2)
--                        lkco rkco
--   | isCoVar cv1 && isCoVar cv2
--   We seems not to have enough information for this case
--   1. Given:
--        cv1      :: (s1 :: k1) ~r (s2 :: k2)
--        kind_co2 :: (s1' ~ s2') ~N (t1 ~ t2)
--        eta1      = mkNthCo role 2 (downgradeRole r Nominal kind_co2)
--                 :: s1' ~ t1
--        eta2      = mkNthCo role 3 (downgradeRole r Nominal kind_co2)
--                 :: s2' ~ t2
--      Wanted:
--        subst1 <- ty_co_match menv subst  s1 eta1 kco1 kco2
--        subst2 <- ty_co_match menv subst1 s2 eta2 kco3 kco4
--      Question: How do we get kcoi?
--   2. Given:
--        lkco :: <*>    -- See Note [Weird typing rule for ForAllTy] in Type
--        rkco :: <*>
--      Wanted:
--        ty_co_match menv' subst2 ty1 co2 lkco' rkco'
--      Question: How do we get lkco' and rkco'?

ty_co_match _ subst :: CvSubstEnv
subst (CoercionTy {}) _ _ _
  = CvSubstEnv -> Maybe CvSubstEnv
forall a. a -> Maybe a
Just CvSubstEnv
subst -- don't inspect coercions

ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty :: Type
ty (GRefl r :: Role
r t :: Type
t (MCo co :: Coercion
co)) lkco :: Coercion
lkco rkco :: Coercion
rkco
  =  MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ty (Role -> Type -> MCoercion -> Coercion
GRefl Role
r Type
t MCoercion
MRefl) Coercion
lkco (Coercion
rkco Coercion -> Coercion -> Coercion
`mkTransCo` Coercion -> Coercion
mkSymCo Coercion
co)

ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty :: Type
ty co1 :: Coercion
co1 lkco :: Coercion
lkco rkco :: Coercion
rkco
  | Just (CastTy t :: Type
t co :: Coercion
co, r :: Role
r) <- Coercion -> Maybe (Type, Role)
isReflCo_maybe Coercion
co1
  -- In @pushRefl@, pushing reflexive coercion inside CastTy will give us
  -- t |> co ~ t ; <t> ; t ~ t |> co
  -- But transitive coercions are not helpful. Therefore we deal
  -- with it here: we do recursion on the smaller reflexive coercion,
  -- while propagating the correct kind coercions.
  = let kco' :: Coercion
kco' = Coercion -> Coercion
mkSymCo Coercion
co
    in MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ty (Role -> Type -> Coercion
mkReflCo Role
r Type
t) (Coercion
lkco Coercion -> Coercion -> Coercion
`mkTransCo` Coercion
kco')
                                                (Coercion
rkco Coercion -> Coercion -> Coercion
`mkTransCo` Coercion
kco')


ty_co_match menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty :: Type
ty co :: Coercion
co lkco :: Coercion
lkco rkco :: Coercion
rkco
  | Just co' :: Coercion
co' <- Coercion -> Maybe Coercion
pushRefl Coercion
co = MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ty Coercion
co' Coercion
lkco Coercion
rkco
  | Bool
otherwise               = Maybe CvSubstEnv
forall a. Maybe a
Nothing

ty_co_match_tc :: MatchEnv -> LiftCoEnv
               -> TyCon -> [Type]
               -> TyCon -> [Coercion]
               -> Maybe LiftCoEnv
ty_co_match_tc :: MatchEnv
-> CvSubstEnv
-> TyCon
-> [Type]
-> TyCon
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_tc menv :: MatchEnv
menv subst :: CvSubstEnv
subst tc1 :: TyCon
tc1 tys1 :: [Type]
tys1 tc2 :: TyCon
tc2 cos2 :: [Coercion]
cos2
  = do { Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (TyCon
tc1 TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tc2)
       ; MatchEnv
-> CvSubstEnv
-> [Type]
-> [Coercion]
-> [Coercion]
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_args MatchEnv
menv CvSubstEnv
subst [Type]
tys1 [Coercion]
cos2 [Coercion]
lkcos [Coercion]
rkcos }
  where
    Pair lkcos :: [Coercion]
lkcos rkcos :: [Coercion]
rkcos
      = (Coercion -> Pair Coercion) -> [Coercion] -> Pair [Coercion]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse ((Type -> Coercion) -> Pair Type -> Pair Coercion
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Type -> Coercion
mkNomReflCo (Pair Type -> Pair Coercion)
-> (Coercion -> Pair Type) -> Coercion -> Pair Coercion
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Coercion -> Pair Type
coercionKind) [Coercion]
cos2

ty_co_match_app :: MatchEnv -> LiftCoEnv
                -> Type -> [Type] -> Coercion -> [Coercion]
                -> Maybe LiftCoEnv
ty_co_match_app :: MatchEnv
-> CvSubstEnv
-> Type
-> [Type]
-> Coercion
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_app menv :: MatchEnv
menv subst :: CvSubstEnv
subst ty1 :: Type
ty1 ty1args :: [Type]
ty1args co2 :: Coercion
co2 co2args :: [Coercion]
co2args
  | Just (ty1' :: Type
ty1', ty1a :: Type
ty1a) <- HasDebugCallStack => Type -> Maybe (Type, Type)
Type -> Maybe (Type, Type)
repSplitAppTy_maybe Type
ty1
  , Just (co2' :: Coercion
co2', co2a :: Coercion
co2a) <- Coercion -> Maybe (Coercion, Coercion)
splitAppCo_maybe Coercion
co2
  = MatchEnv
-> CvSubstEnv
-> Type
-> [Type]
-> Coercion
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_app MatchEnv
menv CvSubstEnv
subst Type
ty1' (Type
ty1a Type -> [Type] -> [Type]
forall a. a -> [a] -> [a]
: [Type]
ty1args) Coercion
co2' (Coercion
co2a Coercion -> [Coercion] -> [Coercion]
forall a. a -> [a] -> [a]
: [Coercion]
co2args)

  | Bool
otherwise
  = do { CvSubstEnv
subst1 <- MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ki1 Coercion
ki2 Coercion
ki_ki_co Coercion
ki_ki_co
       ; let Pair lkco :: Coercion
lkco rkco :: Coercion
rkco = Type -> Coercion
mkNomReflCo (Type -> Coercion) -> Pair Type -> Pair Coercion
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Coercion -> Pair Type
coercionKind Coercion
ki2
       ; CvSubstEnv
subst2 <- MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst1 Type
ty1 Coercion
co2 Coercion
lkco Coercion
rkco
       ; let Pair lkcos :: [Coercion]
lkcos rkcos :: [Coercion]
rkcos = (Coercion -> Pair Coercion) -> [Coercion] -> Pair [Coercion]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse ((Type -> Coercion) -> Pair Type -> Pair Coercion
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Type -> Coercion
mkNomReflCo (Pair Type -> Pair Coercion)
-> (Coercion -> Pair Type) -> Coercion -> Pair Coercion
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Coercion -> Pair Type
coercionKind) [Coercion]
co2args
       ; MatchEnv
-> CvSubstEnv
-> [Type]
-> [Coercion]
-> [Coercion]
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_args MatchEnv
menv CvSubstEnv
subst2 [Type]
ty1args [Coercion]
co2args [Coercion]
lkcos [Coercion]
rkcos }
  where
    ki1 :: Type
ki1 = HasDebugCallStack => Type -> Type
Type -> Type
typeKind Type
ty1
    ki2 :: Coercion
ki2 = Coercion -> Coercion
promoteCoercion Coercion
co2
    ki_ki_co :: Coercion
ki_ki_co = Type -> Coercion
mkNomReflCo Type
liftedTypeKind

ty_co_match_args :: MatchEnv -> LiftCoEnv -> [Type]
                 -> [Coercion] -> [Coercion] -> [Coercion]
                 -> Maybe LiftCoEnv
ty_co_match_args :: MatchEnv
-> CvSubstEnv
-> [Type]
-> [Coercion]
-> [Coercion]
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_args _    subst :: CvSubstEnv
subst []       []         _ _ = CvSubstEnv -> Maybe CvSubstEnv
forall a. a -> Maybe a
Just CvSubstEnv
subst
ty_co_match_args menv :: MatchEnv
menv subst :: CvSubstEnv
subst (ty :: Type
ty:tys :: [Type]
tys) (arg :: Coercion
arg:args :: [Coercion]
args) (lkco :: Coercion
lkco:lkcos :: [Coercion]
lkcos) (rkco :: Coercion
rkco:rkcos :: [Coercion]
rkcos)
  = do { CvSubstEnv
subst' <- MatchEnv
-> CvSubstEnv
-> Type
-> Coercion
-> Coercion
-> Coercion
-> Maybe CvSubstEnv
ty_co_match MatchEnv
menv CvSubstEnv
subst Type
ty Coercion
arg Coercion
lkco Coercion
rkco
       ; MatchEnv
-> CvSubstEnv
-> [Type]
-> [Coercion]
-> [Coercion]
-> [Coercion]
-> Maybe CvSubstEnv
ty_co_match_args MatchEnv
menv CvSubstEnv
subst' [Type]
tys [Coercion]
args [Coercion]
lkcos [Coercion]
rkcos }
ty_co_match_args _    _     _        _          _ _ = Maybe CvSubstEnv
forall a. Maybe a
Nothing

pushRefl :: Coercion -> Maybe Coercion
pushRefl :: Coercion -> Maybe Coercion
pushRefl co :: Coercion
co =
  case (Coercion -> Maybe (Type, Role)
isReflCo_maybe Coercion
co) of
    Just (AppTy ty1 :: Type
ty1 ty2 :: Type
ty2, Nominal)
      -> Coercion -> Maybe Coercion
forall a. a -> Maybe a
Just (Coercion -> Coercion -> Coercion
AppCo (Role -> Type -> Coercion
mkReflCo Role
Nominal Type
ty1) (Type -> Coercion
mkNomReflCo Type
ty2))
    Just (FunTy ty1 :: Type
ty1 ty2 :: Type
ty2, r :: Role
r)
      | Just rep1 :: Type
rep1 <- HasDebugCallStack => Type -> Maybe Type
Type -> Maybe Type
getRuntimeRep_maybe Type
ty1
      , Just rep2 :: Type
rep2 <- HasDebugCallStack => Type -> Maybe Type
Type -> Maybe Type
getRuntimeRep_maybe Type
ty2
      ->  Coercion -> Maybe Coercion
forall a. a -> Maybe a
Just (Role -> TyCon -> [Coercion] -> Coercion
TyConAppCo Role
r TyCon
funTyCon [ Role -> Type -> Coercion
mkReflCo Role
r Type
rep1, Role -> Type -> Coercion
mkReflCo Role
r Type
rep2
                                       , Role -> Type -> Coercion
mkReflCo Role
r Type
ty1,  Role -> Type -> Coercion
mkReflCo Role
r Type
ty2 ])
    Just (TyConApp tc :: TyCon
tc tys :: [Type]
tys, r :: Role
r)
      -> Coercion -> Maybe Coercion
forall a. a -> Maybe a
Just (Role -> TyCon -> [Coercion] -> Coercion
TyConAppCo Role
r TyCon
tc ((Role -> Type -> Coercion) -> [Role] -> [Type] -> [Coercion]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Role -> Type -> Coercion
mkReflCo (Role -> TyCon -> [Role]
tyConRolesX Role
r TyCon
tc) [Type]
tys))
    Just (ForAllTy (Bndr tv :: TyVar
tv _) ty :: Type
ty, r :: Role
r)
      -> Coercion -> Maybe Coercion
forall a. a -> Maybe a
Just (TyVar -> Coercion -> Coercion -> Coercion
ForAllCo TyVar
tv (Type -> Coercion
mkNomReflCo (TyVar -> Type
varType TyVar
tv)) (Role -> Type -> Coercion
mkReflCo Role
r Type
ty))
    -- NB: NoRefl variant. Otherwise, we get a loop!
    _ -> Maybe Coercion
forall a. Maybe a
Nothing