{-
Authors: George Karachalias <george.karachalias@cs.kuleuven.be>
         Sebastian Graf <sgraf1337@gmail.com>
         Ryan Scott <ryan.gl.scott@gmail.com>
-}

{-# LANGUAGE CPP, LambdaCase, TupleSections, PatternSynonyms, ViewPatterns, MultiWayIf #-}

-- | The pattern match oracle. The main export of the module are the functions
-- 'addTmCt', 'addVarCoreCt', 'addRefutableAltCon' and 'addTypeEvidence' for
-- adding facts to the oracle, and 'provideEvidence' to turn a
-- 'Delta' into a concrete evidence for an equation.
module GHC.HsToCore.PmCheck.Oracle (

        DsM, tracePm, mkPmId,
        Delta, initDelta, lookupRefuts, lookupSolution,

        TmCt(..),
        addTypeEvidence,    -- Add type equalities
        addRefutableAltCon, -- Add a negative term equality
        addTmCt,            -- Add a positive term equality x ~ e
        addVarCoreCt,       -- Add a positive term equality x ~ core_expr
        canDiverge,         -- Try to add the term equality x ~ ⊥
        provideEvidence,
    ) where

#include "HsVersions.h"

import GhcPrelude

import GHC.HsToCore.PmCheck.Types

import DynFlags
import Outputable
import ErrUtils
import Util
import Bag
import UniqSet
import UniqDSet
import Unique
import Id
import VarEnv
import UniqDFM
import Var           (EvVar)
import Name
import CoreSyn
import CoreFVs ( exprFreeVars )
import CoreMap
import CoreOpt (simpleOptExpr, exprIsConApp_maybe)
import CoreUtils (exprType)
import MkCore (mkListExpr, mkCharExpr)
import UniqSupply
import FastString
import SrcLoc
import ListSetOps (unionLists)
import Maybes
import ConLike
import DataCon
import PatSyn
import TyCon
import TysWiredIn
import TysPrim (tYPETyCon)
import TyCoRep
import Type
import TcSimplify    (tcNormalise, tcCheckSatisfiability)
import TcType        (evVarPred)
import Unify         (tcMatchTy)
import TcRnTypes     (completeMatchConLikes)
import Coercion
import MonadUtils hiding (foldlM)
import DsMonad hiding (foldlM)
import FamInst
import FamInstEnv

import Control.Monad (guard, mzero)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.State.Strict
import Data.Bifunctor (second)
import Data.Foldable (foldlM, minimumBy)
import Data.List     (find)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Ord      (comparing)
import qualified Data.Semigroup as Semigroup
import Data.Tuple    (swap)

-- Debugging Infrastructre

tracePm :: String -> SDoc -> DsM ()
tracePm :: String -> SDoc -> DsM ()
tracePm String
herald SDoc
doc = do
  DynFlags
dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  PrintUnqualified
printer <- DsM PrintUnqualified
mkPrintUnqualifiedDs
  IO () -> DsM ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> DsM ()) -> IO () -> DsM ()
forall a b. (a -> b) -> a -> b
$ PrintUnqualified -> DynFlags -> DumpFlag -> SDoc -> IO ()
dumpIfSet_dyn_printer PrintUnqualified
printer DynFlags
dflags
            DumpFlag
Opt_D_dump_ec_trace (String -> SDoc
text String
herald SDoc -> SDoc -> SDoc
$$ (Int -> SDoc -> SDoc
nest Int
2 SDoc
doc))

-- | Generate a fresh `Id` of a given type
mkPmId :: Type -> DsM Id
mkPmId :: Type -> DsM Id
mkPmId Type
ty = IOEnv (Env DsGblEnv DsLclEnv) Unique
forall (m :: * -> *). MonadUnique m => m Unique
getUniqueM IOEnv (Env DsGblEnv DsLclEnv) Unique
-> (Unique -> DsM Id) -> DsM Id
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Unique
unique ->
  let occname :: OccName
occname = FastString -> OccName
mkVarOccFS (FastString -> OccName) -> FastString -> OccName
forall a b. (a -> b) -> a -> b
$ String -> FastString
fsLit String
"pm"
      name :: Name
name    = Unique -> OccName -> SrcSpan -> Name
mkInternalName Unique
unique OccName
occname SrcSpan
noSrcSpan
  in  Id -> DsM Id
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Id
mkLocalId Name
name Type
ty)

-----------------------------------------------
-- * Caching possible matches of a COMPLETE set

markMatched :: ConLike -> PossibleMatches -> PossibleMatches
markMatched :: ConLike -> PossibleMatches -> PossibleMatches
markMatched ConLike
_   PossibleMatches
NoPM    = PossibleMatches
NoPM
markMatched ConLike
con (PM NonEmpty ConLikeSet
ms) = NonEmpty ConLikeSet -> PossibleMatches
PM (ConLike -> ConLikeSet -> ConLikeSet
del_one_con ConLike
con (ConLikeSet -> ConLikeSet)
-> NonEmpty ConLikeSet -> NonEmpty ConLikeSet
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> NonEmpty ConLikeSet
ms)
  where
    del_one_con :: ConLike -> ConLikeSet -> ConLikeSet
del_one_con = (ConLikeSet -> ConLike -> ConLikeSet)
-> ConLike -> ConLikeSet -> ConLikeSet
forall a b c. (a -> b -> c) -> b -> a -> c
flip ConLikeSet -> ConLike -> ConLikeSet
forall a. Uniquable a => UniqDSet a -> a -> UniqDSet a
delOneFromUniqDSet

---------------------------------------------------
-- * Instantiating constructors, types and evidence

-- | Instantiate a 'ConLike' given its universal type arguments. Instantiates
-- existential and term binders with fresh variables of appropriate type.
-- Returns instantiated term variables from the match, type evidence and the
-- types of strict constructor fields.
mkOneConFull :: [Type] -> ConLike -> DsM ([Id], Bag TyCt, [Type])
--  * 'con' K is a ConLike
--       - In the case of DataCons and most PatSynCons, these
--         are associated with a particular TyCon T
--       - But there are PatSynCons for this is not the case! See #11336, #17112
--
--  * 'arg_tys' tys are the types K's universally quantified type
--     variables should be instantiated to.
--       - For DataCons and most PatSyns these are the arguments of their TyCon
--       - For cases like the PatSyns in #11336, #17112, we can't easily guess
--         these, so don't call this function.
--
-- After instantiating the universal tyvars of K to tys we get
--          K @tys :: forall bs. Q => s1 .. sn -> T tys
-- Note that if K is a PatSynCon, depending on arg_tys, T might not necessarily
-- be a concrete TyCon.
--
-- Suppose y1 is a strict field. Then we get
-- Results: [y1,..,yn]
--          Q
--          [s1]
mkOneConFull :: [Type] -> ConLike -> DsM ([Id], Bag TyCt, [Type])
mkOneConFull [Type]
arg_tys ConLike
con = do
  let ([Id]
univ_tvs, [Id]
ex_tvs, [EqSpec]
eq_spec, [Type]
thetas, [Type]
_req_theta , [Type]
field_tys, Type
_con_res_ty)
        = ConLike -> ([Id], [Id], [EqSpec], [Type], [Type], [Type], Type)
conLikeFullSig ConLike
con
  -- pprTrace "mkOneConFull" (ppr con $$ ppr arg_tys $$ ppr univ_tvs $$ ppr _con_res_ty) (return ())
  -- Substitute universals for type arguments
  let subst_univ :: TCvSubst
subst_univ = [Id] -> [Type] -> TCvSubst
HasDebugCallStack => [Id] -> [Type] -> TCvSubst
zipTvSubst [Id]
univ_tvs [Type]
arg_tys
  -- Instantiate fresh existentials as arguments to the contructor. This is
  -- important for instantiating the Thetas and field types.
  (TCvSubst
subst, [Id]
_) <- TCvSubst -> [Id] -> UniqSupply -> (TCvSubst, [Id])
cloneTyVarBndrs TCvSubst
subst_univ [Id]
ex_tvs (UniqSupply -> (TCvSubst, [Id]))
-> IOEnv (Env DsGblEnv DsLclEnv) UniqSupply
-> IOEnv (Env DsGblEnv DsLclEnv) (TCvSubst, [Id])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IOEnv (Env DsGblEnv DsLclEnv) UniqSupply
forall (m :: * -> *). MonadUnique m => m UniqSupply
getUniqueSupplyM
  let field_tys' :: [Type]
field_tys' = HasCallStack => TCvSubst -> [Type] -> [Type]
TCvSubst -> [Type] -> [Type]
substTys TCvSubst
subst [Type]
field_tys
  -- Instantiate fresh term variables (VAs) as arguments to the constructor
  [Id]
vars <- (Type -> DsM Id) -> [Type] -> IOEnv (Env DsGblEnv DsLclEnv) [Id]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Type -> DsM Id
mkPmId [Type]
field_tys'
  -- All constraints bound by the constructor (alpha-renamed), these are added
  -- to the type oracle
  let ty_cs :: [TyCt]
ty_cs = (Type -> TyCt) -> [Type] -> [TyCt]
forall a b. (a -> b) -> [a] -> [b]
map Type -> TyCt
TyCt (HasCallStack => TCvSubst -> [Type] -> [Type]
TCvSubst -> [Type] -> [Type]
substTheta TCvSubst
subst ([EqSpec] -> [Type]
eqSpecPreds [EqSpec]
eq_spec [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
thetas))
  -- Figure out the types of strict constructor fields
  let arg_is_strict :: [Bool]
arg_is_strict
        | RealDataCon DataCon
dc <- ConLike
con
        , TyCon -> Bool
isNewTyCon (DataCon -> TyCon
dataConTyCon DataCon
dc)
        = [Bool
True] -- See Note [Divergence of Newtype matches]
        | Bool
otherwise
        = (HsImplBang -> Bool) -> [HsImplBang] -> [Bool]
forall a b. (a -> b) -> [a] -> [b]
map HsImplBang -> Bool
isBanged ([HsImplBang] -> [Bool]) -> [HsImplBang] -> [Bool]
forall a b. (a -> b) -> a -> b
$ ConLike -> [HsImplBang]
conLikeImplBangs ConLike
con
      strict_arg_tys :: [Type]
strict_arg_tys = [Bool] -> [Type] -> [Type]
forall a. [Bool] -> [a] -> [a]
filterByList [Bool]
arg_is_strict [Type]
field_tys'
  ([Id], Bag TyCt, [Type]) -> DsM ([Id], Bag TyCt, [Type])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Id]
vars, [TyCt] -> Bag TyCt
forall a. [a] -> Bag a
listToBag [TyCt]
ty_cs, [Type]
strict_arg_tys)

-------------------------
-- * Pattern match oracle


{- Note [Recovering from unsatisfiable pattern-matching constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following code (see #12957 and #15450):

  f :: Int ~ Bool => ()
  f = case True of { False -> () }

We want to warn that the pattern-matching in `f` is non-exhaustive. But GHC
used not to do this; in fact, it would warn that the match was /redundant/!
This is because the constraint (Int ~ Bool) in `f` is unsatisfiable, and the
coverage checker deems any matches with unsatifiable constraint sets to be
unreachable.

We decide to better than this. When beginning coverage checking, we first
check if the constraints in scope are unsatisfiable, and if so, we start
afresh with an empty set of constraints. This way, we'll get the warnings
that we expect.
-}

-------------------------------------
-- * Composable satisfiability checks

-- | Given a 'Delta', check if it is compatible with new facts encoded in this
-- this check. If so, return 'Just' a potentially extended 'Delta'. Return
-- 'Nothing' if unsatisfiable.
--
-- There are three essential SatisfiabilityChecks:
--   1. 'tmIsSatisfiable', adding term oracle facts
--   2. 'tyIsSatisfiable', adding type oracle facts
--   3. 'tysAreNonVoid', checks if the given types have an inhabitant
-- Functions like 'pmIsSatisfiable', 'nonVoid' and 'testInhabited' plug these
-- together as they see fit.
newtype SatisfiabilityCheck = SC (Delta -> DsM (Maybe Delta))

-- | Check the given 'Delta' for satisfiability by the the given
-- 'SatisfiabilityCheck'. Return 'Just' a new, potentially extended, 'Delta' if
-- successful, and 'Nothing' otherwise.
runSatisfiabilityCheck :: Delta -> SatisfiabilityCheck -> DsM (Maybe Delta)
runSatisfiabilityCheck :: Delta -> SatisfiabilityCheck -> DsM (Maybe Delta)
runSatisfiabilityCheck Delta
delta (SC Delta -> DsM (Maybe Delta)
chk) = Delta -> DsM (Maybe Delta)
chk Delta
delta

-- | Allowing easy composition of 'SatisfiabilityCheck's.
instance Semigroup SatisfiabilityCheck where
  -- This is @a >=> b@ from MaybeT DsM
  SC Delta -> DsM (Maybe Delta)
a <> :: SatisfiabilityCheck -> SatisfiabilityCheck -> SatisfiabilityCheck
<> SC Delta -> DsM (Maybe Delta)
b = (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
SC Delta -> DsM (Maybe Delta)
c
    where
      c :: Delta -> DsM (Maybe Delta)
c Delta
delta = Delta -> DsM (Maybe Delta)
a Delta
delta DsM (Maybe Delta)
-> (Maybe Delta -> DsM (Maybe Delta)) -> DsM (Maybe Delta)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Maybe Delta
Nothing     -> Maybe Delta -> DsM (Maybe Delta)
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Delta
forall a. Maybe a
Nothing
        Just Delta
delta' -> Delta -> DsM (Maybe Delta)
b Delta
delta'

instance Monoid SatisfiabilityCheck where
  -- We only need this because of mconcat (which we use in place of sconcat,
  -- which requires NonEmpty lists as argument, making all call sites ugly)
  mempty :: SatisfiabilityCheck
mempty = (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
SC (Maybe Delta -> DsM (Maybe Delta)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Delta -> DsM (Maybe Delta))
-> (Delta -> Maybe Delta) -> Delta -> DsM (Maybe Delta)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Delta -> Maybe Delta
forall a. a -> Maybe a
Just)

-------------------------------
-- * Oracle transition function

-- | Given a conlike's term constraints, type constraints, and strict argument
-- types, check if they are satisfiable.
-- (In other words, this is the ⊢_Sat oracle judgment from the GADTs Meet
-- Their Match paper.)
--
-- Taking strict argument types into account is something which was not
-- discussed in GADTs Meet Their Match. For an explanation of what role they
-- serve, see @Note [Strict argument type constraints]@.
pmIsSatisfiable
  :: Delta       -- ^ The ambient term and type constraints
                 --   (known to be satisfiable).
  -> Bag TmCt    -- ^ The new term constraints.
  -> Bag TyCt    -- ^ The new type constraints.
  -> [Type]      -- ^ The strict argument types.
  -> DsM (Maybe Delta)
                 -- ^ @'Just' delta@ if the constraints (@delta@) are
                 -- satisfiable, and each strict argument type is inhabitable.
                 -- 'Nothing' otherwise.
pmIsSatisfiable :: Delta -> Bag TmCt -> Bag TyCt -> [Type] -> DsM (Maybe Delta)
pmIsSatisfiable Delta
amb_cs Bag TmCt
new_tm_cs Bag TyCt
new_ty_cs [Type]
strict_arg_tys =
  -- The order is important here! Check the new type constraints before we check
  -- whether strict argument types are inhabited given those constraints.
  Delta -> SatisfiabilityCheck -> DsM (Maybe Delta)
runSatisfiabilityCheck Delta
amb_cs (SatisfiabilityCheck -> DsM (Maybe Delta))
-> SatisfiabilityCheck -> DsM (Maybe Delta)
forall a b. (a -> b) -> a -> b
$ [SatisfiabilityCheck] -> SatisfiabilityCheck
forall a. Monoid a => [a] -> a
mconcat
    [ Bool -> Bag TyCt -> SatisfiabilityCheck
tyIsSatisfiable Bool
True Bag TyCt
new_ty_cs
    , Bag TmCt -> SatisfiabilityCheck
tmIsSatisfiable Bag TmCt
new_tm_cs
    , RecTcChecker -> [Type] -> SatisfiabilityCheck
tysAreNonVoid RecTcChecker
initRecTc [Type]
strict_arg_tys
    ]

-----------------------
-- * Type normalisation

-- | The return value of 'pmTopNormaliseType'
data TopNormaliseTypeResult
  = NoChange Type
  -- ^ 'tcNormalise' failed to simplify the type and 'topNormaliseTypeX' was
  -- unable to reduce the outermost type application, so the type came out
  -- unchanged.
  | NormalisedByConstraints Type
  -- ^ 'tcNormalise' was able to simplify the type with some local constraint
  -- from the type oracle, but 'topNormaliseTypeX' couldn't identify a type
  -- redex.
  | HadRedexes Type [(Type, DataCon, Type)] Type
  -- ^ 'tcNormalise' may or may not been able to simplify the type, but
  -- 'topNormaliseTypeX' made progress either way and got rid of at least one
  -- outermost type or data family redex or newtype.
  -- The first field is the last type that was reduced solely through type
  -- family applications (possibly just the 'tcNormalise'd type). This is the
  -- one that is equal (in source Haskell) to the initial type.
  -- The third field is the type that we get when also looking through data
  -- family applications and newtypes. This would be the representation type in
  -- Core (modulo casts).
  -- The second field is the list of Newtype 'DataCon's that we looked through
  -- in the chain of reduction steps between the Source type and the Core type.
  -- We also keep the type of the DataCon application and its field, so that we
  -- don't have to reconstruct it in 'inhabitationCandidates' and
  -- 'provideEvidence'.
  -- For an example, see Note [Type normalisation].

-- | Just give me the potentially normalised source type, unchanged or not!
normalisedSourceType :: TopNormaliseTypeResult -> Type
normalisedSourceType :: TopNormaliseTypeResult -> Type
normalisedSourceType (NoChange Type
ty)                = Type
ty
normalisedSourceType (NormalisedByConstraints Type
ty) = Type
ty
normalisedSourceType (HadRedexes Type
ty [(Type, DataCon, Type)]
_ Type
_)          = Type
ty

-- | Return the fields of 'HadRedexes'. Returns appropriate defaults in the
-- other cases.
tntrGuts :: TopNormaliseTypeResult -> (Type, [(Type, DataCon, Type)], Type)
tntrGuts :: TopNormaliseTypeResult -> (Type, [(Type, DataCon, Type)], Type)
tntrGuts (NoChange Type
ty)                  = (Type
ty,     [],      Type
ty)
tntrGuts (NormalisedByConstraints Type
ty)   = (Type
ty,     [],      Type
ty)
tntrGuts (HadRedexes Type
src_ty [(Type, DataCon, Type)]
ds Type
core_ty) = (Type
src_ty, [(Type, DataCon, Type)]
ds, Type
core_ty)

instance Outputable TopNormaliseTypeResult where
  ppr :: TopNormaliseTypeResult -> SDoc
ppr (NoChange Type
ty)                  = String -> SDoc
text String
"NoChange" SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty
  ppr (NormalisedByConstraints Type
ty)   = String -> SDoc
text String
"NormalisedByConstraints" SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty
  ppr (HadRedexes Type
src_ty [(Type, DataCon, Type)]
ds Type
core_ty) = String -> SDoc
text String
"HadRedexes" SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
braces SDoc
fields
    where
      fields :: SDoc
fields = [SDoc] -> SDoc
fsep (SDoc -> [SDoc] -> [SDoc]
punctuate SDoc
comma [ String -> SDoc
text String
"src_ty =" SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
src_ty
                                     , String -> SDoc
text String
"newtype_dcs =" SDoc -> SDoc -> SDoc
<+> [(Type, DataCon, Type)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Type, DataCon, Type)]
ds
                                     , String -> SDoc
text String
"core_ty =" SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
core_ty ])

pmTopNormaliseType :: TyState -> Type -> DsM TopNormaliseTypeResult
-- ^ Get rid of *outermost* (or toplevel)
--      * type function redex
--      * data family redex
--      * newtypes
--
-- Behaves like `topNormaliseType_maybe`, but instead of returning a
-- coercion, it returns useful information for issuing pattern matching
-- warnings. See Note [Type normalisation] for details.
-- It also initially 'tcNormalise's the type with the bag of local constraints.
--
-- See 'TopNormaliseTypeResult' for the meaning of the return value.
--
-- NB: Normalisation can potentially change kinds, if the head of the type
-- is a type family with a variable result kind. I (Richard E) can't think
-- of a way to cause trouble here, though.
pmTopNormaliseType :: TyState -> Type -> DsM TopNormaliseTypeResult
pmTopNormaliseType (TySt Bag Id
inert) Type
typ
  = do FamInstEnvs
env <- DsM FamInstEnvs
dsGetFamInstEnvs
       -- Before proceeding, we chuck typ into the constraint solver, in case
       -- solving for given equalities may reduce typ some. See
       -- "Wrinkle: local equalities" in Note [Type normalisation].
       (Messages
_, Maybe Type
mb_typ') <- TcM Type -> DsM (Messages, Maybe Type)
forall a. TcM a -> DsM (Messages, Maybe a)
initTcDsForSolver (TcM Type -> DsM (Messages, Maybe Type))
-> TcM Type -> DsM (Messages, Maybe Type)
forall a b. (a -> b) -> a -> b
$ Bag Id -> Type -> TcM Type
tcNormalise Bag Id
inert Type
typ
       -- If tcNormalise didn't manage to simplify the type, continue anyway.
       -- We might be able to reduce type applications nonetheless!
       let typ' :: Type
typ' = Type -> Maybe Type -> Type
forall a. a -> Maybe a -> a
fromMaybe Type
typ Maybe Type
mb_typ'
       -- Now we look with topNormaliseTypeX through type and data family
       -- applications and newtypes, which tcNormalise does not do.
       -- See also 'TopNormaliseTypeResult'.
       TopNormaliseTypeResult -> DsM TopNormaliseTypeResult
forall (f :: * -> *) a. Applicative f => a -> f a
pure (TopNormaliseTypeResult -> DsM TopNormaliseTypeResult)
-> TopNormaliseTypeResult -> DsM TopNormaliseTypeResult
forall a b. (a -> b) -> a -> b
$ case NormaliseStepper
  ([Type] -> [Type],
   [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
-> (([Type] -> [Type],
     [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
    -> ([Type] -> [Type],
        [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
    -> ([Type] -> [Type],
        [(Type, DataCon, Type)] -> [(Type, DataCon, Type)]))
-> Type
-> Maybe
     (([Type] -> [Type],
       [(Type, DataCon, Type)] -> [(Type, DataCon, Type)]),
      Type)
forall ev.
NormaliseStepper ev -> (ev -> ev -> ev) -> Type -> Maybe (ev, Type)
topNormaliseTypeX (FamInstEnvs
-> NormaliseStepper
     ([Type] -> [Type],
      [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
stepper FamInstEnvs
env) ([Type] -> [Type],
 [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
-> ([Type] -> [Type],
    [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
-> ([Type] -> [Type],
    [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
forall b c b c a a.
(b -> c, b -> c) -> (a -> b, a -> b) -> (a -> c, a -> c)
comb Type
typ' of
         Maybe
  (([Type] -> [Type],
    [(Type, DataCon, Type)] -> [(Type, DataCon, Type)]),
   Type)
Nothing
           | Maybe Type
Nothing <- Maybe Type
mb_typ' -> Type -> TopNormaliseTypeResult
NoChange Type
typ
           | Bool
otherwise          -> Type -> TopNormaliseTypeResult
NormalisedByConstraints Type
typ'
         Just (([Type] -> [Type]
ty_f,[(Type, DataCon, Type)] -> [(Type, DataCon, Type)]
tm_f), Type
ty) -> Type -> [(Type, DataCon, Type)] -> Type -> TopNormaliseTypeResult
HadRedexes Type
src_ty [(Type, DataCon, Type)]
newtype_dcs Type
core_ty
           where
             src_ty :: Type
src_ty = Type -> [Type] -> Type
eq_src_ty Type
ty (Type
typ' Type -> [Type] -> [Type]
forall a. a -> [a] -> [a]
: [Type] -> [Type]
ty_f [Type
ty])
             newtype_dcs :: [(Type, DataCon, Type)]
newtype_dcs = [(Type, DataCon, Type)] -> [(Type, DataCon, Type)]
tm_f []
             core_ty :: Type
core_ty = Type
ty
  where
    -- Find the first type in the sequence of rewrites that is a data type,
    -- newtype, or a data family application (not the representation tycon!).
    -- This is the one that is equal (in source Haskell) to the initial type.
    -- If none is found in the list, then all of them are type family
    -- applications, so we simply return the last one, which is the *simplest*.
    eq_src_ty :: Type -> [Type] -> Type
    eq_src_ty :: Type -> [Type] -> Type
eq_src_ty Type
ty [Type]
tys = Type -> (Type -> Type) -> Maybe Type -> Type
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Type
ty Type -> Type
forall a. a -> a
id ((Type -> Bool) -> [Type] -> Maybe Type
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find Type -> Bool
is_closed_or_data_family [Type]
tys)

    is_closed_or_data_family :: Type -> Bool
    is_closed_or_data_family :: Type -> Bool
is_closed_or_data_family Type
ty = Type -> Bool
pmIsClosedType Type
ty Bool -> Bool -> Bool
|| Type -> Bool
isDataFamilyAppType Type
ty

    -- For efficiency, represent both lists as difference lists.
    -- comb performs the concatenation, for both lists.
    comb :: (b -> c, b -> c) -> (a -> b, a -> b) -> (a -> c, a -> c)
comb (b -> c
tyf1, b -> c
tmf1) (a -> b
tyf2, a -> b
tmf2) = (b -> c
tyf1 (b -> c) -> (a -> b) -> a -> c
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> b
tyf2, b -> c
tmf1 (b -> c) -> (a -> b) -> a -> c
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> b
tmf2)

    stepper :: FamInstEnvs
-> NormaliseStepper
     ([Type] -> [Type],
      [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
stepper FamInstEnvs
env = NormaliseStepper
  ([Type] -> [Type],
   [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
newTypeStepper NormaliseStepper
  ([Type] -> [Type],
   [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
-> NormaliseStepper
     ([Type] -> [Type],
      [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
-> NormaliseStepper
     ([Type] -> [Type],
      [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
forall ev.
NormaliseStepper ev -> NormaliseStepper ev -> NormaliseStepper ev
`composeSteppers` FamInstEnvs
-> NormaliseStepper
     ([Type] -> [Type],
      [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
forall a.
FamInstEnvs -> NormaliseStepper ([Type] -> [Type], a -> a)
tyFamStepper FamInstEnvs
env

    -- A 'NormaliseStepper' that unwraps newtypes, careful not to fall into
    -- a loop. If it would fall into a loop, it produces 'NS_Abort'.
    newTypeStepper :: NormaliseStepper ([Type] -> [Type],[(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
    newTypeStepper :: NormaliseStepper
  ([Type] -> [Type],
   [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
newTypeStepper RecTcChecker
rec_nts TyCon
tc [Type]
tys
      | Just (Type
ty', Coercion
_co) <- TyCon -> [Type] -> Maybe (Type, Coercion)
instNewTyCon_maybe TyCon
tc [Type]
tys
      , let orig_ty :: Type
orig_ty = TyCon -> [Type] -> Type
TyConApp TyCon
tc [Type]
tys
      = case RecTcChecker -> TyCon -> Maybe RecTcChecker
checkRecTc RecTcChecker
rec_nts TyCon
tc of
          Just RecTcChecker
rec_nts' -> let tyf :: [Type] -> [Type]
tyf = (Type
orig_tyType -> [Type] -> [Type]
forall a. a -> [a] -> [a]
:)
                               tmf :: [(Type, DataCon, Type)] -> [(Type, DataCon, Type)]
tmf = ((Type
orig_ty, TyCon -> DataCon
tyConSingleDataCon TyCon
tc, Type
ty')(Type, DataCon, Type)
-> [(Type, DataCon, Type)] -> [(Type, DataCon, Type)]
forall a. a -> [a] -> [a]
:)
                           in  RecTcChecker
-> Type
-> ([Type] -> [Type],
    [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
-> NormaliseStepResult
     ([Type] -> [Type],
      [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
forall ev. RecTcChecker -> Type -> ev -> NormaliseStepResult ev
NS_Step RecTcChecker
rec_nts' Type
ty' ([Type] -> [Type]
tyf, [(Type, DataCon, Type)] -> [(Type, DataCon, Type)]
tmf)
          Maybe RecTcChecker
Nothing       -> NormaliseStepResult
  ([Type] -> [Type],
   [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
forall ev. NormaliseStepResult ev
NS_Abort
      | Bool
otherwise
      = NormaliseStepResult
  ([Type] -> [Type],
   [(Type, DataCon, Type)] -> [(Type, DataCon, Type)])
forall ev. NormaliseStepResult ev
NS_Done

    tyFamStepper :: FamInstEnvs -> NormaliseStepper ([Type] -> [Type], a -> a)
    tyFamStepper :: FamInstEnvs -> NormaliseStepper ([Type] -> [Type], a -> a)
tyFamStepper FamInstEnvs
env RecTcChecker
rec_nts TyCon
tc [Type]
tys  -- Try to step a type/data family
      = let (Coercion
_args_co, [Type]
ntys, Coercion
_res_co) = FamInstEnvs
-> Role -> TyCon -> [Type] -> (Coercion, [Type], Coercion)
normaliseTcArgs FamInstEnvs
env Role
Representational TyCon
tc [Type]
tys in
          -- NB: It's OK to use normaliseTcArgs here instead of
          -- normalise_tc_args (which takes the LiftingContext described
          -- in Note [Normalising types]) because the reduceTyFamApp below
          -- works only at top level. We'll never recur in this function
          -- after reducing the kind of a bound tyvar.

        case FamInstEnvs -> Role -> TyCon -> [Type] -> Maybe (Coercion, Type)
reduceTyFamApp_maybe FamInstEnvs
env Role
Representational TyCon
tc [Type]
ntys of
          Just (Coercion
_co, Type
rhs) -> RecTcChecker
-> Type
-> ([Type] -> [Type], a -> a)
-> NormaliseStepResult ([Type] -> [Type], a -> a)
forall ev. RecTcChecker -> Type -> ev -> NormaliseStepResult ev
NS_Step RecTcChecker
rec_nts Type
rhs ((Type
rhsType -> [Type] -> [Type]
forall a. a -> [a] -> [a]
:), a -> a
forall a. a -> a
id)
          Maybe (Coercion, Type)
_               -> NormaliseStepResult ([Type] -> [Type], a -> a)
forall ev. NormaliseStepResult ev
NS_Done

-- | Returns 'True' if the argument 'Type' is a fully saturated application of
-- a closed type constructor.
--
-- Closed type constructors are those with a fixed right hand side, as
-- opposed to e.g. associated types. These are of particular interest for
-- pattern-match coverage checking, because GHC can exhaustively consider all
-- possible forms that values of a closed type can take on.
--
-- Note that this function is intended to be used to check types of value-level
-- patterns, so as a consequence, the 'Type' supplied as an argument to this
-- function should be of kind @Type@.
pmIsClosedType :: Type -> Bool
pmIsClosedType :: Type -> Bool
pmIsClosedType Type
ty
  = case HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe Type
ty of
      Just (TyCon
tc, [Type]
ty_args)
             | TyCon -> Bool
is_algebraic_like TyCon
tc Bool -> Bool -> Bool
&& Bool -> Bool
not (TyCon -> Bool
isFamilyTyCon TyCon
tc)
             -> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True
      Maybe (TyCon, [Type])
_other -> Bool
False
  where
    -- This returns True for TyCons which /act like/ algebraic types.
    -- (See "Type#type_classification" for what an algebraic type is.)
    --
    -- This is qualified with \"like\" because of a particular special
    -- case: TYPE (the underlyind kind behind Type, among others). TYPE
    -- is conceptually a datatype (and thus algebraic), but in practice it is
    -- a primitive builtin type, so we must check for it specially.
    --
    -- NB: it makes sense to think of TYPE as a closed type in a value-level,
    -- pattern-matching context. However, at the kind level, TYPE is certainly
    -- not closed! Since this function is specifically tailored towards pattern
    -- matching, however, it's OK to label TYPE as closed.
    is_algebraic_like :: TyCon -> Bool
    is_algebraic_like :: TyCon -> Bool
is_algebraic_like TyCon
tc = TyCon -> Bool
isAlgTyCon TyCon
tc Bool -> Bool -> Bool
|| TyCon
tc TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tYPETyCon

{- Note [Type normalisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Constructs like -XEmptyCase or a previous unsuccessful pattern match on a data
constructor place a non-void constraint on the matched thing. This means that it
boils down to checking whether the type of the scrutinee is inhabited. Function
pmTopNormaliseType gets rid of the outermost type function/data family redex and
newtypes, in search of an algebraic type constructor, which is easier to check
for inhabitation.

It returns 3 results instead of one, because there are 2 subtle points:
1. Newtypes are isomorphic to the underlying type in core but not in the source
   language,
2. The representational data family tycon is used internally but should not be
   shown to the user

Hence, if pmTopNormaliseType env ty_cs ty = Just (src_ty, dcs, core_ty),
then
  (a) src_ty is the rewritten type which we can show to the user. That is, the
      type we get if we rewrite type families but not data families or
      newtypes.
  (b) dcs is the list of newtype constructors "skipped", every time we normalise
      a newtype to its core representation, we keep track of the source data
      constructor. For convenienve, we also track the type we unwrap and the
      type of its field. Example: @Down 42@ => @[(Down @Int, Down, Int)]
  (c) core_ty is the rewritten type. That is,
        pmTopNormaliseType env ty_cs ty = Just (src_ty, dcs, core_ty)
      implies
        topNormaliseType_maybe env ty = Just (co, core_ty)
      for some coercion co.

To see how all cases come into play, consider the following example:

  data family T a :: *
  data instance T Int = T1 | T2 Bool
  -- Which gives rise to FC:
  --   data T a
  --   data R:TInt = T1 | T2 Bool
  --   axiom ax_ti : T Int ~R R:TInt

  newtype G1 = MkG1 (T Int)
  newtype G2 = MkG2 G1

  type instance F Int  = F Char
  type instance F Char = G2

In this case pmTopNormaliseType env ty_cs (F Int) results in

  Just (G2, [(G2,MkG2,G1),(G1,MkG1,T Int)], R:TInt)

Which means that in source Haskell:
  - G2 is equivalent to F Int (in contrast, G1 isn't).
  - if (x : R:TInt) then (MkG2 (MkG1 x) : F Int).

-----
-- Wrinkle: Local equalities
-----

Given the following type family:

  type family F a
  type instance F Int = Void

Should the following program (from #14813) be considered exhaustive?

  f :: (i ~ Int) => F i -> a
  f x = case x of {}

You might think "of course, since `x` is obviously of type Void". But the
idType of `x` is technically F i, not Void, so if we pass F i to
inhabitationCandidates, we'll mistakenly conclude that `f` is non-exhaustive.
In order to avoid this pitfall, we need to normalise the type passed to
pmTopNormaliseType, using the constraint solver to solve for any local
equalities (such as i ~ Int) that may be in scope.
-}

----------------
-- * Type oracle

-- | Wraps a 'PredType', which is a constraint type.
newtype TyCt = TyCt PredType

instance Outputable TyCt where
  ppr :: TyCt -> SDoc
ppr (TyCt Type
pred_ty) = Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
pred_ty

-- | Allocates a fresh 'EvVar' name for 'PredTyCt's, or simply returns the
-- wrapped 'EvVar' for 'EvVarTyCt's.
nameTyCt :: TyCt -> DsM EvVar
nameTyCt :: TyCt -> DsM Id
nameTyCt (TyCt Type
pred_ty) = do
  Unique
unique <- IOEnv (Env DsGblEnv DsLclEnv) Unique
forall (m :: * -> *). MonadUnique m => m Unique
getUniqueM
  let occname :: OccName
occname = FastString -> OccName
mkVarOccFS (String -> FastString
fsLit (String
"pm_"String -> String -> String
forall a. [a] -> [a] -> [a]
++Unique -> String
forall a. Show a => a -> String
show Unique
unique))
      idname :: Name
idname  = Unique -> OccName -> SrcSpan -> Name
mkInternalName Unique
unique OccName
occname SrcSpan
noSrcSpan
  Id -> DsM Id
forall (m :: * -> *) a. Monad m => a -> m a
return (Name -> Type -> Id
mkLocalId Name
idname Type
pred_ty)

-- | Add some extra type constraints to the 'TyState'; return 'Nothing' if we
-- find a contradiction (e.g. @Int ~ Bool@).
tyOracle :: TyState -> Bag TyCt -> DsM (Maybe TyState)
tyOracle :: TyState -> Bag TyCt -> DsM (Maybe TyState)
tyOracle (TySt Bag Id
inert) Bag TyCt
cts
  = do { Bag Id
evs <- (TyCt -> DsM Id)
-> Bag TyCt -> IOEnv (Env DsGblEnv DsLclEnv) (Bag Id)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse TyCt -> DsM Id
nameTyCt Bag TyCt
cts
       ; let new_inert :: Bag Id
new_inert = Bag Id
inert Bag Id -> Bag Id -> Bag Id
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag Id
evs
       ; String -> SDoc -> DsM ()
tracePm String
"tyOracle" (Bag TyCt -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TyCt
cts)
       ; ((WarningMessages
_warns, WarningMessages
errs), Maybe Bool
res) <- TcM Bool -> DsM (Messages, Maybe Bool)
forall a. TcM a -> DsM (Messages, Maybe a)
initTcDsForSolver (TcM Bool -> DsM (Messages, Maybe Bool))
-> TcM Bool -> DsM (Messages, Maybe Bool)
forall a b. (a -> b) -> a -> b
$ Bag Id -> TcM Bool
tcCheckSatisfiability Bag Id
new_inert
       ; case Maybe Bool
res of
            -- Note how this implicitly gives all former PredTyCts a name, so
            -- that we don't needlessly re-allocate them every time!
            Just Bool
True  -> Maybe TyState -> DsM (Maybe TyState)
forall (m :: * -> *) a. Monad m => a -> m a
return (TyState -> Maybe TyState
forall a. a -> Maybe a
Just (Bag Id -> TyState
TySt Bag Id
new_inert))
            Just Bool
False -> Maybe TyState -> DsM (Maybe TyState)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe TyState
forall a. Maybe a
Nothing
            Maybe Bool
Nothing    -> String -> SDoc -> DsM (Maybe TyState)
forall a. HasCallStack => String -> SDoc -> a
pprPanic String
"tyOracle" ([SDoc] -> SDoc
vcat ([SDoc] -> SDoc) -> [SDoc] -> SDoc
forall a b. (a -> b) -> a -> b
$ WarningMessages -> [SDoc]
pprErrMsgBagWithLoc WarningMessages
errs) }

-- | A 'SatisfiabilityCheck' based on new type-level constraints.
-- Returns a new 'Delta' if the new constraints are compatible with existing
-- ones. Doesn't bother calling out to the type oracle if the bag of new type
-- constraints was empty. Will only recheck 'PossibleMatches' in the term oracle
-- for emptiness if the first argument is 'True'.
tyIsSatisfiable :: Bool -> Bag TyCt -> SatisfiabilityCheck
tyIsSatisfiable :: Bool -> Bag TyCt -> SatisfiabilityCheck
tyIsSatisfiable Bool
recheck_complete_sets Bag TyCt
new_ty_cs = (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
SC ((Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck)
-> (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
forall a b. (a -> b) -> a -> b
$ \Delta
delta ->
  if Bag TyCt -> Bool
forall a. Bag a -> Bool
isEmptyBag Bag TyCt
new_ty_cs
    then Maybe Delta -> DsM (Maybe Delta)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Delta -> Maybe Delta
forall a. a -> Maybe a
Just Delta
delta)
    else TyState -> Bag TyCt -> DsM (Maybe TyState)
tyOracle (Delta -> TyState
delta_ty_st Delta
delta) Bag TyCt
new_ty_cs DsM (Maybe TyState)
-> (Maybe TyState -> DsM (Maybe Delta)) -> DsM (Maybe Delta)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
      Maybe TyState
Nothing                   -> Maybe Delta -> DsM (Maybe Delta)
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Delta
forall a. Maybe a
Nothing
      Just TyState
ty_st'               -> do
        let delta' :: Delta
delta' = Delta
delta{ delta_ty_st :: TyState
delta_ty_st = TyState
ty_st' }
        if Bool
recheck_complete_sets
          then Delta -> DsM (Maybe Delta)
ensureAllPossibleMatchesInhabited Delta
delta'
          else Maybe Delta -> DsM (Maybe Delta)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Delta -> Maybe Delta
forall a. a -> Maybe a
Just Delta
delta')


{- *********************************************************************
*                                                                      *
              DIdEnv with sharing
*                                                                      *
********************************************************************* -}


{- *********************************************************************
*                                                                      *
                 TmState
          What we know about terms
*                                                                      *
********************************************************************* -}

{- Note [The Pos/Neg invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Invariant applying to each VarInfo: Whenever we have @(C, [y,z])@ in 'vi_pos',
any entry in 'vi_neg' must be incomparable to C (return Nothing) according to
'eqPmAltCons'. Those entries that are comparable either lead to a refutation
or are redudant. Examples:
* @x ~ Just y@, @x /~ [Just]@. 'eqPmAltCon' returns @Equal@, so refute.
* @x ~ Nothing@, @x /~ [Just]@. 'eqPmAltCon' returns @Disjoint@, so negative
  info is redundant and should be discarded.
* @x ~ I# y@, @x /~ [4,2]@. 'eqPmAltCon' returns @PossiblyOverlap@, so orthogal.
  We keep this info in order to be able to refute a redundant match on i.e. 4
  later on.

This carries over to pattern synonyms and overloaded literals. Say, we have
    pattern Just42 = Just 42
    case Just42 of x
      Nothing -> ()
      Just _  -> ()
Even though we had a solution for the value abstraction called x here in form
of a PatSynCon (Just42,[]), this solution is incomparable to both Nothing and
Just. Hence we retain the info in vi_neg, which eventually allows us to detect
the complete pattern match.

The Pos/Neg invariant extends to vi_cache, which stores essentially positive
information. We make sure that vi_neg and vi_cache never overlap. This isn't
strictly necessary since vi_cache is just a cache, so doesn't need to be
accurate: Every suggestion of a possible ConLike from vi_cache might be
refutable by the type oracle anyway. But it helps to maintain sanity while
debugging traces.

Note [Why record both positive and negative info?]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You might think that knowing positive info (like x ~ Just y) would render
negative info irrelevant, but not so because of pattern synonyms.  E.g we might
know that x cannot match (Foo 4), where pattern Foo p = Just p

Also overloaded literals themselves behave like pattern synonyms. E.g if
postively we know that (x ~ I# y), we might also negatively want to record that
x does not match 45 f 45       = e2 f (I# 22#) = e3 f 45       = e4  --
Overlapped

Note [TmState invariants]
~~~~~~~~~~~~~~~~~~~~~~~~~
The term oracle state is never obviously (i.e., without consulting the type
oracle) contradictory. This implies a few invariants:
* Whenever vi_pos overlaps with vi_neg according to 'eqPmAltCon', we refute.
  This is implied by the Note [Pos/Neg invariant].
* Whenever vi_neg subsumes a COMPLETE set, we refute. We consult vi_cache to
  detect this, but we could just compare whole COMPLETE sets to vi_neg every
  time, if it weren't for performance.

Maintaining these invariants in 'addVarVarCt' (the core of the term oracle) and
'addRefutableAltCon' is subtle.
* Merging VarInfos. Example: Add the fact @x ~ y@ (see 'equate').
  - (COMPLETE) If we had @x /~ True@ and @y /~ False@, then we get
    @x /~ [True,False]@. This is vacuous by matter of comparing to the built-in
    COMPLETE set, so should refute.
  - (Pos/Neg) If we had @x /~ True@ and @y ~ True@, we have to refute.
* Adding positive information. Example: Add the fact @x ~ K ys@ (see 'addVarConCt')
  - (Neg) If we had @x /~ K@, refute.
  - (Pos) If we had @x ~ K2@, and that contradicts the new solution according to
    'eqPmAltCon' (ex. K2 is [] and K is (:)), then refute.
  - (Refine) If we had @x /~ K zs@, unify each y with each z in turn.
* Adding negative information. Example: Add the fact @x /~ Nothing@ (see 'addRefutableAltCon')
  - (Refut) If we have @x ~ K ys@, refute.
  - (Redundant) If we have @x ~ K2@ and @eqPmAltCon K K2 == Disjoint@
    (ex. Just and Nothing), the info is redundant and can be
    discarded.
  - (COMPLETE) If K=Nothing and we had @x /~ Just@, then we get
    @x /~ [Just,Nothing]@. This is vacuous by matter of comparing to the built-in
    COMPLETE set, so should refute.

Note that merging VarInfo in equate can be done by calling out to 'addVarConCt' and
'addRefutableAltCon' for each of the facts individually.

Note [Representation of Strings in TmState]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Instead of treating regular String literals as a PmLits, we treat it as a list
of characters in the oracle for better overlap reasoning. The following example
shows why:

  f :: String -> ()
  f ('f':_) = ()
  f "foo"   = ()
  f _       = ()

The second case is redundant, and we like to warn about it. Therefore either
the oracle will have to do some smart conversion between the list and literal
representation or treat is as the list it really is at runtime.

The "smart conversion" has the advantage of leveraging the more compact literal
representation wherever possible, but is really nasty to get right with negative
equalities: Just think of how to encode @x /= "foo"@.
The "list" option is far simpler, but incurs some overhead in representation and
warning messages (which can be alleviated by someone with enough dedication).
-}

-- | A 'SatisfiabilityCheck' based on new term-level constraints.
-- Returns a new 'Delta' if the new constraints are compatible with existing
-- ones.
tmIsSatisfiable :: Bag TmCt -> SatisfiabilityCheck
tmIsSatisfiable :: Bag TmCt -> SatisfiabilityCheck
tmIsSatisfiable Bag TmCt
new_tm_cs = (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
SC ((Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck)
-> (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
forall a b. (a -> b) -> a -> b
$ \Delta
delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta))
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
-> DsM (Maybe Delta)
forall a b. (a -> b) -> a -> b
$ (Delta -> TmCt -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> Delta
-> Bag TmCt
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM Delta -> TmCt -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
go Delta
delta Bag TmCt
new_tm_cs
  where
    go :: Delta -> TmCt -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
go Delta
delta TmCt
ct = DsM (Maybe Delta) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (Delta -> TmCt -> DsM (Maybe Delta)
addTmCt Delta
delta TmCt
ct)

-----------------------
-- * Looking up VarInfo

emptyVarInfo :: Id -> VarInfo
emptyVarInfo :: Id -> VarInfo
emptyVarInfo Id
x = Type
-> [(PmAltCon, [Id])] -> [PmAltCon] -> PossibleMatches -> VarInfo
VI (Id -> Type
idType Id
x) [] [] PossibleMatches
NoPM

lookupVarInfo :: TmState -> Id -> VarInfo
-- (lookupVarInfo tms x) tells what we know about 'x'
lookupVarInfo :: TmState -> Id -> VarInfo
lookupVarInfo (TmSt SharedDIdEnv VarInfo
env CoreMap Id
_) Id
x = VarInfo -> Maybe VarInfo -> VarInfo
forall a. a -> Maybe a -> a
fromMaybe (Id -> VarInfo
emptyVarInfo Id
x) (SharedDIdEnv VarInfo -> Id -> Maybe VarInfo
forall a. SharedDIdEnv a -> Id -> Maybe a
lookupSDIE SharedDIdEnv VarInfo
env Id
x)

initPossibleMatches :: TyState -> VarInfo -> DsM VarInfo
initPossibleMatches :: TyState -> VarInfo -> DsM VarInfo
initPossibleMatches TyState
ty_st vi :: VarInfo
vi@VI{ vi_ty :: VarInfo -> Type
vi_ty = Type
ty, vi_cache :: VarInfo -> PossibleMatches
vi_cache = PossibleMatches
NoPM } = do
  -- New evidence might lead to refined info on ty, in turn leading to discovery
  -- of a COMPLETE set.
  TopNormaliseTypeResult
res <- TyState -> Type -> DsM TopNormaliseTypeResult
pmTopNormaliseType TyState
ty_st Type
ty
  let ty' :: Type
ty' = TopNormaliseTypeResult -> Type
normalisedSourceType TopNormaliseTypeResult
res
  case HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe Type
ty' of
    Maybe (TyCon, [Type])
Nothing -> VarInfo -> DsM VarInfo
forall (f :: * -> *) a. Applicative f => a -> f a
pure VarInfo
vi{ vi_ty :: Type
vi_ty = Type
ty' }
    Just (TyCon
tc, [Type
_])
      | TyCon
tc TyCon -> TyCon -> Bool
forall a. Eq a => a -> a -> Bool
== TyCon
tYPETyCon
      -- TYPE acts like an empty data type on the term-level (#14086), but
      -- it is a PrimTyCon, so tyConDataCons_maybe returns Nothing. Hence a
      -- special case.
      -> VarInfo -> DsM VarInfo
forall (f :: * -> *) a. Applicative f => a -> f a
pure VarInfo
vi{ vi_ty :: Type
vi_ty = Type
ty', vi_cache :: PossibleMatches
vi_cache = NonEmpty ConLikeSet -> PossibleMatches
PM (ConLikeSet -> NonEmpty ConLikeSet
forall (f :: * -> *) a. Applicative f => a -> f a
pure ConLikeSet
forall a. UniqDSet a
emptyUniqDSet) }
    Just (TyCon
tc, [Type]
tc_args) -> do
      -- See Note [COMPLETE sets on data families]
      (TyCon
tc_rep, TyCon
tc_fam) <- case TyCon -> Maybe (TyCon, [Type])
tyConFamInst_maybe TyCon
tc of
        Just (TyCon
tc_fam, [Type]
_) -> (TyCon, TyCon) -> IOEnv (Env DsGblEnv DsLclEnv) (TyCon, TyCon)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (TyCon
tc, TyCon
tc_fam)
        Maybe (TyCon, [Type])
Nothing -> do
          FamInstEnvs
env <- DsM FamInstEnvs
dsGetFamInstEnvs
          let (TyCon
tc_rep, [Type]
_tc_rep_args, Coercion
_co) = FamInstEnvs -> TyCon -> [Type] -> (TyCon, [Type], Coercion)
tcLookupDataFamInst FamInstEnvs
env TyCon
tc [Type]
tc_args
          (TyCon, TyCon) -> IOEnv (Env DsGblEnv DsLclEnv) (TyCon, TyCon)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (TyCon
tc_rep, TyCon
tc)
      -- Note that the common case here is tc_rep == tc_fam
      let mb_rdcs :: Maybe [ConLike]
mb_rdcs = (DataCon -> ConLike) -> [DataCon] -> [ConLike]
forall a b. (a -> b) -> [a] -> [b]
map DataCon -> ConLike
RealDataCon ([DataCon] -> [ConLike]) -> Maybe [DataCon] -> Maybe [ConLike]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TyCon -> Maybe [DataCon]
tyConDataCons_maybe TyCon
tc_rep
      let rdcs :: [[ConLike]]
rdcs = Maybe [ConLike] -> [[ConLike]]
forall a. Maybe a -> [a]
maybeToList Maybe [ConLike]
mb_rdcs
      -- NB: tc_fam, because COMPLETE sets are associated with the parent data
      -- family TyCon
      [CompleteMatch]
pragmas <- TyCon -> DsM [CompleteMatch]
dsGetCompleteMatches TyCon
tc_fam
      let fams :: CompleteMatch -> IOEnv (Env DsGblEnv DsLclEnv) [ConLike]
fams = (Name -> IOEnv (Env DsGblEnv DsLclEnv) ConLike)
-> [Name] -> IOEnv (Env DsGblEnv DsLclEnv) [ConLike]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Name -> IOEnv (Env DsGblEnv DsLclEnv) ConLike
dsLookupConLike ([Name] -> IOEnv (Env DsGblEnv DsLclEnv) [ConLike])
-> (CompleteMatch -> [Name])
-> CompleteMatch
-> IOEnv (Env DsGblEnv DsLclEnv) [ConLike]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CompleteMatch -> [Name]
completeMatchConLikes
      [[ConLike]]
pscs <- (CompleteMatch -> IOEnv (Env DsGblEnv DsLclEnv) [ConLike])
-> [CompleteMatch] -> IOEnv (Env DsGblEnv DsLclEnv) [[ConLike]]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM CompleteMatch -> IOEnv (Env DsGblEnv DsLclEnv) [ConLike]
fams [CompleteMatch]
pragmas
      -- pprTrace "initPossibleMatches" (ppr ty $$ ppr ty' $$ ppr tc_rep <+> ppr tc_fam <+> ppr tc_args $$ ppr (rdcs ++ pscs)) (return ())
      case [[ConLike]] -> Maybe (NonEmpty [ConLike])
forall a. [a] -> Maybe (NonEmpty a)
NonEmpty.nonEmpty ([[ConLike]]
rdcs [[ConLike]] -> [[ConLike]] -> [[ConLike]]
forall a. [a] -> [a] -> [a]
++ [[ConLike]]
pscs) of
        Maybe (NonEmpty [ConLike])
Nothing -> VarInfo -> DsM VarInfo
forall (f :: * -> *) a. Applicative f => a -> f a
pure VarInfo
vi{ vi_ty :: Type
vi_ty = Type
ty' } -- Didn't find any COMPLETE sets
        Just NonEmpty [ConLike]
cs -> VarInfo -> DsM VarInfo
forall (f :: * -> *) a. Applicative f => a -> f a
pure VarInfo
vi{ vi_ty :: Type
vi_ty = Type
ty', vi_cache :: PossibleMatches
vi_cache = NonEmpty ConLikeSet -> PossibleMatches
PM ([ConLike] -> ConLikeSet
forall a. Uniquable a => [a] -> UniqDSet a
mkUniqDSet ([ConLike] -> ConLikeSet)
-> NonEmpty [ConLike] -> NonEmpty ConLikeSet
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> NonEmpty [ConLike]
cs) }
initPossibleMatches TyState
_     VarInfo
vi                                   = VarInfo -> DsM VarInfo
forall (f :: * -> *) a. Applicative f => a -> f a
pure VarInfo
vi

-- | @initLookupVarInfo ts x@ looks up the 'VarInfo' for @x@ in @ts@ and tries
-- to initialise the 'vi_cache' component if it was 'NoPM' through
-- 'initPossibleMatches'.
initLookupVarInfo :: Delta -> Id -> DsM VarInfo
initLookupVarInfo :: Delta -> Id -> DsM VarInfo
initLookupVarInfo MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmState
ts, delta_ty_st :: Delta -> TyState
delta_ty_st = TyState
ty_st } Id
x
  = TyState -> VarInfo -> DsM VarInfo
initPossibleMatches TyState
ty_st (TmState -> Id -> VarInfo
lookupVarInfo TmState
ts Id
x)

{- Note [COMPLETE sets on data families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
User-defined COMPLETE sets involving data families are attached to the family
TyCon, whereas the built-in COMPLETE set is attached to a data family instance's
representation TyCon. This matters for COMPLETE sets involving both DataCons
and PatSyns (from #17207):

  data family T a
  data family instance T () = A | B
  pattern C = B
  {-# COMPLETE A, C #-}
  f :: T () -> ()
  f A = ()
  f C = ()

The match on A is actually wrapped in a CoPat, matching impedance between T ()
and its representation TyCon, which we translate as
@x | let y = x |> co, A <- y@ in PmCheck.

Which TyCon should we use for looking up the COMPLETE set? The representation
TyCon from the match on A would only reveal the built-in COMPLETE set, while the
data family TyCon would only give the user-defined one. But when initialising
the PossibleMatches for a given Type, we want to do so only once, because
merging different COMPLETE sets after the fact is very complicated and possibly
inefficient.

So in fact, we just *drop* the coercion arising from the CoPat when handling
handling the constraint @y ~ x |> co@ in addVarCoreCt, just equating @y ~ x@.
We then handle the fallout in initPossibleMatches, which has to get a hand at
both the representation TyCon tc_rep and the parent data family TyCon tc_fam.
It considers three cases after having established that the Type is a TyConApp:

1. The TyCon is a vanilla data type constructor
2. The TyCon is tc_rep
3. The TyCon is tc_fam

1. is simple and subsumed by the handling of the other two.
We check for case 2. by 'tyConFamInst_maybe' and get the tc_fam out.
Otherwise (3.), we try to lookup the data family instance at that particular
type to get out the tc_rep. In case 1., this will just return the original
TyCon, so tc_rep = tc_fam afterwards.
-}

------------------------------------------------
-- * Exported utility functions querying 'Delta'

-- | Check whether adding a constraint @x ~ BOT@ to 'Delta' succeeds.
canDiverge :: Delta -> Id -> Bool
canDiverge :: Delta -> Id -> Bool
canDiverge delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmState
ts } Id
x
  | VI Type
_ [(PmAltCon, [Id])]
pos [PmAltCon]
neg PossibleMatches
_ <- TmState -> Id -> VarInfo
lookupVarInfo TmState
ts Id
x
  = [PmAltCon] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PmAltCon]
neg Bool -> Bool -> Bool
&& ((PmAltCon, [Id]) -> Bool) -> [(PmAltCon, [Id])] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (PmAltCon, [Id]) -> Bool
pos_can_diverge [(PmAltCon, [Id])]
pos
  where
    pos_can_diverge :: (PmAltCon, [Id]) -> Bool
pos_can_diverge (PmAltConLike (RealDataCon DataCon
dc), [Id
y])
      -- See Note [Divergence of Newtype matches]
      | TyCon -> Bool
isNewTyCon (DataCon -> TyCon
dataConTyCon DataCon
dc) = Delta -> Id -> Bool
canDiverge Delta
delta Id
y
    pos_can_diverge (PmAltCon, [Id])
_ = Bool
False

{- Note [Divergence of Newtype matches]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Newtypes behave rather strangely when compared to ordinary DataCons. In a
pattern-match, they behave like a irrefutable (lazy) match, but for inhabitation
testing purposes (e.g. at construction sites), they behave rather like a DataCon
with a *strict* field, because they don't contribute their own bottom and are
inhabited iff the wrapped type is inhabited.

This distinction becomes apparent in #17248:

  newtype T2 a = T2 a
  g _      True = ()
  g (T2 _) True = ()
  g !_     True = ()

If we treat Newtypes like we treat regular DataCons, we would mark the third
clause as redundant, which clearly is unsound. The solution:
1. When checking the PmCon in 'pmCheck', never mark the result as Divergent if
   it's a Newtype match.
2. Regard @T2 x@ as 'canDiverge' iff @x@ 'canDiverge'. E.g. @T2 x ~ _|_@ <=>
   @x ~ _|_@. This way, the third clause will still be marked as inaccessible
   RHS instead of redundant.
3. When testing for inhabitants ('mkOneConFull'), we regard the newtype field as
   strict, so that the newtype is inhabited iff its field is inhabited.
-}

lookupRefuts :: Uniquable k => Delta -> k -> [PmAltCon]
-- Unfortunately we need the extra bit of polymorphism and the unfortunate
-- duplication of lookupVarInfo here.
lookupRefuts :: Delta -> k -> [PmAltCon]
lookupRefuts MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = ts :: TmState
ts@(TmSt (SDIE DIdEnv (Shared VarInfo)
env) CoreMap Id
_) } k
k =
  case DIdEnv (Shared VarInfo) -> k -> Maybe (Shared VarInfo)
forall key elt. Uniquable key => UniqDFM elt -> key -> Maybe elt
lookupUDFM DIdEnv (Shared VarInfo)
env k
k of
    Maybe (Shared VarInfo)
Nothing -> []
    Just (Indirect Id
y) -> VarInfo -> [PmAltCon]
vi_neg (TmState -> Id -> VarInfo
lookupVarInfo TmState
ts Id
y)
    Just (Entry VarInfo
vi)   -> VarInfo -> [PmAltCon]
vi_neg VarInfo
vi

isDataConSolution :: (PmAltCon, [Id]) -> Bool
isDataConSolution :: (PmAltCon, [Id]) -> Bool
isDataConSolution (PmAltConLike (RealDataCon DataCon
_), [Id]
_) = Bool
True
isDataConSolution (PmAltCon, [Id])
_                                 = Bool
False

-- @lookupSolution delta x@ picks a single solution ('vi_pos') of @x@ from
-- possibly many, preferring 'RealDataCon' solutions whenever possible.
lookupSolution :: Delta -> Id -> Maybe (PmAltCon, [Id])
lookupSolution :: Delta -> Id -> Maybe (PmAltCon, [Id])
lookupSolution Delta
delta Id
x = case VarInfo -> [(PmAltCon, [Id])]
vi_pos (TmState -> Id -> VarInfo
lookupVarInfo (Delta -> TmState
delta_tm_st Delta
delta) Id
x) of
  []                                         -> Maybe (PmAltCon, [Id])
forall a. Maybe a
Nothing
  [(PmAltCon, [Id])]
pos
    | Just (PmAltCon, [Id])
sol <- ((PmAltCon, [Id]) -> Bool)
-> [(PmAltCon, [Id])] -> Maybe (PmAltCon, [Id])
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (PmAltCon, [Id]) -> Bool
isDataConSolution [(PmAltCon, [Id])]
pos -> (PmAltCon, [Id]) -> Maybe (PmAltCon, [Id])
forall a. a -> Maybe a
Just (PmAltCon, [Id])
sol
    | Bool
otherwise                              -> (PmAltCon, [Id]) -> Maybe (PmAltCon, [Id])
forall a. a -> Maybe a
Just ([(PmAltCon, [Id])] -> (PmAltCon, [Id])
forall a. [a] -> a
head [(PmAltCon, [Id])]
pos)

-------------------------------
-- * Adding facts to the oracle

-- | A term constraint. Either equates two variables or a variable with a
-- 'PmAltCon' application.
data TmCt
  = TmVarVar     !Id !Id
  | TmVarCon     !Id !PmAltCon ![Id]
  | TmVarNonVoid !Id

instance Outputable TmCt where
  ppr :: TmCt -> SDoc
ppr (TmVarVar Id
x Id
y)        = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
x SDoc -> SDoc -> SDoc
<+> Char -> SDoc
char Char
'~' SDoc -> SDoc -> SDoc
<+> Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
y
  ppr (TmVarCon Id
x PmAltCon
con [Id]
args) = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
x SDoc -> SDoc -> SDoc
<+> Char -> SDoc
char Char
'~' SDoc -> SDoc -> SDoc
<+> [SDoc] -> SDoc
hsep (PmAltCon -> SDoc
forall a. Outputable a => a -> SDoc
ppr PmAltCon
con SDoc -> [SDoc] -> [SDoc]
forall a. a -> [a] -> [a]
: (Id -> SDoc) -> [Id] -> [SDoc]
forall a b. (a -> b) -> [a] -> [b]
map Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Id]
args)
  ppr (TmVarNonVoid Id
x)      = Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
x SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
"/~ ⊥"

-- | Add type equalities to 'Delta'.
addTypeEvidence :: Delta -> Bag EvVar -> DsM (Maybe Delta)
addTypeEvidence :: Delta -> Bag Id -> DsM (Maybe Delta)
addTypeEvidence Delta
delta Bag Id
dicts
  = Delta -> SatisfiabilityCheck -> DsM (Maybe Delta)
runSatisfiabilityCheck Delta
delta (Bool -> Bag TyCt -> SatisfiabilityCheck
tyIsSatisfiable Bool
True (Type -> TyCt
TyCt (Type -> TyCt) -> (Id -> Type) -> Id -> TyCt
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Id -> Type
evVarPred (Id -> TyCt) -> Bag Id -> Bag TyCt
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Bag Id
dicts))

-- | Tries to equate two representatives in 'Delta'.
-- See Note [TmState invariants].
addTmCt :: Delta -> TmCt -> DsM (Maybe Delta)
addTmCt :: Delta -> TmCt -> DsM (Maybe Delta)
addTmCt Delta
delta TmCt
ct = MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta))
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
-> DsM (Maybe Delta)
forall a b. (a -> b) -> a -> b
$ case TmCt
ct of
  TmVarVar Id
x Id
y        -> Delta -> (Id, Id) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarVarCt Delta
delta (Id
x, Id
y)
  TmVarCon Id
x PmAltCon
con [Id]
args -> Delta
-> Id
-> PmAltCon
-> [Id]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarConCt Delta
delta Id
x PmAltCon
con [Id]
args
  TmVarNonVoid Id
x      -> Delta -> Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarNonVoidCt Delta
delta Id
x

-- | Record that a particular 'Id' can't take the shape of a 'PmAltCon' in the
-- 'Delta' and return @Nothing@ if that leads to a contradiction.
-- See Note [TmState invariants].
addRefutableAltCon :: Delta -> Id -> PmAltCon -> DsM (Maybe Delta)
addRefutableAltCon :: Delta -> Id -> PmAltCon -> DsM (Maybe Delta)
addRefutableAltCon delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmSt SharedDIdEnv VarInfo
env CoreMap Id
reps } Id
x PmAltCon
nalt = MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta))
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
-> DsM (Maybe Delta)
forall a b. (a -> b) -> a -> b
$ do
  vi :: VarInfo
vi@(VI Type
_ [(PmAltCon, [Id])]
pos [PmAltCon]
neg PossibleMatches
pm) <- DsM VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Delta -> Id -> DsM VarInfo
initLookupVarInfo Delta
delta Id
x)
  -- 1. Bail out quickly when nalt contradicts a solution
  let contradicts :: PmAltCon -> (PmAltCon, b) -> Bool
contradicts PmAltCon
nalt (PmAltCon
cl, b
_args) = PmAltCon -> PmAltCon -> PmEquality
eqPmAltCon PmAltCon
cl PmAltCon
nalt PmEquality -> PmEquality -> Bool
forall a. Eq a => a -> a -> Bool
== PmEquality
Equal
  Bool -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Bool -> Bool
not (((PmAltCon, [Id]) -> Bool) -> [(PmAltCon, [Id])] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (PmAltCon -> (PmAltCon, [Id]) -> Bool
forall b. PmAltCon -> (PmAltCon, b) -> Bool
contradicts PmAltCon
nalt) [(PmAltCon, [Id])]
pos))
  -- 2. Only record the new fact when it's not already implied by one of the
  -- solutions
  let implies :: PmAltCon -> (PmAltCon, b) -> Bool
implies PmAltCon
nalt (PmAltCon
cl, b
_args) = PmAltCon -> PmAltCon -> PmEquality
eqPmAltCon PmAltCon
cl PmAltCon
nalt PmEquality -> PmEquality -> Bool
forall a. Eq a => a -> a -> Bool
== PmEquality
Disjoint
  let neg' :: [PmAltCon]
neg'
        | ((PmAltCon, [Id]) -> Bool) -> [(PmAltCon, [Id])] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (PmAltCon -> (PmAltCon, [Id]) -> Bool
forall b. PmAltCon -> (PmAltCon, b) -> Bool
implies PmAltCon
nalt) [(PmAltCon, [Id])]
pos = [PmAltCon]
neg
        -- See Note [Completeness checking with required Thetas]
        | PmAltCon -> Bool
hasRequiredTheta PmAltCon
nalt  = [PmAltCon]
neg
        | Bool
otherwise              = [PmAltCon] -> [PmAltCon] -> [PmAltCon]
forall a.
(HasDebugCallStack, Outputable a, Eq a) =>
[a] -> [a] -> [a]
unionLists [PmAltCon]
neg [PmAltCon
nalt]
  let vi_ext :: VarInfo
vi_ext = VarInfo
vi{ vi_neg :: [PmAltCon]
vi_neg = [PmAltCon]
neg' }
  -- 3. Make sure there's at least one other possible constructor
  VarInfo
vi' <- case PmAltCon
nalt of
    PmAltConLike ConLike
cl
      -> IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (Delta -> VarInfo -> IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
ensureInhabited Delta
delta VarInfo
vi_ext{ vi_cache :: PossibleMatches
vi_cache = ConLike -> PossibleMatches -> PossibleMatches
markMatched ConLike
cl PossibleMatches
pm })
    PmAltCon
_ -> VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall (f :: * -> *) a. Applicative f => a -> f a
pure VarInfo
vi_ext
  Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a. Applicative f => a -> f a
pure Delta
delta{ delta_tm_st :: TmState
delta_tm_st = SharedDIdEnv VarInfo -> CoreMap Id -> TmState
TmSt (SharedDIdEnv VarInfo -> Id -> VarInfo -> SharedDIdEnv VarInfo
forall a. SharedDIdEnv a -> Id -> a -> SharedDIdEnv a
setEntrySDIE SharedDIdEnv VarInfo
env Id
x VarInfo
vi') CoreMap Id
reps }

hasRequiredTheta :: PmAltCon -> Bool
hasRequiredTheta :: PmAltCon -> Bool
hasRequiredTheta (PmAltConLike ConLike
cl) = [Type] -> Bool
forall a. [a] -> Bool
notNull [Type]
req_theta
  where
    ([Id]
_,[Id]
_,[EqSpec]
_,[Type]
_,[Type]
req_theta,[Type]
_,Type
_) = ConLike -> ([Id], [Id], [EqSpec], [Type], [Type], [Type], Type)
conLikeFullSig ConLike
cl
hasRequiredTheta PmAltCon
_                 = Bool
False

{- Note [Completeness checking with required Thetas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the situation in #11224

    import Text.Read (readMaybe)
    pattern PRead :: Read a => () => a -> String
    pattern PRead x <- (readMaybe -> Just x)
    f :: String -> Int
    f (PRead x)  = x
    f (PRead xs) = length xs
    f _          = 0

Is the first match exhaustive on the PRead synonym? Should the second line thus
deemed redundant? The answer is, of course, No! The required theta is like a
hidden parameter which must be supplied at the pattern match site, so PRead
is much more like a view pattern (where behavior depends on the particular value
passed in).
The simple solution here is to forget in 'addRefutableAltCon' that we matched
on synonyms with a required Theta like @PRead@, so that subsequent matches on
the same constructor are never flagged as redundant. The consequence is that
we no longer detect the actually redundant match in

    g :: String -> Int
    g (PRead x) = x
    g (PRead y) = y -- redundant!
    g _         = 0

But that's a small price to pay, compared to the proper solution here involving
storing required arguments along with the PmAltConLike in 'vi_neg'.
-}

-- | Guess the universal argument types of a ConLike from an instantiation of
-- its result type. Rather easy for DataCons, but not so much for PatSynCons.
-- See Note [Pattern synonym result type] in PatSyn.hs.
guessConLikeUnivTyArgsFromResTy :: FamInstEnvs -> Type -> ConLike -> Maybe [Type]
guessConLikeUnivTyArgsFromResTy :: FamInstEnvs -> Type -> ConLike -> Maybe [Type]
guessConLikeUnivTyArgsFromResTy FamInstEnvs
env Type
res_ty (RealDataCon DataCon
_) = do
  (TyCon
tc, [Type]
tc_args) <- HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe Type
res_ty
  -- Consider data families: In case of a DataCon, we need to translate to
  -- the representation TyCon. For PatSyns, they are relative to the data
  -- family TyCon, so we don't need to translate them.
  let (TyCon
_, [Type]
tc_args', Coercion
_) = FamInstEnvs -> TyCon -> [Type] -> (TyCon, [Type], Coercion)
tcLookupDataFamInst FamInstEnvs
env TyCon
tc [Type]
tc_args
  [Type] -> Maybe [Type]
forall a. a -> Maybe a
Just [Type]
tc_args'
guessConLikeUnivTyArgsFromResTy FamInstEnvs
_   Type
res_ty (PatSynCon PatSyn
ps)  = do
  -- We are successful if we managed to instantiate *every* univ_tv of con.
  -- This is difficult and bound to fail in some cases, see
  -- Note [Pattern synonym result type] in PatSyn.hs. So we just try our best
  -- here and be sure to return an instantiation when we can substitute every
  -- universally quantified type variable.
  -- We *could* instantiate all the other univ_tvs just to fresh variables, I
  -- suppose, but that means we get weird field types for which we don't know
  -- anything. So we prefer to keep it simple here.
  let ([Id]
univ_tvs,[Type]
_,[Id]
_,[Type]
_,[Type]
_,Type
con_res_ty) = PatSyn -> ([Id], [Type], [Id], [Type], [Type], Type)
patSynSig PatSyn
ps
  TCvSubst
subst <- Type -> Type -> Maybe TCvSubst
tcMatchTy Type
con_res_ty Type
res_ty
  (Id -> Maybe Type) -> [Id] -> Maybe [Type]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse (TCvSubst -> Id -> Maybe Type
lookupTyVar TCvSubst
subst) [Id]
univ_tvs

-- | Kind of tries to add a non-void contraint to 'Delta', but doesn't really
-- commit to upholding that constraint in the future. This will be rectified
-- in a follow-up patch. The status quo should work good enough for now.
addVarNonVoidCt :: Delta -> Id -> MaybeT DsM Delta
addVarNonVoidCt :: Delta -> Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarNonVoidCt delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmSt SharedDIdEnv VarInfo
env CoreMap Id
reps } Id
x = do
  VarInfo
vi  <- DsM VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (DsM VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo)
-> DsM VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall a b. (a -> b) -> a -> b
$ Delta -> Id -> DsM VarInfo
initLookupVarInfo Delta
delta Id
x
  VarInfo
vi' <- IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
 -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo)
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall a b. (a -> b) -> a -> b
$ Delta -> VarInfo -> IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
ensureInhabited Delta
delta VarInfo
vi
  -- vi' has probably constructed and then thinned out some PossibleMatches.
  -- We want to cache that work
  Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a. Applicative f => a -> f a
pure Delta
delta{ delta_tm_st :: TmState
delta_tm_st = SharedDIdEnv VarInfo -> CoreMap Id -> TmState
TmSt (SharedDIdEnv VarInfo -> Id -> VarInfo -> SharedDIdEnv VarInfo
forall a. SharedDIdEnv a -> Id -> a -> SharedDIdEnv a
setEntrySDIE SharedDIdEnv VarInfo
env Id
x VarInfo
vi') CoreMap Id
reps}

ensureInhabited :: Delta -> VarInfo -> DsM (Maybe VarInfo)
   -- Returns (Just vi) if at least one member of each ConLike in the COMPLETE
   -- set satisfies the oracle
   --
   -- Internally uses and updates the ConLikeSets in vi_cache.
   --
   -- NB: Does /not/ filter each ConLikeSet with the oracle; members may
   --     remain that do not statisfy it.  This lazy approach just
   --     avoids doing unnecessary work.
ensureInhabited :: Delta -> VarInfo -> IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
ensureInhabited Delta
delta VarInfo
vi = (PossibleMatches -> VarInfo)
-> Maybe PossibleMatches -> Maybe VarInfo
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (VarInfo -> PossibleMatches -> VarInfo
set_cache VarInfo
vi) (Maybe PossibleMatches -> Maybe VarInfo)
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe PossibleMatches)
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PossibleMatches
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe PossibleMatches)
test (VarInfo -> PossibleMatches
vi_cache VarInfo
vi) -- This would be much less tedious with lenses
  where
    set_cache :: VarInfo -> PossibleMatches -> VarInfo
set_cache VarInfo
vi PossibleMatches
cache = VarInfo
vi { vi_cache :: PossibleMatches
vi_cache = PossibleMatches
cache }

    test :: PossibleMatches
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe PossibleMatches)
test PossibleMatches
NoPM    = Maybe PossibleMatches
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe PossibleMatches)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PossibleMatches -> Maybe PossibleMatches
forall a. a -> Maybe a
Just PossibleMatches
NoPM)
    test (PM NonEmpty ConLikeSet
ms) = MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) PossibleMatches
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe PossibleMatches)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (NonEmpty ConLikeSet -> PossibleMatches
PM (NonEmpty ConLikeSet -> PossibleMatches)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (NonEmpty ConLikeSet)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) PossibleMatches
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ConLikeSet -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet)
-> NonEmpty ConLikeSet
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (NonEmpty ConLikeSet)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse ConLikeSet -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
one_set NonEmpty ConLikeSet
ms)

    one_set :: ConLikeSet -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
one_set ConLikeSet
cs = ConLikeSet
-> [ConLike] -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
find_one_inh ConLikeSet
cs (ConLikeSet -> [ConLike]
forall a. UniqDSet a -> [a]
uniqDSetToList ConLikeSet
cs)

    find_one_inh :: ConLikeSet -> [ConLike] -> MaybeT DsM ConLikeSet
    -- (find_one_inh cs cls) iterates over cls, deleting from cs
    -- any uninhabited elements of cls.  Stop (returning Just cs)
    -- when you see an inhabited element; return Nothing if all
    -- are uninhabited
    find_one_inh :: ConLikeSet
-> [ConLike] -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
find_one_inh ConLikeSet
_  [] = MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
forall (m :: * -> *) a. MonadPlus m => m a
mzero
    find_one_inh ConLikeSet
cs (ConLike
con:[ConLike]
cons) = IOEnv (Env DsGblEnv DsLclEnv) Bool
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Bool
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ConLike -> IOEnv (Env DsGblEnv DsLclEnv) Bool
inh_test ConLike
con) MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Bool
-> (Bool -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
      Bool
True  -> ConLikeSet -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
forall (f :: * -> *) a. Applicative f => a -> f a
pure ConLikeSet
cs
      Bool
False -> ConLikeSet
-> [ConLike] -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ConLikeSet
find_one_inh (ConLikeSet -> ConLike -> ConLikeSet
forall a. Uniquable a => UniqDSet a -> a -> UniqDSet a
delOneFromUniqDSet ConLikeSet
cs ConLike
con) [ConLike]
cons

    inh_test :: ConLike -> DsM Bool
    -- @inh_test K@ Returns False if a non-bottom value @v::ty@ cannot possibly
    -- be of form @K _ _ _@. Returning True is always sound.
    --
    -- It's like 'DataCon.dataConCannotMatch', but more clever because it takes
    -- the facts in Delta into account.
    inh_test :: ConLike -> IOEnv (Env DsGblEnv DsLclEnv) Bool
inh_test ConLike
con = do
      FamInstEnvs
env <- DsM FamInstEnvs
dsGetFamInstEnvs
      case FamInstEnvs -> Type -> ConLike -> Maybe [Type]
guessConLikeUnivTyArgsFromResTy FamInstEnvs
env (VarInfo -> Type
vi_ty VarInfo
vi) ConLike
con of
        Maybe [Type]
Nothing -> Bool -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True -- be conservative about this
        Just [Type]
arg_tys -> do
          ([Id]
_vars, Bag TyCt
ty_cs, [Type]
strict_arg_tys) <- [Type] -> ConLike -> DsM ([Id], Bag TyCt, [Type])
mkOneConFull [Type]
arg_tys ConLike
con
          String -> SDoc -> DsM ()
tracePm String
"inh_test" (ConLike -> SDoc
forall a. Outputable a => a -> SDoc
ppr ConLike
con SDoc -> SDoc -> SDoc
$$ Bag TyCt -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TyCt
ty_cs)
          -- No need to run the term oracle compared to pmIsSatisfiable
          (Maybe Delta -> Bool)
-> DsM (Maybe Delta) -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Maybe Delta -> Bool
forall a. Maybe a -> Bool
isJust (DsM (Maybe Delta) -> IOEnv (Env DsGblEnv DsLclEnv) Bool)
-> (SatisfiabilityCheck -> DsM (Maybe Delta))
-> SatisfiabilityCheck
-> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Delta -> SatisfiabilityCheck -> DsM (Maybe Delta)
runSatisfiabilityCheck Delta
delta (SatisfiabilityCheck -> IOEnv (Env DsGblEnv DsLclEnv) Bool)
-> SatisfiabilityCheck -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall a b. (a -> b) -> a -> b
$ [SatisfiabilityCheck] -> SatisfiabilityCheck
forall a. Monoid a => [a] -> a
mconcat
            -- Important to pass False to tyIsSatisfiable here, so that we won't
            -- recursively call ensureAllPossibleMatchesInhabited, leading to an
            -- endless recursion.
            [ Bool -> Bag TyCt -> SatisfiabilityCheck
tyIsSatisfiable Bool
False Bag TyCt
ty_cs
            , RecTcChecker -> [Type] -> SatisfiabilityCheck
tysAreNonVoid RecTcChecker
initRecTc [Type]
strict_arg_tys
            ]

-- | Checks if every 'VarInfo' in the term oracle has still an inhabited
-- 'vi_cache', considering the current type information in 'Delta'.
-- This check is necessary after having matched on a GADT con to weed out
-- impossible matches.
ensureAllPossibleMatchesInhabited :: Delta -> DsM (Maybe Delta)
ensureAllPossibleMatchesInhabited :: Delta -> DsM (Maybe Delta)
ensureAllPossibleMatchesInhabited delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmSt SharedDIdEnv VarInfo
env CoreMap Id
reps }
  = MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (Delta -> SharedDIdEnv VarInfo -> Delta
set_tm_cs_env Delta
delta (SharedDIdEnv VarInfo -> Delta)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (SharedDIdEnv VarInfo)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo)
-> SharedDIdEnv VarInfo
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (SharedDIdEnv VarInfo)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> SharedDIdEnv a -> f (SharedDIdEnv b)
traverseSDIE VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
go SharedDIdEnv VarInfo
env)
  where
    set_tm_cs_env :: Delta -> SharedDIdEnv VarInfo -> Delta
set_tm_cs_env Delta
delta SharedDIdEnv VarInfo
env = Delta
delta{ delta_tm_st :: TmState
delta_tm_st = SharedDIdEnv VarInfo -> CoreMap Id -> TmState
TmSt SharedDIdEnv VarInfo
env CoreMap Id
reps }
    go :: VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
go VarInfo
vi = IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (Delta -> VarInfo -> IOEnv (Env DsGblEnv DsLclEnv) (Maybe VarInfo)
ensureInhabited Delta
delta VarInfo
vi)

--------------------------------------
-- * Term oracle unification procedure

-- | Try to unify two 'Id's and record the gained knowledge in 'Delta'.
--
-- Returns @Nothing@ when there's a contradiction. Returns @Just delta@
-- when the constraint was compatible with prior facts, in which case @delta@
-- has integrated the knowledge from the equality constraint.
--
-- See Note [TmState invariants].
addVarVarCt :: Delta -> (Id, Id) -> MaybeT DsM Delta
addVarVarCt :: Delta -> (Id, Id) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarVarCt delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmSt SharedDIdEnv VarInfo
env CoreMap Id
_ } (Id
x, Id
y)
  -- It's important that we never @equate@ two variables of the same equivalence
  -- class, otherwise we might get cyclic substitutions.
  -- Cf. 'extendSubstAndSolve' and
  -- @testsuite/tests/pmcheck/should_compile/CyclicSubst.hs@.
  | SharedDIdEnv VarInfo -> Id -> Id -> Bool
forall a. SharedDIdEnv a -> Id -> Id -> Bool
sameRepresentativeSDIE SharedDIdEnv VarInfo
env Id
x Id
y = Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a. Applicative f => a -> f a
pure Delta
delta
  | Bool
otherwise                      = Delta -> Id -> Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
equate Delta
delta Id
x Id
y

-- | @equate ts@(TmSt env) x y@ merges the equivalence classes of @x@ and @y@ by
-- adding an indirection to the environment.
-- Makes sure that the positive and negative facts of @x@ and @y@ are
-- compatible.
-- Preconditions: @not (sameRepresentativeSDIE env x y)@
--
-- See Note [TmState invariants].
equate :: Delta -> Id -> Id -> MaybeT DsM Delta
equate :: Delta -> Id -> Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
equate delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmSt SharedDIdEnv VarInfo
env CoreMap Id
reps } Id
x Id
y
  = ASSERT( not (sameRepresentativeSDIE env x y) )
    case (SharedDIdEnv VarInfo -> Id -> Maybe VarInfo
forall a. SharedDIdEnv a -> Id -> Maybe a
lookupSDIE SharedDIdEnv VarInfo
env Id
x, SharedDIdEnv VarInfo -> Id -> Maybe VarInfo
forall a. SharedDIdEnv a -> Id -> Maybe a
lookupSDIE SharedDIdEnv VarInfo
env Id
y) of
      (Maybe VarInfo
Nothing, Maybe VarInfo
_) -> Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Delta
delta{ delta_tm_st :: TmState
delta_tm_st = SharedDIdEnv VarInfo -> CoreMap Id -> TmState
TmSt (SharedDIdEnv VarInfo -> Id -> Id -> SharedDIdEnv VarInfo
forall a. SharedDIdEnv a -> Id -> Id -> SharedDIdEnv a
setIndirectSDIE SharedDIdEnv VarInfo
env Id
x Id
y) CoreMap Id
reps })
      (Maybe VarInfo
_, Maybe VarInfo
Nothing) -> Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Delta
delta{ delta_tm_st :: TmState
delta_tm_st = SharedDIdEnv VarInfo -> CoreMap Id -> TmState
TmSt (SharedDIdEnv VarInfo -> Id -> Id -> SharedDIdEnv VarInfo
forall a. SharedDIdEnv a -> Id -> Id -> SharedDIdEnv a
setIndirectSDIE SharedDIdEnv VarInfo
env Id
y Id
x) CoreMap Id
reps })
      -- Merge the info we have for x into the info for y
      (Just VarInfo
vi_x, Just VarInfo
vi_y) -> do
        -- This assert will probably trigger at some point...
        -- We should decide how to break the tie
        MASSERT2( vi_ty vi_x `eqType` vi_ty vi_y, text "Not same type" )
        -- First assume that x and y are in the same equivalence class
        let env_ind :: SharedDIdEnv VarInfo
env_ind = SharedDIdEnv VarInfo -> Id -> Id -> SharedDIdEnv VarInfo
forall a. SharedDIdEnv a -> Id -> Id -> SharedDIdEnv a
setIndirectSDIE SharedDIdEnv VarInfo
env Id
x Id
y
        -- Then sum up the refinement counters
        let env_refs :: SharedDIdEnv VarInfo
env_refs = SharedDIdEnv VarInfo -> Id -> VarInfo -> SharedDIdEnv VarInfo
forall a. SharedDIdEnv a -> Id -> a -> SharedDIdEnv a
setEntrySDIE SharedDIdEnv VarInfo
env_ind Id
y VarInfo
vi_y
        let delta_refs :: Delta
delta_refs = Delta
delta{ delta_tm_st :: TmState
delta_tm_st = SharedDIdEnv VarInfo -> CoreMap Id -> TmState
TmSt SharedDIdEnv VarInfo
env_refs CoreMap Id
reps }
        -- and then gradually merge every positive fact we have on x into y
        let add_fact :: Delta
-> (PmAltCon, [Id]) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
add_fact Delta
delta (PmAltCon
cl, [Id]
args) = Delta
-> Id
-> PmAltCon
-> [Id]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarConCt Delta
delta Id
y PmAltCon
cl [Id]
args
        Delta
delta_pos <- (Delta
 -> (PmAltCon, [Id])
 -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> Delta
-> [(PmAltCon, [Id])]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM Delta
-> (PmAltCon, [Id]) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
add_fact Delta
delta_refs (VarInfo -> [(PmAltCon, [Id])]
vi_pos VarInfo
vi_x)
        -- Do the same for negative info
        let add_refut :: Delta -> PmAltCon -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
add_refut Delta
delta PmAltCon
nalt = DsM (Maybe Delta) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (m :: * -> *) a. m (Maybe a) -> MaybeT m a
MaybeT (Delta -> Id -> PmAltCon -> DsM (Maybe Delta)
addRefutableAltCon Delta
delta Id
y PmAltCon
nalt)
        Delta
delta_neg <- (Delta -> PmAltCon -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> Delta
-> [PmAltCon]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM Delta -> PmAltCon -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
add_refut Delta
delta_pos (VarInfo -> [PmAltCon]
vi_neg VarInfo
vi_x)
        -- vi_cache will be updated in addRefutableAltCon, so we are good to
        -- go!
        Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a. Applicative f => a -> f a
pure Delta
delta_neg

-- | @addVarConCt x alt args ts@ extends the substitution with a solution
-- @x :-> (alt, args)@ if compatible with refutable shapes of @x@ and its
-- other solutions, reject (@Nothing@) otherwise.
--
-- See Note [TmState invariants].
addVarConCt :: Delta -> Id -> PmAltCon -> [Id] -> MaybeT DsM Delta
addVarConCt :: Delta
-> Id
-> PmAltCon
-> [Id]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarConCt delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = TmSt SharedDIdEnv VarInfo
env CoreMap Id
reps } Id
x PmAltCon
alt [Id]
args = do
  VI Type
ty [(PmAltCon, [Id])]
pos [PmAltCon]
neg PossibleMatches
cache <- DsM VarInfo -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) VarInfo
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Delta -> Id -> DsM VarInfo
initLookupVarInfo Delta
delta Id
x)
  -- First try to refute with a negative fact
  Bool -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard ((PmAltCon -> Bool) -> [PmAltCon] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((PmEquality -> PmEquality -> Bool
forall a. Eq a => a -> a -> Bool
/= PmEquality
Equal) (PmEquality -> Bool)
-> (PmAltCon -> PmEquality) -> PmAltCon -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PmAltCon -> PmAltCon -> PmEquality
eqPmAltCon PmAltCon
alt) [PmAltCon]
neg)
  -- Then see if any of the other solutions (remember: each of them is an
  -- additional refinement of the possible values x could take) indicate a
  -- contradiction
  Bool -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (((PmAltCon, [Id]) -> Bool) -> [(PmAltCon, [Id])] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((PmEquality -> PmEquality -> Bool
forall a. Eq a => a -> a -> Bool
/= PmEquality
Disjoint) (PmEquality -> Bool)
-> ((PmAltCon, [Id]) -> PmEquality) -> (PmAltCon, [Id]) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PmAltCon -> PmAltCon -> PmEquality
eqPmAltCon PmAltCon
alt (PmAltCon -> PmEquality)
-> ((PmAltCon, [Id]) -> PmAltCon) -> (PmAltCon, [Id]) -> PmEquality
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PmAltCon, [Id]) -> PmAltCon
forall a b. (a, b) -> a
fst) [(PmAltCon, [Id])]
pos)
  -- Now we should be good! Add (alt, args) as a possible solution, or refine an
  -- existing one
  case ((PmAltCon, [Id]) -> Bool)
-> [(PmAltCon, [Id])] -> Maybe (PmAltCon, [Id])
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((PmEquality -> PmEquality -> Bool
forall a. Eq a => a -> a -> Bool
== PmEquality
Equal) (PmEquality -> Bool)
-> ((PmAltCon, [Id]) -> PmEquality) -> (PmAltCon, [Id]) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PmAltCon -> PmAltCon -> PmEquality
eqPmAltCon PmAltCon
alt (PmAltCon -> PmEquality)
-> ((PmAltCon, [Id]) -> PmAltCon) -> (PmAltCon, [Id]) -> PmEquality
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PmAltCon, [Id]) -> PmAltCon
forall a b. (a, b) -> a
fst) [(PmAltCon, [Id])]
pos of
    Just (PmAltCon
_, [Id]
other_args) -> do
      (Delta -> (Id, Id) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> Delta
-> [(Id, Id)]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM Delta -> (Id, Id) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarVarCt Delta
delta ([Id] -> [Id] -> [(Id, Id)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Id]
args [Id]
other_args)
    Maybe (PmAltCon, [Id])
Nothing -> do
      -- Filter out redundant negative facts (those that compare Just False to
      -- the new solution)
      let neg' :: [PmAltCon]
neg' = (PmAltCon -> Bool) -> [PmAltCon] -> [PmAltCon]
forall a. (a -> Bool) -> [a] -> [a]
filter ((PmEquality -> PmEquality -> Bool
forall a. Eq a => a -> a -> Bool
== PmEquality
PossiblyOverlap) (PmEquality -> Bool)
-> (PmAltCon -> PmEquality) -> PmAltCon -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PmAltCon -> PmAltCon -> PmEquality
eqPmAltCon PmAltCon
alt) [PmAltCon]
neg
      let pos' :: [(PmAltCon, [Id])]
pos' = (PmAltCon
alt,[Id]
args)(PmAltCon, [Id]) -> [(PmAltCon, [Id])] -> [(PmAltCon, [Id])]
forall a. a -> [a] -> [a]
:[(PmAltCon, [Id])]
pos
      Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (f :: * -> *) a. Applicative f => a -> f a
pure Delta
delta{ delta_tm_st :: TmState
delta_tm_st = SharedDIdEnv VarInfo -> CoreMap Id -> TmState
TmSt (SharedDIdEnv VarInfo -> Id -> VarInfo -> SharedDIdEnv VarInfo
forall a. SharedDIdEnv a -> Id -> a -> SharedDIdEnv a
setEntrySDIE SharedDIdEnv VarInfo
env Id
x (Type
-> [(PmAltCon, [Id])] -> [PmAltCon] -> PossibleMatches -> VarInfo
VI Type
ty [(PmAltCon, [Id])]
pos' [PmAltCon]
neg' PossibleMatches
cache)) CoreMap Id
reps}

----------------------------------------
-- * Enumerating inhabitation candidates

-- | Information about a conlike that is relevant to coverage checking.
-- It is called an \"inhabitation candidate\" since it is a value which may
-- possibly inhabit some type, but only if its term constraints ('ic_tm_cs')
-- and type constraints ('ic_ty_cs') are permitting, and if all of its strict
-- argument types ('ic_strict_arg_tys') are inhabitable.
-- See @Note [Strict argument type constraints]@.
data InhabitationCandidate =
  InhabitationCandidate
  { InhabitationCandidate -> Bag TmCt
ic_tm_cs          :: Bag TmCt
  , InhabitationCandidate -> Bag TyCt
ic_ty_cs          :: Bag TyCt
  , InhabitationCandidate -> [Type]
ic_strict_arg_tys :: [Type]
  }

instance Outputable InhabitationCandidate where
  ppr :: InhabitationCandidate -> SDoc
ppr (InhabitationCandidate Bag TmCt
tm_cs Bag TyCt
ty_cs [Type]
strict_arg_tys) =
    String -> SDoc
text String
"InhabitationCandidate" SDoc -> SDoc -> SDoc
<+>
      [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"ic_tm_cs          =" SDoc -> SDoc -> SDoc
<+> Bag TmCt -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TmCt
tm_cs
           , String -> SDoc
text String
"ic_ty_cs          =" SDoc -> SDoc -> SDoc
<+> Bag TyCt -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TyCt
ty_cs
           , String -> SDoc
text String
"ic_strict_arg_tys =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
strict_arg_tys ]

mkInhabitationCandidate :: Id -> DataCon -> DsM InhabitationCandidate
-- Precondition: idType x is a TyConApp, so that tyConAppArgs in here is safe.
mkInhabitationCandidate :: Id -> DataCon -> DsM InhabitationCandidate
mkInhabitationCandidate Id
x DataCon
dc = do
  let cl :: ConLike
cl = DataCon -> ConLike
RealDataCon DataCon
dc
  let tc_args :: [Type]
tc_args = Type -> [Type]
tyConAppArgs (Id -> Type
idType Id
x)
  ([Id]
arg_vars, Bag TyCt
ty_cs, [Type]
strict_arg_tys) <- [Type] -> ConLike -> DsM ([Id], Bag TyCt, [Type])
mkOneConFull [Type]
tc_args ConLike
cl
  InhabitationCandidate -> DsM InhabitationCandidate
forall (f :: * -> *) a. Applicative f => a -> f a
pure InhabitationCandidate :: Bag TmCt -> Bag TyCt -> [Type] -> InhabitationCandidate
InhabitationCandidate
        { ic_tm_cs :: Bag TmCt
ic_tm_cs = TmCt -> Bag TmCt
forall a. a -> Bag a
unitBag (Id -> PmAltCon -> [Id] -> TmCt
TmVarCon Id
x (ConLike -> PmAltCon
PmAltConLike ConLike
cl) [Id]
arg_vars)
        , ic_ty_cs :: Bag TyCt
ic_ty_cs = Bag TyCt
ty_cs
        , ic_strict_arg_tys :: [Type]
ic_strict_arg_tys = [Type]
strict_arg_tys
        }

-- | Generate all 'InhabitationCandidate's for a given type. The result is
-- either @'Left' ty@, if the type cannot be reduced to a closed algebraic type
-- (or if it's one trivially inhabited, like 'Int'), or @'Right' candidates@,
-- if it can. In this case, the candidates are the signature of the tycon, each
-- one accompanied by the term- and type- constraints it gives rise to.
-- See also Note [Checking EmptyCase Expressions]
inhabitationCandidates :: Delta -> Type
                       -> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
inhabitationCandidates :: Delta
-> Type -> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
inhabitationCandidates MkDelta{ delta_ty_st :: Delta -> TyState
delta_ty_st = TyState
ty_st } Type
ty = do
  TyState -> Type -> DsM TopNormaliseTypeResult
pmTopNormaliseType TyState
ty_st Type
ty DsM TopNormaliseTypeResult
-> (TopNormaliseTypeResult
    -> DsM (Either Type (TyCon, Id, [InhabitationCandidate])))
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    NoChange Type
_                    -> Type
-> Type
-> [(Type, DataCon, Type)]
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
alts_to_check Type
ty     Type
ty      []
    NormalisedByConstraints Type
ty'   -> Type
-> Type
-> [(Type, DataCon, Type)]
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
alts_to_check Type
ty'    Type
ty'     []
    HadRedexes Type
src_ty [(Type, DataCon, Type)]
dcs Type
core_ty -> Type
-> Type
-> [(Type, DataCon, Type)]
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
alts_to_check Type
src_ty Type
core_ty [(Type, DataCon, Type)]
dcs
  where
    build_newtype :: (Type, DataCon, Type) -> Id -> DsM (Id, TmCt)
    build_newtype :: (Type, DataCon, Type) -> Id -> DsM (Id, TmCt)
build_newtype (Type
ty, DataCon
dc, Type
_arg_ty) Id
x = do
      -- ty is the type of @dc x@. It's a @dataConTyCon dc@ application.
      Id
y <- Type -> DsM Id
mkPmId Type
ty
      (Id, TmCt) -> DsM (Id, TmCt)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Id
y, Id -> PmAltCon -> [Id] -> TmCt
TmVarCon Id
y (ConLike -> PmAltCon
PmAltConLike (DataCon -> ConLike
RealDataCon DataCon
dc)) [Id
x])

    build_newtypes :: Id -> [(Type, DataCon, Type)] -> DsM (Id, [TmCt])
    build_newtypes :: Id -> [(Type, DataCon, Type)] -> DsM (Id, [TmCt])
build_newtypes Id
x = ((Type, DataCon, Type) -> (Id, [TmCt]) -> DsM (Id, [TmCt]))
-> (Id, [TmCt]) -> [(Type, DataCon, Type)] -> DsM (Id, [TmCt])
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> b -> m b) -> b -> t a -> m b
foldrM (\(Type, DataCon, Type)
dc (Id
x, [TmCt]
cts) -> (Type, DataCon, Type) -> Id -> [TmCt] -> DsM (Id, [TmCt])
go (Type, DataCon, Type)
dc Id
x [TmCt]
cts) (Id
x, [])
      where
        go :: (Type, DataCon, Type) -> Id -> [TmCt] -> DsM (Id, [TmCt])
go (Type, DataCon, Type)
dc Id
x [TmCt]
cts = (TmCt -> [TmCt]) -> (Id, TmCt) -> (Id, [TmCt])
forall (p :: * -> * -> *) b c a.
Bifunctor p =>
(b -> c) -> p a b -> p a c
second (TmCt -> [TmCt] -> [TmCt]
forall a. a -> [a] -> [a]
:[TmCt]
cts) ((Id, TmCt) -> (Id, [TmCt])) -> DsM (Id, TmCt) -> DsM (Id, [TmCt])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Type, DataCon, Type) -> Id -> DsM (Id, TmCt)
build_newtype (Type, DataCon, Type)
dc Id
x

    -- Inhabitation candidates, using the result of pmTopNormaliseType
    alts_to_check :: Type -> Type -> [(Type, DataCon, Type)]
                  -> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
    alts_to_check :: Type
-> Type
-> [(Type, DataCon, Type)]
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
alts_to_check Type
src_ty Type
core_ty [(Type, DataCon, Type)]
dcs = case HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe Type
core_ty of
      Just (TyCon
tc, [Type]
_)
        |  TyCon -> Bool
isTyConTriviallyInhabited TyCon
tc
        -> case [(Type, DataCon, Type)]
dcs of
             []    -> Either Type (TyCon, Id, [InhabitationCandidate])
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Either Type (TyCon, Id, [InhabitationCandidate])
forall a b. a -> Either a b
Left Type
src_ty)
             ((Type, DataCon, Type)
_:[(Type, DataCon, Type)]
_) -> do Id
inner <- Type -> DsM Id
mkPmId Type
core_ty
                         (Id
outer, [TmCt]
new_tm_cts) <- Id -> [(Type, DataCon, Type)] -> DsM (Id, [TmCt])
build_newtypes Id
inner [(Type, DataCon, Type)]
dcs
                         Either Type (TyCon, Id, [InhabitationCandidate])
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
forall (m :: * -> *) a. Monad m => a -> m a
return (Either Type (TyCon, Id, [InhabitationCandidate])
 -> DsM (Either Type (TyCon, Id, [InhabitationCandidate])))
-> Either Type (TyCon, Id, [InhabitationCandidate])
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
forall a b. (a -> b) -> a -> b
$ (TyCon, Id, [InhabitationCandidate])
-> Either Type (TyCon, Id, [InhabitationCandidate])
forall a b. b -> Either a b
Right (TyCon
tc, Id
outer, [InhabitationCandidate :: Bag TmCt -> Bag TyCt -> [Type] -> InhabitationCandidate
InhabitationCandidate
                           { ic_tm_cs :: Bag TmCt
ic_tm_cs = [TmCt] -> Bag TmCt
forall a. [a] -> Bag a
listToBag [TmCt]
new_tm_cts
                           , ic_ty_cs :: Bag TyCt
ic_ty_cs = Bag TyCt
forall a. Bag a
emptyBag, ic_strict_arg_tys :: [Type]
ic_strict_arg_tys = [] }])

        |  Type -> Bool
pmIsClosedType Type
core_ty Bool -> Bool -> Bool
&& Bool -> Bool
not (TyCon -> Bool
isAbstractTyCon TyCon
tc)
           -- Don't consider abstract tycons since we don't know what their
           -- constructors are, which makes the results of coverage checking
           -- them extremely misleading.
        -> do
             Id
inner <- Type -> DsM Id
mkPmId Type
core_ty -- it would be wrong to unify inner
             [InhabitationCandidate]
alts <- (DataCon -> DsM InhabitationCandidate)
-> [DataCon]
-> IOEnv (Env DsGblEnv DsLclEnv) [InhabitationCandidate]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Id -> DataCon -> DsM InhabitationCandidate
mkInhabitationCandidate Id
inner) (TyCon -> [DataCon]
tyConDataCons TyCon
tc)
             (Id
outer, [TmCt]
new_tm_cts) <- Id -> [(Type, DataCon, Type)] -> DsM (Id, [TmCt])
build_newtypes Id
inner [(Type, DataCon, Type)]
dcs
             let wrap_dcs :: InhabitationCandidate -> InhabitationCandidate
wrap_dcs InhabitationCandidate
alt = InhabitationCandidate
alt{ ic_tm_cs :: Bag TmCt
ic_tm_cs = [TmCt] -> Bag TmCt
forall a. [a] -> Bag a
listToBag [TmCt]
new_tm_cts Bag TmCt -> Bag TmCt -> Bag TmCt
forall a. Bag a -> Bag a -> Bag a
`unionBags` InhabitationCandidate -> Bag TmCt
ic_tm_cs InhabitationCandidate
alt}
             Either Type (TyCon, Id, [InhabitationCandidate])
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
forall (m :: * -> *) a. Monad m => a -> m a
return (Either Type (TyCon, Id, [InhabitationCandidate])
 -> DsM (Either Type (TyCon, Id, [InhabitationCandidate])))
-> Either Type (TyCon, Id, [InhabitationCandidate])
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
forall a b. (a -> b) -> a -> b
$ (TyCon, Id, [InhabitationCandidate])
-> Either Type (TyCon, Id, [InhabitationCandidate])
forall a b. b -> Either a b
Right (TyCon
tc, Id
outer, (InhabitationCandidate -> InhabitationCandidate)
-> [InhabitationCandidate] -> [InhabitationCandidate]
forall a b. (a -> b) -> [a] -> [b]
map InhabitationCandidate -> InhabitationCandidate
wrap_dcs [InhabitationCandidate]
alts)
      -- For other types conservatively assume that they are inhabited.
      Maybe (TyCon, [Type])
_other -> Either Type (TyCon, Id, [InhabitationCandidate])
-> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
forall (m :: * -> *) a. Monad m => a -> m a
return (Type -> Either Type (TyCon, Id, [InhabitationCandidate])
forall a b. a -> Either a b
Left Type
src_ty)

-- | All these types are trivially inhabited
triviallyInhabitedTyCons :: UniqSet TyCon
triviallyInhabitedTyCons :: UniqSet TyCon
triviallyInhabitedTyCons = [TyCon] -> UniqSet TyCon
forall a. Uniquable a => [a] -> UniqSet a
mkUniqSet [
    TyCon
charTyCon, TyCon
doubleTyCon, TyCon
floatTyCon, TyCon
intTyCon, TyCon
wordTyCon, TyCon
word8TyCon
  ]

isTyConTriviallyInhabited :: TyCon -> Bool
isTyConTriviallyInhabited :: TyCon -> Bool
isTyConTriviallyInhabited TyCon
tc = TyCon -> UniqSet TyCon -> Bool
forall a. Uniquable a => a -> UniqSet a -> Bool
elementOfUniqSet TyCon
tc UniqSet TyCon
triviallyInhabitedTyCons

----------------------------
-- * Detecting vacuous types

{- Note [Checking EmptyCase Expressions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Empty case expressions are strict on the scrutinee. That is, `case x of {}`
will force argument `x`. Hence, `checkMatches` is not sufficient for checking
empty cases, because it assumes that the match is not strict (which is true
for all other cases, apart from EmptyCase). This gave rise to #10746. Instead,
we do the following:

1. We normalise the outermost type family redex, data family redex or newtype,
   using pmTopNormaliseType (in types/FamInstEnv.hs). This computes 3
   things:
   (a) A normalised type src_ty, which is equal to the type of the scrutinee in
       source Haskell (does not normalise newtypes or data families)
   (b) The actual normalised type core_ty, which coincides with the result
       topNormaliseType_maybe. This type is not necessarily equal to the input
       type in source Haskell. And this is precicely the reason we compute (a)
       and (c): the reasoning happens with the underlying types, but both the
       patterns and types we print should respect newtypes and also show the
       family type constructors and not the representation constructors.

   (c) A list of all newtype data constructors dcs, each one corresponding to a
       newtype rewrite performed in (b).

   For an example see also Note [Type normalisation]
   in types/FamInstEnv.hs.

2. Function Check.checkEmptyCase' performs the check:
   - If core_ty is not an algebraic type, then we cannot check for
     inhabitation, so we emit (_ :: src_ty) as missing, conservatively assuming
     that the type is inhabited.
   - If core_ty is an algebraic type, then we unfold the scrutinee to all
     possible constructor patterns, using inhabitationCandidates, and then
     check each one for constraint satisfiability, same as we do for normal
     pattern match checking.
-}

-- | A 'SatisfiabilityCheck' based on "NonVoid ty" constraints, e.g. Will
-- check if the @strict_arg_tys@ are actually all inhabited.
-- Returns the old 'Delta' if all the types are non-void according to 'Delta'.
tysAreNonVoid :: RecTcChecker -> [Type] -> SatisfiabilityCheck
tysAreNonVoid :: RecTcChecker -> [Type] -> SatisfiabilityCheck
tysAreNonVoid RecTcChecker
rec_env [Type]
strict_arg_tys = (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
SC ((Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck)
-> (Delta -> DsM (Maybe Delta)) -> SatisfiabilityCheck
forall a b. (a -> b) -> a -> b
$ \Delta
delta -> do
  Bool
all_non_void <- RecTcChecker
-> Delta -> [Type] -> IOEnv (Env DsGblEnv DsLclEnv) Bool
checkAllNonVoid RecTcChecker
rec_env Delta
delta [Type]
strict_arg_tys
  -- Check if each strict argument type is inhabitable
  Maybe Delta -> DsM (Maybe Delta)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Delta -> DsM (Maybe Delta))
-> Maybe Delta -> DsM (Maybe Delta)
forall a b. (a -> b) -> a -> b
$ if Bool
all_non_void
            then Delta -> Maybe Delta
forall a. a -> Maybe a
Just Delta
delta
            else Maybe Delta
forall a. Maybe a
Nothing

-- | Implements two performance optimizations, as described in
-- @Note [Strict argument type constraints]@.
checkAllNonVoid :: RecTcChecker -> Delta -> [Type] -> DsM Bool
checkAllNonVoid :: RecTcChecker
-> Delta -> [Type] -> IOEnv (Env DsGblEnv DsLclEnv) Bool
checkAllNonVoid RecTcChecker
rec_ts Delta
amb_cs [Type]
strict_arg_tys = do
  let definitely_inhabited :: Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool
definitely_inhabited = TyState -> Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool
definitelyInhabitedType (Delta -> TyState
delta_ty_st Delta
amb_cs)
  [Type]
tys_to_check <- (Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool)
-> [Type] -> IOEnv (Env DsGblEnv DsLclEnv) [Type]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterOutM Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool
definitely_inhabited [Type]
strict_arg_tys
  -- See Note [Fuel for the inhabitation test]
  let rec_max_bound :: Int
rec_max_bound | [Type]
tys_to_check [Type] -> Int -> Bool
forall a. [a] -> Int -> Bool
`lengthExceeds` Int
1
                    = Int
1
                    | Bool
otherwise
                    = Int
3
      rec_ts' :: RecTcChecker
rec_ts' = Int -> RecTcChecker -> RecTcChecker
setRecTcMaxBound Int
rec_max_bound RecTcChecker
rec_ts
  (Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool)
-> [Type] -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (m :: * -> *) a. Monad m => (a -> m Bool) -> [a] -> m Bool
allM (RecTcChecker -> Delta -> Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool
nonVoid RecTcChecker
rec_ts' Delta
amb_cs) [Type]
tys_to_check

-- | Checks if a strict argument type of a conlike is inhabitable by a
-- terminating value (i.e, an 'InhabitationCandidate').
-- See @Note [Strict argument type constraints]@.
nonVoid
  :: RecTcChecker -- ^ The per-'TyCon' recursion depth limit.
  -> Delta        -- ^ The ambient term/type constraints (known to be
                  --   satisfiable).
  -> Type         -- ^ The strict argument type.
  -> DsM Bool     -- ^ 'True' if the strict argument type might be inhabited by
                  --   a terminating value (i.e., an 'InhabitationCandidate').
                  --   'False' if it is definitely uninhabitable by anything
                  --   (except bottom).
nonVoid :: RecTcChecker -> Delta -> Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool
nonVoid RecTcChecker
rec_ts Delta
amb_cs Type
strict_arg_ty = do
  Either Type (TyCon, Id, [InhabitationCandidate])
mb_cands <- Delta
-> Type -> DsM (Either Type (TyCon, Id, [InhabitationCandidate]))
inhabitationCandidates Delta
amb_cs Type
strict_arg_ty
  case Either Type (TyCon, Id, [InhabitationCandidate])
mb_cands of
    Right (TyCon
tc, Id
_, [InhabitationCandidate]
cands)
      -- See Note [Fuel for the inhabitation test]
      |  Just RecTcChecker
rec_ts' <- RecTcChecker -> TyCon -> Maybe RecTcChecker
checkRecTc RecTcChecker
rec_ts TyCon
tc
      -> (InhabitationCandidate -> IOEnv (Env DsGblEnv DsLclEnv) Bool)
-> [InhabitationCandidate] -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (m :: * -> *) a. Monad m => (a -> m Bool) -> [a] -> m Bool
anyM (RecTcChecker
-> Delta
-> InhabitationCandidate
-> IOEnv (Env DsGblEnv DsLclEnv) Bool
cand_is_inhabitable RecTcChecker
rec_ts' Delta
amb_cs) [InhabitationCandidate]
cands
           -- A strict argument type is inhabitable by a terminating value if
           -- at least one InhabitationCandidate is inhabitable.
    Either Type (TyCon, Id, [InhabitationCandidate])
_ -> Bool -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
           -- Either the type is trivially inhabited or we have exceeded the
           -- recursion depth for some TyCon (so bail out and conservatively
           -- claim the type is inhabited).
  where
    -- Checks if an InhabitationCandidate for a strict argument type:
    --
    -- (1) Has satisfiable term and type constraints.
    -- (2) Has 'nonVoid' strict argument types (we bail out of this
    --     check if recursion is detected).
    --
    -- See Note [Strict argument type constraints]
    cand_is_inhabitable :: RecTcChecker -> Delta
                        -> InhabitationCandidate -> DsM Bool
    cand_is_inhabitable :: RecTcChecker
-> Delta
-> InhabitationCandidate
-> IOEnv (Env DsGblEnv DsLclEnv) Bool
cand_is_inhabitable RecTcChecker
rec_ts Delta
amb_cs
      (InhabitationCandidate{ ic_tm_cs :: InhabitationCandidate -> Bag TmCt
ic_tm_cs          = Bag TmCt
new_tm_cs
                            , ic_ty_cs :: InhabitationCandidate -> Bag TyCt
ic_ty_cs          = Bag TyCt
new_ty_cs
                            , ic_strict_arg_tys :: InhabitationCandidate -> [Type]
ic_strict_arg_tys = [Type]
new_strict_arg_tys }) =
        (Maybe Delta -> Bool)
-> DsM (Maybe Delta) -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Maybe Delta -> Bool
forall a. Maybe a -> Bool
isJust (DsM (Maybe Delta) -> IOEnv (Env DsGblEnv DsLclEnv) Bool)
-> DsM (Maybe Delta) -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall a b. (a -> b) -> a -> b
$ Delta -> SatisfiabilityCheck -> DsM (Maybe Delta)
runSatisfiabilityCheck Delta
amb_cs (SatisfiabilityCheck -> DsM (Maybe Delta))
-> SatisfiabilityCheck -> DsM (Maybe Delta)
forall a b. (a -> b) -> a -> b
$ [SatisfiabilityCheck] -> SatisfiabilityCheck
forall a. Monoid a => [a] -> a
mconcat
          [ Bool -> Bag TyCt -> SatisfiabilityCheck
tyIsSatisfiable Bool
False Bag TyCt
new_ty_cs
          , Bag TmCt -> SatisfiabilityCheck
tmIsSatisfiable Bag TmCt
new_tm_cs
          , RecTcChecker -> [Type] -> SatisfiabilityCheck
tysAreNonVoid RecTcChecker
rec_ts [Type]
new_strict_arg_tys
          ]

-- | @'definitelyInhabitedType' ty@ returns 'True' if @ty@ has at least one
-- constructor @C@ such that:
--
-- 1. @C@ has no equality constraints.
-- 2. @C@ has no strict argument types.
--
-- See the @Note [Strict argument type constraints]@.
definitelyInhabitedType :: TyState -> Type -> DsM Bool
definitelyInhabitedType :: TyState -> Type -> IOEnv (Env DsGblEnv DsLclEnv) Bool
definitelyInhabitedType TyState
ty_st Type
ty = do
  TopNormaliseTypeResult
res <- TyState -> Type -> DsM TopNormaliseTypeResult
pmTopNormaliseType TyState
ty_st Type
ty
  Bool -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Bool -> IOEnv (Env DsGblEnv DsLclEnv) Bool)
-> Bool -> IOEnv (Env DsGblEnv DsLclEnv) Bool
forall a b. (a -> b) -> a -> b
$ case TopNormaliseTypeResult
res of
           HadRedexes Type
_ [(Type, DataCon, Type)]
cons Type
_ -> ((Type, DataCon, Type) -> Bool) -> [(Type, DataCon, Type)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Type, DataCon, Type) -> Bool
meets_criteria [(Type, DataCon, Type)]
cons
           TopNormaliseTypeResult
_                   -> Bool
False
  where
    meets_criteria :: (Type, DataCon, Type) -> Bool
    meets_criteria :: (Type, DataCon, Type) -> Bool
meets_criteria (Type
_, DataCon
con, Type
_) =
      [EqSpec] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (DataCon -> [EqSpec]
dataConEqSpec DataCon
con) Bool -> Bool -> Bool
&& -- (1)
      [HsImplBang] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (DataCon -> [HsImplBang]
dataConImplBangs DataCon
con) -- (2)

{- Note [Strict argument type constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the ConVar case of clause processing, each conlike K traditionally
generates two different forms of constraints:

* A term constraint (e.g., x ~ K y1 ... yn)
* Type constraints from the conlike's context (e.g., if K has type
  forall bs. Q => s1 .. sn -> T tys, then Q would be its type constraints)

As it turns out, these alone are not enough to detect a certain class of
unreachable code. Consider the following example (adapted from #15305):

  data K = K1 | K2 !Void

  f :: K -> ()
  f K1 = ()

Even though `f` doesn't match on `K2`, `f` is exhaustive in its patterns. Why?
Because it's impossible to construct a terminating value of type `K` using the
`K2` constructor, and thus it's impossible for `f` to ever successfully match
on `K2`.

The reason is because `K2`'s field of type `Void` is //strict//. Because there
are no terminating values of type `Void`, any attempt to construct something
using `K2` will immediately loop infinitely or throw an exception due to the
strictness annotation. (If the field were not strict, then `f` could match on,
say, `K2 undefined` or `K2 (let x = x in x)`.)

Since neither the term nor type constraints mentioned above take strict
argument types into account, we make use of the `nonVoid` function to
determine whether a strict type is inhabitable by a terminating value or not.
We call this the "inhabitation test".

`nonVoid ty` returns True when either:
1. `ty` has at least one InhabitationCandidate for which both its term and type
   constraints are satifiable, and `nonVoid` returns `True` for all of the
   strict argument types in that InhabitationCandidate.
2. We're unsure if it's inhabited by a terminating value.

`nonVoid ty` returns False when `ty` is definitely uninhabited by anything
(except bottom). Some examples:

* `nonVoid Void` returns False, since Void has no InhabitationCandidates.
  (This is what lets us discard the `K2` constructor in the earlier example.)
* `nonVoid (Int :~: Int)` returns True, since it has an InhabitationCandidate
  (through the Refl constructor), and its term constraint (x ~ Refl) and
  type constraint (Int ~ Int) are satisfiable.
* `nonVoid (Int :~: Bool)` returns False. Although it has an
  InhabitationCandidate (by way of Refl), its type constraint (Int ~ Bool) is
  not satisfiable.
* Given the following definition of `MyVoid`:

    data MyVoid = MkMyVoid !Void

  `nonVoid MyVoid` returns False. The InhabitationCandidate for the MkMyVoid
  constructor contains Void as a strict argument type, and since `nonVoid Void`
  returns False, that InhabitationCandidate is discarded, leaving no others.
* Whether or not a type is inhabited is undecidable in general.
  See Note [Fuel for the inhabitation test].
* For some types, inhabitation is evident immediately and we don't need to
  perform expensive tests. See Note [Types that are definitely inhabitable].

Note [Fuel for the inhabitation test]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Whether or not a type is inhabited is undecidable in general. As a result, we
can run into infinite loops in `nonVoid`. Therefore, we adopt a fuel-based
approach to prevent that.

Consider the following example:

  data Abyss = MkAbyss !Abyss
  stareIntoTheAbyss :: Abyss -> a
  stareIntoTheAbyss x = case x of {}

In principle, stareIntoTheAbyss is exhaustive, since there is no way to
construct a terminating value using MkAbyss. However, both the term and type
constraints for MkAbyss are satisfiable, so the only way one could determine
that MkAbyss is unreachable is to check if `nonVoid Abyss` returns False.
There is only one InhabitationCandidate for Abyss—MkAbyss—and both its term
and type constraints are satisfiable, so we'd need to check if `nonVoid Abyss`
returns False... and now we've entered an infinite loop!

To avoid this sort of conundrum, `nonVoid` uses a simple test to detect the
presence of recursive types (through `checkRecTc`), and if recursion is
detected, we bail out and conservatively assume that the type is inhabited by
some terminating value. This avoids infinite loops at the expense of making
the coverage checker incomplete with respect to functions like
stareIntoTheAbyss above. Then again, the same problem occurs with recursive
newtypes, like in the following code:

  newtype Chasm = MkChasm Chasm
  gazeIntoTheChasm :: Chasm -> a
  gazeIntoTheChasm x = case x of {} -- Erroneously warned as non-exhaustive

So this limitation is somewhat understandable.

Note that even with this recursion detection, there is still a possibility that
`nonVoid` can run in exponential time. Consider the following data type:

  data T = MkT !T !T !T

If we call `nonVoid` on each of its fields, that will require us to once again
check if `MkT` is inhabitable in each of those three fields, which in turn will
require us to check if `MkT` is inhabitable again... As you can see, the
branching factor adds up quickly, and if the recursion depth limit is, say,
100, then `nonVoid T` will effectively take forever.

To mitigate this, we check the branching factor every time we are about to call
`nonVoid` on a list of strict argument types. If the branching factor exceeds 1
(i.e., if there is potential for exponential runtime), then we limit the
maximum recursion depth to 1 to mitigate the problem. If the branching factor
is exactly 1 (i.e., we have a linear chain instead of a tree), then it's okay
to stick with a larger maximum recursion depth.

In #17977 we saw that the defaultRecTcMaxBound (100 at the time of writing) was
too large and had detrimental effect on performance of the coverage checker.
Given that we only commit to a best effort anyway, we decided to substantially
decrement the recursion depth to 3, at the cost of precision in some edge cases
like

  data Nat = Z | S Nat
  data Down :: Nat -> Type where
    Down :: !(Down n) -> Down (S n)
  f :: Down (S (S (S (S (S Z))))) -> ()
  f x = case x of {}

Since the coverage won't bother to instantiate Down 4 levels deep to see that it
is in fact uninhabited, it will emit a inexhaustivity warning for the case.

Note [Types that are definitely inhabitable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Another microoptimization applies to data types like this one:

  data S a = S ![a] !T

Even though there is a strict field of type [a], it's quite silly to call
nonVoid on it, since it's "obvious" that it is inhabitable. To make this
intuition formal, we say that a type is definitely inhabitable (DI) if:

  * It has at least one constructor C such that:
    1. C has no equality constraints (since they might be unsatisfiable)
    2. C has no strict argument types (since they might be uninhabitable)

It's relatively cheap to check if a type is DI, so before we call `nonVoid`
on a list of strict argument types, we filter out all of the DI ones.
-}

--------------------------------------------
-- * Providing positive evidence for a Delta

-- | @provideEvidence vs n delta@ returns a list of
-- at most @n@ (but perhaps empty) refinements of @delta@ that instantiate
-- @vs@ to compatible constructor applications or wildcards.
-- Negative information is only retained if literals are involved or when
-- for recursive GADTs.
provideEvidence :: [Id] -> Int -> Delta -> DsM [Delta]
provideEvidence :: [Id] -> Int -> Delta -> DsM [Delta]
provideEvidence = [Id] -> Int -> Delta -> DsM [Delta]
go
  where
    go :: [Id] -> Int -> Delta -> DsM [Delta]
go [Id]
_      Int
0 Delta
_     = [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
    go []     Int
_ Delta
delta = [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure [Delta
delta]
    go (Id
x:[Id]
xs) Int
n Delta
delta = do
      String -> SDoc -> DsM ()
tracePm String
"provideEvidence" (Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
x SDoc -> SDoc -> SDoc
$$ [Id] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Id]
xs SDoc -> SDoc -> SDoc
$$ Delta -> SDoc
forall a. Outputable a => a -> SDoc
ppr Delta
delta SDoc -> SDoc -> SDoc
$$ Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr Int
n)
      VI Type
_ [(PmAltCon, [Id])]
pos [PmAltCon]
neg PossibleMatches
_ <- Delta -> Id -> DsM VarInfo
initLookupVarInfo Delta
delta Id
x
      case [(PmAltCon, [Id])]
pos of
        (PmAltCon, [Id])
_:[(PmAltCon, [Id])]
_ -> do
          -- All solutions must be valid at once. Try to find candidates for their
          -- fields. Example:
          --   f x@(Just _) True = case x of SomePatSyn _ -> ()
          -- after this clause, we want to report that
          --   * @f Nothing _@ is uncovered
          --   * @f x False@ is uncovered
          -- where @x@ will have two possibly compatible solutions, @Just y@ for
          -- some @y@ and @SomePatSyn z@ for some @z@. We must find evidence for @y@
          -- and @z@ that is valid at the same time. These constitute arg_vas below.
          let arg_vas :: [Id]
arg_vas = ((PmAltCon, [Id]) -> [Id]) -> [(PmAltCon, [Id])] -> [Id]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\(PmAltCon
_cl, [Id]
args) -> [Id]
args) [(PmAltCon, [Id])]
pos
          [Id] -> Int -> Delta -> DsM [Delta]
go ([Id]
arg_vas [Id] -> [Id] -> [Id]
forall a. [a] -> [a] -> [a]
++ [Id]
xs) Int
n Delta
delta
        []
          -- When there are literals involved, just print negative info
          -- instead of listing missed constructors
          | [PmLit] -> Bool
forall a. [a] -> Bool
notNull [ PmLit
l | PmAltLit PmLit
l <- [PmAltCon]
neg ]
          -> [Id] -> Int -> Delta -> DsM [Delta]
go [Id]
xs Int
n Delta
delta
        [] -> Id -> [Id] -> Int -> Delta -> DsM [Delta]
try_instantiate Id
x [Id]
xs Int
n Delta
delta

    -- | Tries to instantiate a variable by possibly following the chain of
    -- newtypes and then instantiating to all ConLikes of the wrapped type's
    -- minimal residual COMPLETE set.
    try_instantiate :: Id -> [Id] -> Int -> Delta -> DsM [Delta]
    -- Convention: x binds the outer constructor in the chain, y the inner one.
    try_instantiate :: Id -> [Id] -> Int -> Delta -> DsM [Delta]
try_instantiate Id
x [Id]
xs Int
n Delta
delta = do
      (Type
_src_ty, [(Type, DataCon, Type)]
dcs, Type
core_ty) <- TopNormaliseTypeResult -> (Type, [(Type, DataCon, Type)], Type)
tntrGuts (TopNormaliseTypeResult -> (Type, [(Type, DataCon, Type)], Type))
-> DsM TopNormaliseTypeResult
-> IOEnv
     (Env DsGblEnv DsLclEnv) (Type, [(Type, DataCon, Type)], Type)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TyState -> Type -> DsM TopNormaliseTypeResult
pmTopNormaliseType (Delta -> TyState
delta_ty_st Delta
delta) (Id -> Type
idType Id
x)
      let build_newtype :: (Id, Delta)
-> (a, DataCon, Type)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta)
build_newtype (Id
x, Delta
delta) (a
_ty, DataCon
dc, Type
arg_ty) = do
            Id
y <- DsM Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Id
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (DsM Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Id)
-> DsM Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Id
forall a b. (a -> b) -> a -> b
$ Type -> DsM Id
mkPmId Type
arg_ty
            Delta
delta' <- Delta
-> Id
-> PmAltCon
-> [Id]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarConCt Delta
delta Id
x (ConLike -> PmAltCon
PmAltConLike (DataCon -> ConLike
RealDataCon DataCon
dc)) [Id
y]
            (Id, Delta) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Id
y, Delta
delta')
      MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta)
-> IOEnv (Env DsGblEnv DsLclEnv) (Maybe (Id, Delta))
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (((Id, Delta)
 -> (Type, DataCon, Type)
 -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta))
-> (Id, Delta)
-> [(Type, DataCon, Type)]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta)
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldlM (Id, Delta)
-> (Type, DataCon, Type)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta)
forall a.
(Id, Delta)
-> (a, DataCon, Type)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta)
build_newtype (Id
x, Delta
delta) [(Type, DataCon, Type)]
dcs) IOEnv (Env DsGblEnv DsLclEnv) (Maybe (Id, Delta))
-> (Maybe (Id, Delta) -> DsM [Delta]) -> DsM [Delta]
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Maybe (Id, Delta)
Nothing -> [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
        Just (Id
y, Delta
newty_delta) -> do
          -- Pick a COMPLETE set and instantiate it (n at max). Take care of ⊥.
          PossibleMatches
pm     <- VarInfo -> PossibleMatches
vi_cache (VarInfo -> PossibleMatches)
-> DsM VarInfo -> IOEnv (Env DsGblEnv DsLclEnv) PossibleMatches
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Delta -> Id -> DsM VarInfo
initLookupVarInfo Delta
newty_delta Id
y
          Maybe ConLikeSet
mb_cls <- Delta -> PossibleMatches -> DsM (Maybe ConLikeSet)
pickMinimalCompleteSet Delta
newty_delta PossibleMatches
pm
          case ConLikeSet -> [ConLike]
forall a. UniqDSet a -> [a]
uniqDSetToList (ConLikeSet -> [ConLike]) -> Maybe ConLikeSet -> Maybe [ConLike]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe ConLikeSet
mb_cls of
            Just cls :: [ConLike]
cls@(ConLike
_:[ConLike]
_) -> Id -> Type -> [Id] -> Int -> Delta -> [ConLike] -> DsM [Delta]
instantiate_cons Id
y Type
core_ty [Id]
xs Int
n Delta
newty_delta [ConLike]
cls
            Just [] | Bool -> Bool
not (Delta -> Id -> Bool
canDiverge Delta
newty_delta Id
y) -> [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
            -- Either ⊥ is still possible (think Void) or there are no COMPLETE
            -- sets available, so we can assume it's inhabited
            Maybe [ConLike]
_ -> [Id] -> Int -> Delta -> DsM [Delta]
go [Id]
xs Int
n Delta
newty_delta

    instantiate_cons :: Id -> Type -> [Id] -> Int -> Delta -> [ConLike] -> DsM [Delta]
    instantiate_cons :: Id -> Type -> [Id] -> Int -> Delta -> [ConLike] -> DsM [Delta]
instantiate_cons Id
_ Type
_  [Id]
_  Int
_ Delta
_     []       = [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
    instantiate_cons Id
_ Type
_  [Id]
_  Int
0 Delta
_     [ConLike]
_        = [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
    instantiate_cons Id
_ Type
ty [Id]
xs Int
n Delta
delta [ConLike]
_
      -- We don't want to expose users to GHC-specific constructors for Int etc.
      | ((TyCon, [Type]) -> Bool) -> Maybe (TyCon, [Type]) -> Maybe Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (TyCon -> Bool
isTyConTriviallyInhabited (TyCon -> Bool)
-> ((TyCon, [Type]) -> TyCon) -> (TyCon, [Type]) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TyCon, [Type]) -> TyCon
forall a b. (a, b) -> a
fst) (HasDebugCallStack => Type -> Maybe (TyCon, [Type])
Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe Type
ty) Maybe Bool -> Maybe Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
True
      = [Id] -> Int -> Delta -> DsM [Delta]
go [Id]
xs Int
n Delta
delta
    instantiate_cons Id
x Type
ty [Id]
xs Int
n Delta
delta (ConLike
cl:[ConLike]
cls) = do
      FamInstEnvs
env <- DsM FamInstEnvs
dsGetFamInstEnvs
      case FamInstEnvs -> Type -> ConLike -> Maybe [Type]
guessConLikeUnivTyArgsFromResTy FamInstEnvs
env Type
ty ConLike
cl of
        Maybe [Type]
Nothing -> [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure [Delta
delta] -- No idea idea how to refine this one, so just finish off with a wildcard
        Just [Type]
arg_tys -> do
          ([Id]
arg_vars, Bag TyCt
new_ty_cs, [Type]
strict_arg_tys) <- [Type] -> ConLike -> DsM ([Id], Bag TyCt, [Type])
mkOneConFull [Type]
arg_tys ConLike
cl
          let new_tm_cs :: Bag TmCt
new_tm_cs = TmCt -> Bag TmCt
forall a. a -> Bag a
unitBag (Id -> PmAltCon -> [Id] -> TmCt
TmVarCon Id
x (ConLike -> PmAltCon
PmAltConLike ConLike
cl) [Id]
arg_vars)
          -- Now check satifiability
          Maybe Delta
mb_delta <- Delta -> Bag TmCt -> Bag TyCt -> [Type] -> DsM (Maybe Delta)
pmIsSatisfiable Delta
delta Bag TmCt
new_tm_cs Bag TyCt
new_ty_cs [Type]
strict_arg_tys
          String -> SDoc -> DsM ()
tracePm String
"instantiate_cons" ([SDoc] -> SDoc
vcat [ Id -> SDoc
forall a. Outputable a => a -> SDoc
ppr Id
x
                                           , Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Id -> Type
idType Id
x)
                                           , Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty
                                           , ConLike -> SDoc
forall a. Outputable a => a -> SDoc
ppr ConLike
cl
                                           , [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
arg_tys
                                           , Bag TmCt -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TmCt
new_tm_cs
                                           , Bag TyCt -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TyCt
new_ty_cs
                                           , [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
strict_arg_tys
                                           , Delta -> SDoc
forall a. Outputable a => a -> SDoc
ppr Delta
delta
                                           , Maybe Delta -> SDoc
forall a. Outputable a => a -> SDoc
ppr Maybe Delta
mb_delta
                                           , Int -> SDoc
forall a. Outputable a => a -> SDoc
ppr Int
n ])
          [Delta]
con_deltas <- case Maybe Delta
mb_delta of
            Maybe Delta
Nothing     -> [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure []
            -- NB: We don't prepend arg_vars as we don't have any evidence on
            -- them and we only want to split once on a data type. They are
            -- inhabited, otherwise pmIsSatisfiable would have refuted.
            Just Delta
delta' -> [Id] -> Int -> Delta -> DsM [Delta]
go [Id]
xs Int
n Delta
delta'
          [Delta]
other_cons_deltas <- Id -> Type -> [Id] -> Int -> Delta -> [ConLike] -> DsM [Delta]
instantiate_cons Id
x Type
ty [Id]
xs (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Delta] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Delta]
con_deltas) Delta
delta [ConLike]
cls
          [Delta] -> DsM [Delta]
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([Delta]
con_deltas [Delta] -> [Delta] -> [Delta]
forall a. [a] -> [a] -> [a]
++ [Delta]
other_cons_deltas)

pickMinimalCompleteSet :: Delta -> PossibleMatches -> DsM (Maybe ConLikeSet)
pickMinimalCompleteSet :: Delta -> PossibleMatches -> DsM (Maybe ConLikeSet)
pickMinimalCompleteSet Delta
_ PossibleMatches
NoPM      = Maybe ConLikeSet -> DsM (Maybe ConLikeSet)
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe ConLikeSet
forall a. Maybe a
Nothing
-- TODO: First prune sets with type info in delta. But this is good enough for
-- now and less costly. See #17386.
pickMinimalCompleteSet Delta
_ (PM NonEmpty ConLikeSet
clss) = do
  String -> SDoc -> DsM ()
tracePm String
"pickMinimalCompleteSet" ([ConLikeSet] -> SDoc
forall a. Outputable a => a -> SDoc
ppr ([ConLikeSet] -> SDoc) -> [ConLikeSet] -> SDoc
forall a b. (a -> b) -> a -> b
$ NonEmpty ConLikeSet -> [ConLikeSet]
forall a. NonEmpty a -> [a]
NonEmpty.toList NonEmpty ConLikeSet
clss)
  Maybe ConLikeSet -> DsM (Maybe ConLikeSet)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ConLikeSet -> Maybe ConLikeSet
forall a. a -> Maybe a
Just ((ConLikeSet -> ConLikeSet -> Ordering)
-> NonEmpty ConLikeSet -> ConLikeSet
forall (t :: * -> *) a.
Foldable t =>
(a -> a -> Ordering) -> t a -> a
minimumBy ((ConLikeSet -> Int) -> ConLikeSet -> ConLikeSet -> Ordering
forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing ConLikeSet -> Int
forall a. UniqDSet a -> Int
sizeUniqDSet) NonEmpty ConLikeSet
clss))

-- | See if we already encountered a semantically equivalent expression and
-- return its representative.
representCoreExpr :: Delta -> CoreExpr -> DsM (Delta, Id)
representCoreExpr :: Delta -> CoreExpr -> DsM (Delta, Id)
representCoreExpr delta :: Delta
delta@MkDelta{ delta_tm_st :: Delta -> TmState
delta_tm_st = ts :: TmState
ts@TmSt{ ts_reps :: TmState -> CoreMap Id
ts_reps = CoreMap Id
reps } } CoreExpr
e = do
  DynFlags
dflags <- IOEnv (Env DsGblEnv DsLclEnv) DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  let e' :: CoreExpr
e' = DynFlags -> CoreExpr -> CoreExpr
simpleOptExpr DynFlags
dflags CoreExpr
e
  case CoreMap Id -> CoreExpr -> Maybe Id
forall a. CoreMap a -> CoreExpr -> Maybe a
lookupCoreMap CoreMap Id
reps CoreExpr
e' of
    Just Id
rep -> (Delta, Id) -> DsM (Delta, Id)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Delta
delta, Id
rep)
    Maybe Id
Nothing  -> do
      Id
rep <- Type -> DsM Id
mkPmId (CoreExpr -> Type
exprType CoreExpr
e')
      let reps' :: CoreMap Id
reps'  = CoreMap Id -> CoreExpr -> Id -> CoreMap Id
forall a. CoreMap a -> CoreExpr -> a -> CoreMap a
extendCoreMap CoreMap Id
reps CoreExpr
e' Id
rep
      let delta' :: Delta
delta' = Delta
delta{ delta_tm_st :: TmState
delta_tm_st = TmState
ts{ ts_reps :: CoreMap Id
ts_reps = CoreMap Id
reps' } }
      (Delta, Id) -> DsM (Delta, Id)
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Delta
delta', Id
rep)

-- Most of our actions thread around a delta from one computation to the next,
-- thereby potentially failing. This is expressed in the following Monad:
-- type PmM a = StateT Delta (MaybeT DsM) a

-- | Records that a variable @x@ is equal to a 'CoreExpr' @e@.
addVarCoreCt :: Delta -> Id -> CoreExpr -> DsM (Maybe Delta)
addVarCoreCt :: Delta -> Id -> CoreExpr -> DsM (Maybe Delta)
addVarCoreCt Delta
delta Id
x CoreExpr
e = MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta -> DsM (Maybe Delta)
forall (m :: * -> *) a. MaybeT m a -> m (Maybe a)
runMaybeT (StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
-> Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m s
execStateT (Id
-> CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
core_expr Id
x CoreExpr
e) Delta
delta)
  where
    -- | Takes apart a 'CoreExpr' and tries to extract as much information about
    -- literals and constructor applications as possible.
    core_expr :: Id -> CoreExpr -> StateT Delta (MaybeT DsM) ()
    -- TODO: Handle newtypes properly, by wrapping the expression in a DataCon
    -- This is the right thing for casts involving data family instances and
    -- their representation TyCon, though (which are not visible in source
    -- syntax). See Note [COMPLETE sets on data families]
    -- core_expr x e | pprTrace "core_expr" (ppr x $$ ppr e) False = undefined
    core_expr :: Id
-> CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
core_expr Id
x (Cast CoreExpr
e Coercion
_co) = Id
-> CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
core_expr Id
x CoreExpr
e
    core_expr Id
x (Tick Tickish Id
_t CoreExpr
e) = Id
-> CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
core_expr Id
x CoreExpr
e
    core_expr Id
x CoreExpr
e
      | Just (PmLit -> Maybe FastString
pmLitAsStringLit -> Just FastString
s) <- CoreExpr -> Maybe PmLit
coreExprAsPmLit CoreExpr
e
      , Type
expr_ty Type -> Type -> Bool
`eqType` Type
stringTy
      -- See Note [Representation of Strings in TmState]
      = case FastString -> String
unpackFS FastString
s of
          -- We need this special case to break a loop with coreExprAsPmLit
          -- Otherwise we alternate endlessly between [] and ""
          [] -> Id
-> DataCon
-> [Id]
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
data_con_app Id
x DataCon
nilDataCon []
          String
s' -> Id
-> CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
core_expr Id
x (Type -> [CoreExpr] -> CoreExpr
mkListExpr Type
charTy ((Char -> CoreExpr) -> String -> [CoreExpr]
forall a b. (a -> b) -> [a] -> [b]
map Char -> CoreExpr
mkCharExpr String
s'))
      | Just PmLit
lit <- CoreExpr -> Maybe PmLit
coreExprAsPmLit CoreExpr
e
      = Id
-> PmLit
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
pm_lit Id
x PmLit
lit
      | Just (InScopeSet
_in_scope, _empty_floats :: [FloatBind]
_empty_floats@[], DataCon
dc, [Type]
_arg_tys, [CoreExpr]
args)
            <- InScopeEnv
-> CoreExpr
-> Maybe (InScopeSet, [FloatBind], DataCon, [Type], [CoreExpr])
exprIsConApp_maybe InScopeEnv
forall b. (InScopeSet, b -> Unfolding)
in_scope_env CoreExpr
e
      = do { [Id]
arg_ids <- (CoreExpr
 -> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id)
-> [CoreExpr]
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) [Id]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
traverse CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
bind_expr [CoreExpr]
args
           ; Id
-> DataCon
-> [Id]
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
data_con_app Id
x DataCon
dc [Id]
arg_ids }
      -- See Note [Detecting pattern synonym applications in expressions]
      | Var Id
y <- CoreExpr
e, Maybe DataCon
Nothing <- Id -> Maybe DataCon
isDataConId_maybe Id
x
      -- We don't consider DataCons flexible variables
      = (Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
forall (m :: * -> *) s. Monad m => (s -> m s) -> StateT s m ()
modifyT (\Delta
delta -> Delta -> (Id, Id) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarVarCt Delta
delta (Id
x, Id
y))
      | Bool
otherwise
      -- Any other expression. Try to find other uses of a semantically
      -- equivalent expression and represent them by the same variable!
      = do { Id
rep <- CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
represent_expr CoreExpr
e
           ; (Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
forall (m :: * -> *) s. Monad m => (s -> m s) -> StateT s m ()
modifyT (\Delta
delta -> Delta -> (Id, Id) -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarVarCt Delta
delta (Id
x, Id
rep)) }
      where
        expr_ty :: Type
expr_ty       = CoreExpr -> Type
exprType CoreExpr
e
        expr_in_scope :: InScopeSet
expr_in_scope = VarSet -> InScopeSet
mkInScopeSet (CoreExpr -> VarSet
exprFreeVars CoreExpr
e)
        in_scope_env :: (InScopeSet, b -> Unfolding)
in_scope_env  = (InScopeSet
expr_in_scope, Unfolding -> b -> Unfolding
forall a b. a -> b -> a
const Unfolding
NoUnfolding)
        -- It's inconvenient to get hold of a global in-scope set
        -- here, but it'll only be needed if exprIsConApp_maybe ends
        -- up substituting inside a forall or lambda (i.e. seldom)
        -- so using exprFreeVars seems fine.   See MR !1647.

        bind_expr :: CoreExpr -> StateT Delta (MaybeT DsM) Id
        bind_expr :: CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
bind_expr CoreExpr
e = do
          Id
x <- MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Id
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (DsM Id -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Id
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Type -> DsM Id
mkPmId (CoreExpr -> Type
exprType CoreExpr
e)))
          Id
-> CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
core_expr Id
x CoreExpr
e
          Id -> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
forall (f :: * -> *) a. Applicative f => a -> f a
pure Id
x

        -- See if we already encountered a semantically equivalent expression
        -- and return its representative
        represent_expr :: CoreExpr -> StateT Delta (MaybeT DsM) Id
        represent_expr :: CoreExpr
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
represent_expr CoreExpr
e = (Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta))
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta))
 -> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id)
-> (Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta))
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) Id
forall a b. (a -> b) -> a -> b
$ \Delta
delta ->
          (Delta, Id) -> (Id, Delta)
forall a b. (a, b) -> (b, a)
swap ((Delta, Id) -> (Id, Delta))
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Delta, Id)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Id, Delta)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> DsM (Delta, Id)
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) (Delta, Id)
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Delta -> CoreExpr -> DsM (Delta, Id)
representCoreExpr Delta
delta CoreExpr
e)

    data_con_app :: Id -> DataCon -> [Id] -> StateT Delta (MaybeT DsM) ()
    data_con_app :: Id
-> DataCon
-> [Id]
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
data_con_app Id
x DataCon
dc [Id]
args = Id
-> PmAltCon
-> [Id]
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
pm_alt_con_app Id
x (ConLike -> PmAltCon
PmAltConLike (DataCon -> ConLike
RealDataCon DataCon
dc)) [Id]
args

    pm_lit :: Id -> PmLit -> StateT Delta (MaybeT DsM) ()
    pm_lit :: Id
-> PmLit
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
pm_lit Id
x PmLit
lit = Id
-> PmAltCon
-> [Id]
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
pm_alt_con_app Id
x (PmLit -> PmAltCon
PmAltLit PmLit
lit) []

    -- | Adds the given constructor application as a solution for @x@.
    pm_alt_con_app :: Id -> PmAltCon -> [Id] -> StateT Delta (MaybeT DsM) ()
    pm_alt_con_app :: Id
-> PmAltCon
-> [Id]
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
pm_alt_con_app Id
x PmAltCon
con [Id]
args = (Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
forall (m :: * -> *) s. Monad m => (s -> m s) -> StateT s m ()
modifyT ((Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
 -> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ())
-> (Delta -> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta)
-> StateT Delta (MaybeT (IOEnv (Env DsGblEnv DsLclEnv))) ()
forall a b. (a -> b) -> a -> b
$ \Delta
delta -> Delta
-> Id
-> PmAltCon
-> [Id]
-> MaybeT (IOEnv (Env DsGblEnv DsLclEnv)) Delta
addVarConCt Delta
delta Id
x PmAltCon
con [Id]
args

-- | Like 'modify', but with an effectful modifier action
modifyT :: Monad m => (s -> m s) -> StateT s m ()
modifyT :: (s -> m s) -> StateT s m ()
modifyT s -> m s
f = (s -> m ((), s)) -> StateT s m ()
forall s (m :: * -> *) a. (s -> m (a, s)) -> StateT s m a
StateT ((s -> m ((), s)) -> StateT s m ())
-> (s -> m ((), s)) -> StateT s m ()
forall a b. (a -> b) -> a -> b
$ (s -> ((), s)) -> m s -> m ((), s)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((,) ()) (m s -> m ((), s)) -> (s -> m s) -> s -> m ((), s)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. s -> m s
f

{- Note [Detecting pattern synonym applications in expressions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At the moment we fail to detect pattern synonyms in scrutinees and RHS of
guards. This could be alleviated with considerable effort and complexity, but
the returns are meager. Consider:

    pattern P
    pattern Q
    case P 15 of
      Q _  -> ...
      P 15 ->

Compared to the situation where P and Q are DataCons, the lack of generativity
means we could never flag Q as redundant.
(also see Note [Undecidable Equality for PmAltCons] in PmTypes.)
On the other hand, if we fail to recognise the pattern synonym, we flag the
pattern match as inexhaustive. That wouldn't happen if we had knowledge about
the scrutinee, in which case the oracle basically knows "If it's a P, then its
field is 15".

This is a pretty narrow use case and I don't think we should to try to fix it
until a user complains energetically.
-}