{-# LANGUAGE CPP #-}

module GHC.Tc.Solver(
       simplifyInfer, InferMode(..),
       growThetaTyVars,
       simplifyAmbiguityCheck,
       simplifyDefault,
       simplifyTop, simplifyTopImplic,
       simplifyInteractive,
       solveEqualities, solveLocalEqualities, solveLocalEqualitiesX,
       simplifyWantedsTcM,
       tcCheckSatisfiability,
       tcNormalise,

       captureTopConstraints,

       simpl_top,

       promoteTyVarSet, emitFlatConstraints,

       -- For Rules we need these
       solveWanteds, solveWantedsAndDrop,
       approximateWC, runTcSDeriveds
  ) where

#include "HsVersions.h"

import GHC.Prelude

import GHC.Data.Bag
import GHC.Core.Class ( Class, classKey, classTyCon )
import GHC.Driver.Session
import GHC.Types.Id   ( idType )
import GHC.Tc.Utils.Instantiate
import GHC.Data.List.SetOps
import GHC.Types.Name
import GHC.Utils.Outputable
import GHC.Builtin.Utils
import GHC.Builtin.Names
import GHC.Tc.Errors
import GHC.Tc.Types.Evidence
import GHC.Tc.Solver.Interact
import GHC.Tc.Solver.Canonical   ( makeSuperClasses, solveCallStack )
import GHC.Tc.Solver.Flatten     ( flattenType )
import GHC.Tc.Utils.TcMType   as TcM
import GHC.Tc.Utils.Monad as TcM
import GHC.Tc.Solver.Monad  as TcS
import GHC.Tc.Types.Constraint
import GHC.Core.Predicate
import GHC.Tc.Types.Origin
import GHC.Tc.Utils.TcType
import GHC.Core.Type
import GHC.Builtin.Types ( liftedRepTy, manyDataConTy )
import GHC.Core.Unify    ( tcMatchTyKi )
import GHC.Utils.Misc
import GHC.Types.Var
import GHC.Types.Var.Set
import GHC.Types.Basic    ( IntWithInf, intGtLimit )
import GHC.Utils.Error    ( emptyMessages )
import qualified GHC.LanguageExtensions as LangExt

import Control.Monad
import Data.Foldable      ( toList )
import Data.List          ( partition )
import Data.List.NonEmpty ( NonEmpty(..) )

{-
*********************************************************************************
*                                                                               *
*                           External interface                                  *
*                                                                               *
*********************************************************************************
-}

captureTopConstraints :: TcM a -> TcM (a, WantedConstraints)
-- (captureTopConstraints m) runs m, and returns the type constraints it
-- generates plus the constraints produced by static forms inside.
-- If it fails with an exception, it reports any insolubles
-- (out of scope variables) before doing so
--
-- captureTopConstraints is used exclusively by GHC.Tc.Module at the top
-- level of a module.
--
-- Importantly, if captureTopConstraints propagates an exception, it
-- reports any insoluble constraints first, lest they be lost
-- altogether.  This is important, because solveLocalEqualities (maybe
-- other things too) throws an exception without adding any error
-- messages; it just puts the unsolved constraints back into the
-- monad. See GHC.Tc.Utils.Monad Note [Constraints and errors]
-- #16376 is an example of what goes wrong if you don't do this.
--
-- NB: the caller should bring any environments into scope before
-- calling this, so that the reportUnsolved has access to the most
-- complete GlobalRdrEnv
captureTopConstraints :: forall a. TcM a -> TcM (a, WantedConstraints)
captureTopConstraints TcM a
thing_inside
  = do { TcRef WantedConstraints
static_wc_var <- WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv (TcRef WantedConstraints)
forall a gbl lcl. a -> TcRnIf gbl lcl (TcRef a)
TcM.newTcRef WantedConstraints
emptyWC ;
       ; (Maybe a
mb_res, WantedConstraints
lie) <- (TcGblEnv -> TcGblEnv)
-> TcRnIf TcGblEnv TcLclEnv (Maybe a, WantedConstraints)
-> TcRnIf TcGblEnv TcLclEnv (Maybe a, WantedConstraints)
forall gbl lcl a.
(gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
TcM.updGblEnv (\TcGblEnv
env -> TcGblEnv
env { tcg_static_wc :: TcRef WantedConstraints
tcg_static_wc = TcRef WantedConstraints
static_wc_var } ) (TcRnIf TcGblEnv TcLclEnv (Maybe a, WantedConstraints)
 -> TcRnIf TcGblEnv TcLclEnv (Maybe a, WantedConstraints))
-> TcRnIf TcGblEnv TcLclEnv (Maybe a, WantedConstraints)
-> TcRnIf TcGblEnv TcLclEnv (Maybe a, WantedConstraints)
forall a b. (a -> b) -> a -> b
$
                          TcM a -> TcRnIf TcGblEnv TcLclEnv (Maybe a, WantedConstraints)
forall a. TcM a -> TcM (Maybe a, WantedConstraints)
TcM.tryCaptureConstraints TcM a
thing_inside
       ; WantedConstraints
stWC <- TcRef WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
TcM.readTcRef TcRef WantedConstraints
static_wc_var

       -- See GHC.Tc.Utils.Monad Note [Constraints and errors]
       -- If the thing_inside threw an exception, but generated some insoluble
       -- constraints, report the latter before propagating the exception
       -- Otherwise they will be lost altogether
       ; case Maybe a
mb_res of
           Just a
res -> (a, WantedConstraints) -> TcM (a, WantedConstraints)
forall (m :: * -> *) a. Monad m => a -> m a
return (a
res, WantedConstraints
lie WantedConstraints -> WantedConstraints -> WantedConstraints
`andWC` WantedConstraints
stWC)
           Maybe a
Nothing  -> do { Bag EvBind
_ <- WantedConstraints -> TcM (Bag EvBind)
simplifyTop WantedConstraints
lie; TcM (a, WantedConstraints)
forall env a. IOEnv env a
failM } }
                -- This call to simplifyTop is the reason
                -- this function is here instead of GHC.Tc.Utils.Monad
                -- We call simplifyTop so that it does defaulting
                -- (esp of runtime-reps) before reporting errors

simplifyTopImplic :: Bag Implication -> TcM ()
simplifyTopImplic :: Bag Implication -> TcM ()
simplifyTopImplic Bag Implication
implics
  = do { Bag EvBind
empty_binds <- WantedConstraints -> TcM (Bag EvBind)
simplifyTop (Bag Implication -> WantedConstraints
mkImplicWC Bag Implication
implics)

       -- Since all the inputs are implications the returned bindings will be empty
       ; MASSERT2( isEmptyBag empty_binds, ppr empty_binds )

       ; () -> TcM ()
forall (m :: * -> *) a. Monad m => a -> m a
return () }

simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
-- Simplify top-level constraints
-- Usually these will be implications,
-- but when there is nothing to quantify we don't wrap
-- in a degenerate implication, so we do that here instead
simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
simplifyTop WantedConstraints
wanteds
  = do { String -> SDoc -> TcM ()
traceTc String
"simplifyTop {" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ String -> SDoc
text String
"wanted = " SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wanteds
       ; ((WantedConstraints
final_wc, Cts
unsafe_ol), EvBindMap
binds1) <- TcS (WantedConstraints, Cts)
-> TcM ((WantedConstraints, Cts), EvBindMap)
forall a. TcS a -> TcM (a, EvBindMap)
runTcS (TcS (WantedConstraints, Cts)
 -> TcM ((WantedConstraints, Cts), EvBindMap))
-> TcS (WantedConstraints, Cts)
-> TcM ((WantedConstraints, Cts), EvBindMap)
forall a b. (a -> b) -> a -> b
$
            do { WantedConstraints
final_wc <- WantedConstraints -> TcS WantedConstraints
simpl_top WantedConstraints
wanteds
               ; Cts
unsafe_ol <- TcS Cts
getSafeOverlapFailures
               ; (WantedConstraints, Cts) -> TcS (WantedConstraints, Cts)
forall (m :: * -> *) a. Monad m => a -> m a
return (WantedConstraints
final_wc, Cts
unsafe_ol) }
       ; String -> SDoc -> TcM ()
traceTc String
"End simplifyTop }" SDoc
empty

       ; Bag EvBind
binds2 <- WantedConstraints -> TcM (Bag EvBind)
reportUnsolved WantedConstraints
final_wc

       ; String -> SDoc -> TcM ()
traceTc String
"reportUnsolved (unsafe overlapping) {" SDoc
empty
       ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Cts -> Bool
isEmptyCts Cts
unsafe_ol) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$ do {
           -- grab current error messages and clear, warnAllUnsolved will
           -- update error messages which we'll grab and then restore saved
           -- messages.
           ; TcRef Messages
errs_var  <- TcRn (TcRef Messages)
getErrsVar
           ; Messages
saved_msg <- TcRef Messages -> TcRnIf TcGblEnv TcLclEnv Messages
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
TcM.readTcRef TcRef Messages
errs_var
           ; TcRef Messages -> Messages -> TcM ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
TcM.writeTcRef TcRef Messages
errs_var Messages
emptyMessages

           ; WantedConstraints -> TcM ()
warnAllUnsolved (WantedConstraints -> TcM ()) -> WantedConstraints -> TcM ()
forall a b. (a -> b) -> a -> b
$ WantedConstraints
emptyWC { wc_simple :: Cts
wc_simple = Cts
unsafe_ol }

           ; WarningMessages
whyUnsafe <- Messages -> WarningMessages
forall a b. (a, b) -> a
fst (Messages -> WarningMessages)
-> TcRnIf TcGblEnv TcLclEnv Messages
-> IOEnv (Env TcGblEnv TcLclEnv) WarningMessages
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TcRef Messages -> TcRnIf TcGblEnv TcLclEnv Messages
forall a gbl lcl. TcRef a -> TcRnIf gbl lcl a
TcM.readTcRef TcRef Messages
errs_var
           ; TcRef Messages -> Messages -> TcM ()
forall a gbl lcl. TcRef a -> a -> TcRnIf gbl lcl ()
TcM.writeTcRef TcRef Messages
errs_var Messages
saved_msg
           ; WarningMessages -> TcM ()
recordUnsafeInfer WarningMessages
whyUnsafe
           }
       ; String -> SDoc -> TcM ()
traceTc String
"reportUnsolved (unsafe overlapping) }" SDoc
empty

       ; Bag EvBind -> TcM (Bag EvBind)
forall (m :: * -> *) a. Monad m => a -> m a
return (EvBindMap -> Bag EvBind
evBindMapBinds EvBindMap
binds1 Bag EvBind -> Bag EvBind -> Bag EvBind
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag EvBind
binds2) }


-- | Type-check a thing that emits only equality constraints, solving any
-- constraints we can and re-emitting constraints that we can't. The thing_inside
-- should generally bump the TcLevel to make sure that this run of the solver
-- doesn't affect anything lying around.
solveLocalEqualities :: String -> TcM a -> TcM a
-- Note [Failure in local type signatures]
solveLocalEqualities :: forall a. String -> TcM a -> TcM a
solveLocalEqualities String
callsite TcM a
thing_inside
  = do { (WantedConstraints
wanted, a
res) <- String -> TcM a -> TcM (WantedConstraints, a)
forall a. String -> TcM a -> TcM (WantedConstraints, a)
solveLocalEqualitiesX String
callsite TcM a
thing_inside
       ; WantedConstraints -> TcM ()
emitFlatConstraints WantedConstraints
wanted
       ; a -> TcM a
forall (m :: * -> *) a. Monad m => a -> m a
return a
res }

emitFlatConstraints :: WantedConstraints -> TcM ()
-- See Note [Failure in local type signatures]
emitFlatConstraints :: WantedConstraints -> TcM ()
emitFlatConstraints WantedConstraints
wanted
  = do { WantedConstraints
wanted <- WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
TcM.zonkWC WantedConstraints
wanted
       ; case WantedConstraints -> Maybe (Cts, Bag Hole)
floatKindEqualities WantedConstraints
wanted of
           Maybe (Cts, Bag Hole)
Nothing -> do { String -> SDoc -> TcM ()
traceTc String
"emitFlatConstraints: failing" (WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wanted)
                         ; WantedConstraints -> TcM ()
emitConstraints WantedConstraints
wanted -- So they get reported!
                         ; TcM ()
forall env a. IOEnv env a
failM }
           Just (Cts
simples, Bag Hole
holes)
              -> do { Bool
_ <- VarSet -> TcM Bool
promoteTyVarSet (Cts -> VarSet
tyCoVarsOfCts Cts
simples)
                    ; String -> SDoc -> TcM ()
traceTc String
"emitFlatConstraints:" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
                      [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"simples:" SDoc -> SDoc -> SDoc
<+> Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
simples
                           , String -> SDoc
text String
"holes:  " SDoc -> SDoc -> SDoc
<+> Bag Hole -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag Hole
holes ]
                    ; Bag Hole -> TcM ()
emitHoles Bag Hole
holes -- Holes don't need promotion
                    ; Cts -> TcM ()
emitSimples Cts
simples } }

floatKindEqualities :: WantedConstraints -> Maybe (Bag Ct, Bag Hole)
-- Float out all the constraints from the WantedConstraints,
-- Return Nothing if any constraints can't be floated (captured
-- by skolems), or if there is an insoluble constraint, or
-- IC_Telescope telescope error
floatKindEqualities :: WantedConstraints -> Maybe (Cts, Bag Hole)
floatKindEqualities WantedConstraints
wc = VarSet -> WantedConstraints -> Maybe (Cts, Bag Hole)
float_wc VarSet
emptyVarSet WantedConstraints
wc
  where
    float_wc :: TcTyCoVarSet -> WantedConstraints -> Maybe (Bag Ct, Bag Hole)
    float_wc :: VarSet -> WantedConstraints -> Maybe (Cts, Bag Hole)
float_wc VarSet
trapping_tvs (WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples
                              , wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implics
                              , wc_holes :: WantedConstraints -> Bag Hole
wc_holes = Bag Hole
holes })
      | (Ct -> Bool) -> Cts -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Ct -> Bool
is_floatable Cts
simples
      = do { (Cts
inner_simples, Bag Hole
inner_holes)
                <- (Implication -> Maybe (Cts, Bag Hole))
-> Bag Implication -> Maybe (Cts, Bag Hole)
forall (m :: * -> *) a b c.
Monad m =>
(a -> m (Bag b, Bag c)) -> Bag a -> m (Bag b, Bag c)
flatMapBagPairM (VarSet -> Implication -> Maybe (Cts, Bag Hole)
float_implic VarSet
trapping_tvs) Bag Implication
implics
           ; (Cts, Bag Hole) -> Maybe (Cts, Bag Hole)
forall (m :: * -> *) a. Monad m => a -> m a
return ( Cts
simples Cts -> Cts -> Cts
forall a. Bag a -> Bag a -> Bag a
`unionBags` Cts
inner_simples
                    , Bag Hole
holes Bag Hole -> Bag Hole -> Bag Hole
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag Hole
inner_holes) }
      | Bool
otherwise
      = Maybe (Cts, Bag Hole)
forall a. Maybe a
Nothing
      where
        is_floatable :: Ct -> Bool
is_floatable Ct
ct
           | Ct -> Bool
insolubleEqCt Ct
ct = Bool
False
           | Bool
otherwise        = Ct -> VarSet
tyCoVarsOfCt Ct
ct VarSet -> VarSet -> Bool
`disjointVarSet` VarSet
trapping_tvs

    float_implic :: TcTyCoVarSet -> Implication -> Maybe (Bag Ct, Bag Hole)
    float_implic :: VarSet -> Implication -> Maybe (Cts, Bag Hole)
float_implic VarSet
trapping_tvs (Implic { ic_wanted :: Implication -> WantedConstraints
ic_wanted = WantedConstraints
wanted, ic_no_eqs :: Implication -> Bool
ic_no_eqs = Bool
no_eqs
                                      , ic_skols :: Implication -> [TcTyVar]
ic_skols = [TcTyVar]
skols, ic_status :: Implication -> ImplicStatus
ic_status = ImplicStatus
status })
      | ImplicStatus -> Bool
isInsolubleStatus ImplicStatus
status
      = Maybe (Cts, Bag Hole)
forall a. Maybe a
Nothing   -- A short cut /plus/ we must keep track of IC_BadTelescope
      | Bool
otherwise
      = do { (Cts
simples, Bag Hole
holes) <- VarSet -> WantedConstraints -> Maybe (Cts, Bag Hole)
float_wc VarSet
new_trapping_tvs WantedConstraints
wanted
           ; Bool -> Maybe () -> Maybe ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (Cts -> Bool
forall a. Bag a -> Bool
isEmptyBag Cts
simples) Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
no_eqs) (Maybe () -> Maybe ()) -> Maybe () -> Maybe ()
forall a b. (a -> b) -> a -> b
$
             Maybe ()
forall a. Maybe a
Nothing
                 -- If there are some constraints to float out, but we can't
                 -- because we don't float out past local equalities
                 -- (c.f GHC.Tc.Solver.approximateWC), then fail
           ; (Cts, Bag Hole) -> Maybe (Cts, Bag Hole)
forall (m :: * -> *) a. Monad m => a -> m a
return (Cts
simples, Bag Hole
holes) }
      where
        new_trapping_tvs :: VarSet
new_trapping_tvs = VarSet
trapping_tvs VarSet -> [TcTyVar] -> VarSet
`extendVarSetList` [TcTyVar]
skols


{- Note [Failure in local type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When kind checking a type signature, we like to fail fast if we can't
solve all the kind equality constraints: see Note [Fail fast on kind
errors].  But what about /local/ type signatures, mentioning in-scope
type variables for which there might be given equalities.  Here's
an example (T15076b):

  class (a ~ b) => C a b
  data SameKind :: k -> k -> Type where { SK :: SameKind a b }

  bar :: forall (a :: Type) (b :: Type).
         C a b => Proxy a -> Proxy b -> ()
  bar _ _ = const () (undefined :: forall (x :: a) (y :: b). SameKind x y)

Consider the type singature on 'undefined'. It's ill-kinded unless
a~b.  But the superclass of (C a b) means that indeed (a~b). So all
should be well. BUT it's hard to see that when kind-checking the signature
for undefined.  We want to emit a residual (a~b) constraint, to solve
later.

Another possiblity is that we might have something like
   F alpha ~ [Int]
where alpha is bound further out, which might become soluble
"later" when we learn more about alpha.  So we want to emit
those residual constraints.

BUT it's no good simply wrapping all unsolved constraints from
a type signature in an implication constraint to solve later. The
problem is that we are going to /use/ that signature, including
instantiate it.  Say we have
     f :: forall a.  (forall b. blah) -> blah2
     f x = <body>
To typecheck the definition of f, we have to instantiate those
foralls.  Moreover, any unsolved kind equalities will be coercion
holes in the type.  If we naively wrap them in an implication like
     forall a. (co1:k1~k2,  forall b.  co2:k3~k4)
hoping to solve it later, we might end up filling in the holes
co1 and co2 with coercions involving 'a' and 'b' -- but by now
we've instantiated the type.  Chaos!

Moreover, the unsolved constraints might be skolem-escpae things, and
if we proceed with f bound to a nonsensical type, we get a cascade of
follow-up errors. For example polykinds/T12593, T15577, and many others.

So here's the plan:

* solveLocalEqualitiesX: try to solve the constraints (solveLocalEqualitiesX)

* buildTvImplication: build an implication for the residual, unsolved
  constraint

* emitFlatConstraints: try to float out every unsolved equalities
  inside that implication, in the hope that it constrains only global
  type variables, not the locally-quantified ones.

  * If we fail, or find an insoluble constraint, emit the implication,
    so that the errors will be reported, and fail.

  * If we succeed in floating all the equalities, promote them and
    re-emit them as flat constraint, not wrapped at all (since they
    don't mention any of the quantified variables.

* Note that this float-and-promote step means that anonymous
  wildcards get floated to top level, as we want; see
  Note [Checking partial type signatures] in GHC.Tc.Gen.HsType.

All this is done:

* in solveLocalEqualities, where there is no kind-generalisation
  to complicate matters.

* in GHC.Tc.Gen.HsType.tcHsSigType, where quantification intervenes.

See also #18062, #11506
-}

solveLocalEqualitiesX :: String -> TcM a -> TcM (WantedConstraints, a)
solveLocalEqualitiesX :: forall a. String -> TcM a -> TcM (WantedConstraints, a)
solveLocalEqualitiesX String
callsite TcM a
thing_inside
  = do { String -> SDoc -> TcM ()
traceTc String
"solveLocalEqualitiesX {" ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Called from" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
callsite ])

       ; (a
result, WantedConstraints
wanted) <- TcM a -> TcM (a, WantedConstraints)
forall a. TcM a -> TcM (a, WantedConstraints)
captureConstraints TcM a
thing_inside

       ; String -> SDoc -> TcM ()
traceTc String
"solveLocalEqualities: running solver" (WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wanted)
       ; WantedConstraints
residual_wanted <- TcS WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a. TcS a -> TcM a
runTcSEqualities (WantedConstraints -> TcS WantedConstraints
solveWanteds WantedConstraints
wanted)

       ; String -> SDoc -> TcM ()
traceTc String
"solveLocalEqualitiesX end }" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         String -> SDoc
text String
"residual_wanted =" SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
residual_wanted

       ; (WantedConstraints, a) -> TcM (WantedConstraints, a)
forall (m :: * -> *) a. Monad m => a -> m a
return (WantedConstraints
residual_wanted, a
result) }

-- | Type-check a thing that emits only equality constraints, then
-- solve those constraints. Fails outright if there is trouble.
-- Use this if you're not going to get another crack at solving
-- (because, e.g., you're checking a datatype declaration)
solveEqualities :: TcM a -> TcM a
solveEqualities :: forall a. TcM a -> TcM a
solveEqualities TcM a
thing_inside
  = TcM a -> TcM a
forall a. TcM a -> TcM a
checkNoErrs (TcM a -> TcM a) -> TcM a -> TcM a
forall a b. (a -> b) -> a -> b
$  -- See Note [Fail fast on kind errors]
    do { TcLevel
lvl <- TcM TcLevel
TcM.getTcLevel
       ; String -> SDoc -> TcM ()
traceTc String
"solveEqualities {" (String -> SDoc
text String
"level =" SDoc -> SDoc -> SDoc
<+> TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
lvl)

       ; (a
result, WantedConstraints
wanted) <- TcM a -> TcM (a, WantedConstraints)
forall a. TcM a -> TcM (a, WantedConstraints)
captureConstraints TcM a
thing_inside

       ; String -> SDoc -> TcM ()
traceTc String
"solveEqualities: running solver" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ String -> SDoc
text String
"wanted = " SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wanted
       ; WantedConstraints
final_wc <- TcS WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a. TcS a -> TcM a
runTcSEqualities (TcS WantedConstraints
 -> TcRnIf TcGblEnv TcLclEnv WantedConstraints)
-> TcS WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a b. (a -> b) -> a -> b
$ WantedConstraints -> TcS WantedConstraints
simpl_top WantedConstraints
wanted
          -- NB: Use simpl_top here so that we potentially default RuntimeRep
          -- vars to LiftedRep. This is needed to avoid #14991.

       ; String -> SDoc -> TcM ()
traceTc String
"End solveEqualities }" SDoc
empty
       ; WantedConstraints -> TcM ()
reportAllUnsolved WantedConstraints
final_wc
       ; a -> TcM a
forall (m :: * -> *) a. Monad m => a -> m a
return a
result }

-- | Simplify top-level constraints, but without reporting any unsolved
-- constraints nor unsafe overlapping.
simpl_top :: WantedConstraints -> TcS WantedConstraints
    -- See Note [Top-level Defaulting Plan]
simpl_top :: WantedConstraints -> TcS WantedConstraints
simpl_top WantedConstraints
wanteds
  = do { WantedConstraints
wc_first_go <- TcS WantedConstraints -> TcS WantedConstraints
forall a. TcS a -> TcS a
nestTcS (WantedConstraints -> TcS WantedConstraints
solveWantedsAndDrop WantedConstraints
wanteds)
                            -- This is where the main work happens
       ; DynFlags
dflags <- TcS DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; DynFlags -> WantedConstraints -> TcS WantedConstraints
try_tyvar_defaulting DynFlags
dflags WantedConstraints
wc_first_go }
  where
    try_tyvar_defaulting :: DynFlags -> WantedConstraints -> TcS WantedConstraints
    try_tyvar_defaulting :: DynFlags -> WantedConstraints -> TcS WantedConstraints
try_tyvar_defaulting DynFlags
dflags WantedConstraints
wc
      | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wc
      = WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
wc
      | WantedConstraints -> Bool
insolubleWC WantedConstraints
wc
      , GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_PrintExplicitRuntimeReps DynFlags
dflags -- See Note [Defaulting insolubles]
      = WantedConstraints -> TcS WantedConstraints
try_class_defaulting WantedConstraints
wc
      | Bool
otherwise
      = do { [TcTyVar]
free_tvs <- [TcTyVar] -> TcS [TcTyVar]
TcS.zonkTyCoVarsAndFVList (WantedConstraints -> [TcTyVar]
tyCoVarsOfWCList WantedConstraints
wc)
           ; let meta_tvs :: [TcTyVar]
meta_tvs = (TcTyVar -> Bool) -> [TcTyVar] -> [TcTyVar]
forall a. (a -> Bool) -> [a] -> [a]
filter (TcTyVar -> Bool
isTyVar (TcTyVar -> Bool) -> (TcTyVar -> Bool) -> TcTyVar -> Bool
forall (f :: * -> *). Applicative f => f Bool -> f Bool -> f Bool
<&&> TcTyVar -> Bool
isMetaTyVar) [TcTyVar]
free_tvs
                   -- zonkTyCoVarsAndFV: the wc_first_go is not yet zonked
                   -- filter isMetaTyVar: we might have runtime-skolems in GHCi,
                   -- and we definitely don't want to try to assign to those!
                   -- The isTyVar is needed to weed out coercion variables

           ; [Bool]
defaulted <- (TcTyVar -> TcS Bool) -> [TcTyVar] -> TcS [Bool]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcTyVar -> TcS Bool
defaultTyVarTcS [TcTyVar]
meta_tvs   -- Has unification side effects
           ; if [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or [Bool]
defaulted
             then do { WantedConstraints
wc_residual <- TcS WantedConstraints -> TcS WantedConstraints
forall a. TcS a -> TcS a
nestTcS (WantedConstraints -> TcS WantedConstraints
solveWanteds WantedConstraints
wc)
                            -- See Note [Must simplify after defaulting]
                     ; WantedConstraints -> TcS WantedConstraints
try_class_defaulting WantedConstraints
wc_residual }
             else WantedConstraints -> TcS WantedConstraints
try_class_defaulting WantedConstraints
wc }     -- No defaulting took place

    try_class_defaulting :: WantedConstraints -> TcS WantedConstraints
    try_class_defaulting :: WantedConstraints -> TcS WantedConstraints
try_class_defaulting WantedConstraints
wc
      | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wc Bool -> Bool -> Bool
|| WantedConstraints -> Bool
insolubleWC WantedConstraints
wc -- See Note [Defaulting insolubles]
      = WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
wc
      | Bool
otherwise  -- See Note [When to do type-class defaulting]
      = do { Bool
something_happened <- WantedConstraints -> TcS Bool
applyDefaultingRules WantedConstraints
wc
                                   -- See Note [Top-level Defaulting Plan]
           ; if Bool
something_happened
             then do { WantedConstraints
wc_residual <- TcS WantedConstraints -> TcS WantedConstraints
forall a. TcS a -> TcS a
nestTcS (WantedConstraints -> TcS WantedConstraints
solveWantedsAndDrop WantedConstraints
wc)
                     ; WantedConstraints -> TcS WantedConstraints
try_class_defaulting WantedConstraints
wc_residual }
                  -- See Note [Overview of implicit CallStacks] in GHC.Tc.Types.Evidence
             else WantedConstraints -> TcS WantedConstraints
try_callstack_defaulting WantedConstraints
wc }

    try_callstack_defaulting :: WantedConstraints -> TcS WantedConstraints
    try_callstack_defaulting :: WantedConstraints -> TcS WantedConstraints
try_callstack_defaulting WantedConstraints
wc
      | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wc
      = WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
wc
      | Bool
otherwise
      = WantedConstraints -> TcS WantedConstraints
defaultCallStacks WantedConstraints
wc

-- | Default any remaining @CallStack@ constraints to empty @CallStack@s.
defaultCallStacks :: WantedConstraints -> TcS WantedConstraints
-- See Note [Overview of implicit CallStacks] in GHC.Tc.Types.Evidence
defaultCallStacks :: WantedConstraints -> TcS WantedConstraints
defaultCallStacks WantedConstraints
wanteds
  = do Cts
simples <- Cts -> TcS Cts
handle_simples (WantedConstraints -> Cts
wc_simple WantedConstraints
wanteds)
       Bag (Maybe Implication)
mb_implics <- (Implication -> TcS (Maybe Implication))
-> Bag Implication -> TcS (Bag (Maybe Implication))
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM Implication -> TcS (Maybe Implication)
handle_implic (WantedConstraints -> Bag Implication
wc_impl WantedConstraints
wanteds)
       WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return (WantedConstraints
wanteds { wc_simple :: Cts
wc_simple = Cts
simples
                       , wc_impl :: Bag Implication
wc_impl = Bag (Maybe Implication) -> Bag Implication
forall a. Bag (Maybe a) -> Bag a
catBagMaybes Bag (Maybe Implication)
mb_implics })

  where

  handle_simples :: Cts -> TcS Cts
handle_simples Cts
simples
    = Bag (Maybe Ct) -> Cts
forall a. Bag (Maybe a) -> Bag a
catBagMaybes (Bag (Maybe Ct) -> Cts) -> TcS (Bag (Maybe Ct)) -> TcS Cts
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Ct -> TcS (Maybe Ct)) -> Cts -> TcS (Bag (Maybe Ct))
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM Ct -> TcS (Maybe Ct)
defaultCallStack Cts
simples

  handle_implic :: Implication -> TcS (Maybe Implication)
  -- The Maybe is because solving the CallStack constraint
  -- may well allow us to discard the implication entirely
  handle_implic :: Implication -> TcS (Maybe Implication)
handle_implic Implication
implic
    | ImplicStatus -> Bool
isSolvedStatus (Implication -> ImplicStatus
ic_status Implication
implic)
    = Maybe Implication -> TcS (Maybe Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication -> Maybe Implication
forall a. a -> Maybe a
Just Implication
implic)
    | Bool
otherwise
    = do { WantedConstraints
wanteds <- EvBindsVar -> TcS WantedConstraints -> TcS WantedConstraints
forall a. EvBindsVar -> TcS a -> TcS a
setEvBindsTcS (Implication -> EvBindsVar
ic_binds Implication
implic) (TcS WantedConstraints -> TcS WantedConstraints)
-> TcS WantedConstraints -> TcS WantedConstraints
forall a b. (a -> b) -> a -> b
$
                      -- defaultCallStack sets a binding, so
                      -- we must set the correct binding group
                      WantedConstraints -> TcS WantedConstraints
defaultCallStacks (Implication -> WantedConstraints
ic_wanted Implication
implic)
         ; Implication -> TcS (Maybe Implication)
setImplicationStatus (Implication
implic { ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
wanteds }) }

  defaultCallStack :: Ct -> TcS (Maybe Ct)
defaultCallStack Ct
ct
    | ClassPred Class
cls [Type]
tys <- Type -> Pred
classifyPredType (Ct -> Type
ctPred Ct
ct)
    , Just {} <- Class -> [Type] -> Maybe FastString
isCallStackPred Class
cls [Type]
tys
    = do { CtEvidence -> EvCallStack -> TcS ()
solveCallStack (Ct -> CtEvidence
ctEvidence Ct
ct) EvCallStack
EvCsEmpty
         ; Maybe Ct -> TcS (Maybe Ct)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Ct
forall a. Maybe a
Nothing }

  defaultCallStack Ct
ct
    = Maybe Ct -> TcS (Maybe Ct)
forall (m :: * -> *) a. Monad m => a -> m a
return (Ct -> Maybe Ct
forall a. a -> Maybe a
Just Ct
ct)


{- Note [Fail fast on kind errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
solveEqualities is used to solve kind equalities when kind-checking
user-written types. If solving fails we should fail outright, rather
than just accumulate an error message, for two reasons:

  * A kind-bogus type signature may cause a cascade of knock-on
    errors if we let it pass

  * More seriously, we don't have a convenient term-level place to add
    deferred bindings for unsolved kind-equality constraints, so we
    don't build evidence bindings (by usine reportAllUnsolved). That
    means that we'll be left with a type that has coercion holes
    in it, something like
           <type> |> co-hole
    where co-hole is not filled in.  Eeek!  That un-filled-in
    hole actually causes GHC to crash with "fvProv falls into a hole"
    See #11563, #11520, #11516, #11399

So it's important to use 'checkNoErrs' here!

Note [When to do type-class defaulting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC 7.6 and 7.8.2, we did type-class defaulting only if insolubleWC
was false, on the grounds that defaulting can't help solve insoluble
constraints.  But if we *don't* do defaulting we may report a whole
lot of errors that would be solved by defaulting; these errors are
quite spurious because fixing the single insoluble error means that
defaulting happens again, which makes all the other errors go away.
This is jolly confusing: #9033.

So it seems better to always do type-class defaulting.

However, always doing defaulting does mean that we'll do it in
situations like this (#5934):
   run :: (forall s. GenST s) -> Int
   run = fromInteger 0
We don't unify the return type of fromInteger with the given function
type, because the latter involves foralls.  So we're left with
    (Num alpha, alpha ~ (forall s. GenST s) -> Int)
Now we do defaulting, get alpha := Integer, and report that we can't
match Integer with (forall s. GenST s) -> Int.  That's not totally
stupid, but perhaps a little strange.

Another potential alternative would be to suppress *all* non-insoluble
errors if there are *any* insoluble errors, anywhere, but that seems
too drastic.

Note [Must simplify after defaulting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We may have a deeply buried constraint
    (t:*) ~ (a:Open)
which we couldn't solve because of the kind incompatibility, and 'a' is free.
Then when we default 'a' we can solve the constraint.  And we want to do
that before starting in on type classes.  We MUST do it before reporting
errors, because it isn't an error!  #7967 was due to this.

Note [Top-level Defaulting Plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We have considered two design choices for where/when to apply defaulting.
   (i) Do it in SimplCheck mode only /whenever/ you try to solve some
       simple constraints, maybe deep inside the context of implications.
       This used to be the case in GHC 7.4.1.
   (ii) Do it in a tight loop at simplifyTop, once all other constraints have
        finished. This is the current story.

Option (i) had many disadvantages:
   a) Firstly, it was deep inside the actual solver.
   b) Secondly, it was dependent on the context (Infer a type signature,
      or Check a type signature, or Interactive) since we did not want
      to always start defaulting when inferring (though there is an exception to
      this, see Note [Default while Inferring]).
   c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs:
          f :: Int -> Bool
          f x = const True (\y -> let w :: a -> a
                                      w a = const a (y+1)
                                  in w y)
      We will get an implication constraint (for beta the type of y):
               [untch=beta] forall a. 0 => Num beta
      which we really cannot default /while solving/ the implication, since beta is
      untouchable.

Instead our new defaulting story is to pull defaulting out of the solver loop and
go with option (ii), implemented at SimplifyTop. Namely:
     - First, have a go at solving the residual constraint of the whole
       program
     - Try to approximate it with a simple constraint
     - Figure out derived defaulting equations for that simple constraint
     - Go round the loop again if you did manage to get some equations

Now, that has to do with class defaulting. However there exists type variable /kind/
defaulting. Again this is done at the top-level and the plan is:
     - At the top-level, once you had a go at solving the constraint, do
       figure out /all/ the touchable unification variables of the wanted constraints.
     - Apply defaulting to their kinds

More details in Note [DefaultTyVar].

Note [Safe Haskell Overlapping Instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Safe Haskell, we apply an extra restriction to overlapping instances. The
motive is to prevent untrusted code provided by a third-party, changing the
behavior of trusted code through type-classes. This is due to the global and
implicit nature of type-classes that can hide the source of the dictionary.

Another way to state this is: if a module M compiles without importing another
module N, changing M to import N shouldn't change the behavior of M.

Overlapping instances with type-classes can violate this principle. However,
overlapping instances aren't always unsafe. They are just unsafe when the most
selected dictionary comes from untrusted code (code compiled with -XSafe) and
overlaps instances provided by other modules.

In particular, in Safe Haskell at a call site with overlapping instances, we
apply the following rule to determine if it is a 'unsafe' overlap:

 1) Most specific instance, I1, defined in an `-XSafe` compiled module.
 2) I1 is an orphan instance or a MPTC.
 3) At least one overlapped instance, Ix, is both:
    A) from a different module than I1
    B) Ix is not marked `OVERLAPPABLE`

This is a slightly involved heuristic, but captures the situation of an
imported module N changing the behavior of existing code. For example, if
condition (2) isn't violated, then the module author M must depend either on a
type-class or type defined in N.

Secondly, when should these heuristics be enforced? We enforced them when the
type-class method call site is in a module marked `-XSafe` or `-XTrustworthy`.
This allows `-XUnsafe` modules to operate without restriction, and for Safe
Haskell inferrence to infer modules with unsafe overlaps as unsafe.

One alternative design would be to also consider if an instance was imported as
a `safe` import or not and only apply the restriction to instances imported
safely. However, since instances are global and can be imported through more
than one path, this alternative doesn't work.

Note [Safe Haskell Overlapping Instances Implementation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

How is this implemented? It's complicated! So we'll step through it all:

 1) `InstEnv.lookupInstEnv` -- Performs instance resolution, so this is where
    we check if a particular type-class method call is safe or unsafe. We do this
    through the return type, `ClsInstLookupResult`, where the last parameter is a
    list of instances that are unsafe to overlap. When the method call is safe,
    the list is null.

 2) `GHC.Tc.Solver.Interact.matchClassInst` -- This module drives the instance resolution
    / dictionary generation. The return type is `ClsInstResult`, which either
    says no instance matched, or one found, and if it was a safe or unsafe
    overlap.

 3) `GHC.Tc.Solver.Interact.doTopReactDict` -- Takes a dictionary / class constraint and
     tries to resolve it by calling (in part) `matchClassInst`. The resolving
     mechanism has a work list (of constraints) that it process one at a time. If
     the constraint can't be resolved, it's added to an inert set. When compiling
     an `-XSafe` or `-XTrustworthy` module, we follow this approach as we know
     compilation should fail. These are handled as normal constraint resolution
     failures from here-on (see step 6).

     Otherwise, we may be inferring safety (or using `-Wunsafe`), and
     compilation should succeed, but print warnings and/or mark the compiled module
     as `-XUnsafe`. In this case, we call `insertSafeOverlapFailureTcS` which adds
     the unsafe (but resolved!) constraint to the `inert_safehask` field of
     `InertCans`.

 4) `GHC.Tc.Solver.simplifyTop`:
       * Call simpl_top, the top-level function for driving the simplifier for
         constraint resolution.

       * Once finished, call `getSafeOverlapFailures` to retrieve the
         list of overlapping instances that were successfully resolved,
         but unsafe. Remember, this is only applicable for generating warnings
         (`-Wunsafe`) or inferring a module unsafe. `-XSafe` and `-XTrustworthy`
         cause compilation failure by not resolving the unsafe constraint at all.

       * For unresolved constraints (all types), call `GHC.Tc.Errors.reportUnsolved`,
         while for resolved but unsafe overlapping dictionary constraints, call
         `GHC.Tc.Errors.warnAllUnsolved`. Both functions convert constraints into a
         warning message for the user.

       * In the case of `warnAllUnsolved` for resolved, but unsafe
         dictionary constraints, we collect the generated warning
         message (pop it) and call `GHC.Tc.Utils.Monad.recordUnsafeInfer` to
         mark the module we are compiling as unsafe, passing the
         warning message along as the reason.

 5) `GHC.Tc.Errors.*Unsolved` -- Generates error messages for constraints by
    actually calling `InstEnv.lookupInstEnv` again! Yes, confusing, but all we
    know is the constraint that is unresolved or unsafe. For dictionary, all we
    know is that we need a dictionary of type C, but not what instances are
    available and how they overlap. So we once again call `lookupInstEnv` to
    figure that out so we can generate a helpful error message.

 6) `GHC.Tc.Utils.Monad.recordUnsafeInfer` -- Save the unsafe result and reason in an
      IORef called `tcg_safeInfer`.

 7) `GHC.Driver.Main.tcRnModule'` -- Reads `tcg_safeInfer` after type-checking, calling
    `GHC.Driver.Main.markUnsafeInfer` (passing the reason along) when safe-inferrence
    failed.

Note [No defaulting in the ambiguity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When simplifying constraints for the ambiguity check, we use
solveWantedsAndDrop, not simpl_top, so that we do no defaulting.
#11947 was an example:
   f :: Num a => Int -> Int
This is ambiguous of course, but we don't want to default the
(Num alpha) constraint to (Num Int)!  Doing so gives a defaulting
warning, but no error.

Note [Defaulting insolubles]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a set of wanteds is insoluble, we have no hope of accepting the
program. Yet we do not stop constraint solving, etc., because we may
simplify the wanteds to produce better error messages. So, once
we have an insoluble constraint, everything we do is just about producing
helpful error messages.

Should we default in this case or not? Let's look at an example (tcfail004):

  (f,g) = (1,2,3)

With defaulting, we get a conflict between (a0,b0) and (Integer,Integer,Integer).
Without defaulting, we get a conflict between (a0,b0) and (a1,b1,c1). I (Richard)
find the latter more helpful. Several other test cases (e.g. tcfail005) suggest
similarly. So: we should not do class defaulting with insolubles.

On the other hand, RuntimeRep-defaulting is different. Witness tcfail078:

  f :: Integer i => i
  f =               0

Without RuntimeRep-defaulting, we GHC suggests that Integer should have kind
TYPE r0 -> Constraint and then complains that r0 is actually untouchable
(presumably, because it can't be sure if `Integer i` entails an equality).
If we default, we are told of a clash between (* -> Constraint) and Constraint.
The latter seems far better, suggesting we *should* do RuntimeRep-defaulting
even on insolubles.

But, evidently, not always. Witness UnliftedNewtypesInfinite:

  newtype Foo = FooC (# Int#, Foo #)

This should fail with an occurs-check error on the kind of Foo (with -XUnliftedNewtypes).
If we default RuntimeRep-vars, we get

  Expecting a lifted type, but ‘(# Int#, Foo #)’ is unlifted

which is just plain wrong.

Conclusion: we should do RuntimeRep-defaulting on insolubles only when the user does not
want to hear about RuntimeRep stuff -- that is, when -fprint-explicit-runtime-reps
is not set.
-}

------------------
simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM ()
simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM ()
simplifyAmbiguityCheck Type
ty WantedConstraints
wanteds
  = do { String -> SDoc -> TcM ()
traceTc String
"simplifyAmbiguityCheck {" (String -> SDoc
text String
"type = " SDoc -> SDoc -> SDoc
<+> Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty SDoc -> SDoc -> SDoc
$$ String -> SDoc
text String
"wanted = " SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wanteds)
       ; (WantedConstraints
final_wc, EvBindMap
_) <- TcS WantedConstraints -> TcM (WantedConstraints, EvBindMap)
forall a. TcS a -> TcM (a, EvBindMap)
runTcS (TcS WantedConstraints -> TcM (WantedConstraints, EvBindMap))
-> TcS WantedConstraints -> TcM (WantedConstraints, EvBindMap)
forall a b. (a -> b) -> a -> b
$ WantedConstraints -> TcS WantedConstraints
solveWantedsAndDrop WantedConstraints
wanteds
             -- NB: no defaulting!  See Note [No defaulting in the ambiguity check]

       ; String -> SDoc -> TcM ()
traceTc String
"End simplifyAmbiguityCheck }" SDoc
empty

       -- Normally report all errors; but with -XAllowAmbiguousTypes
       -- report only insoluble ones, since they represent genuinely
       -- inaccessible code
       ; Bool
allow_ambiguous <- Extension -> TcM Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.AllowAmbiguousTypes
       ; String -> SDoc -> TcM ()
traceTc String
"reportUnsolved(ambig) {" SDoc
empty
       ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Bool
allow_ambiguous Bool -> Bool -> Bool
&& Bool -> Bool
not (WantedConstraints -> Bool
insolubleWC WantedConstraints
final_wc))
                (TcM (Bag EvBind) -> TcM ()
forall a. TcM a -> TcM ()
discardResult (WantedConstraints -> TcM (Bag EvBind)
reportUnsolved WantedConstraints
final_wc))
       ; String -> SDoc -> TcM ()
traceTc String
"reportUnsolved(ambig) }" SDoc
empty

       ; () -> TcM ()
forall (m :: * -> *) a. Monad m => a -> m a
return () }

------------------
simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
simplifyInteractive WantedConstraints
wanteds
  = String -> SDoc -> TcM ()
traceTc String
"simplifyInteractive" SDoc
empty TcM () -> TcM (Bag EvBind) -> TcM (Bag EvBind)
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>
    WantedConstraints -> TcM (Bag EvBind)
simplifyTop WantedConstraints
wanteds

------------------
simplifyDefault :: ThetaType    -- Wanted; has no type variables in it
                -> TcM ()       -- Succeeds if the constraint is soluble
simplifyDefault :: [Type] -> TcM ()
simplifyDefault [Type]
theta
  = do { String -> SDoc -> TcM ()
traceTc String
"simplifyDefault" SDoc
empty
       ; [CtEvidence]
wanteds  <- CtOrigin -> [Type] -> TcM [CtEvidence]
newWanteds CtOrigin
DefaultOrigin [Type]
theta
       ; WantedConstraints
unsolved <- TcS WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a. TcS a -> TcM a
runTcSDeriveds (WantedConstraints -> TcS WantedConstraints
solveWantedsAndDrop ([CtEvidence] -> WantedConstraints
mkSimpleWC [CtEvidence]
wanteds))
       ; WantedConstraints -> TcM ()
reportAllUnsolved WantedConstraints
unsolved
       ; () -> TcM ()
forall (m :: * -> *) a. Monad m => a -> m a
return () }

------------------
tcCheckSatisfiability :: Bag EvVar -> TcM Bool
-- Return True if satisfiable, False if definitely contradictory
tcCheckSatisfiability :: Bag TcTyVar -> TcM Bool
tcCheckSatisfiability Bag TcTyVar
given_ids
  = do { TcLclEnv
lcl_env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
TcM.getLclEnv
       ; let given_loc :: CtLoc
given_loc = TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
mkGivenLoc TcLevel
topTcLevel SkolemInfo
UnkSkol TcLclEnv
lcl_env
       ; (Bool
res, EvBindMap
_ev_binds) <- TcS Bool -> TcM (Bool, EvBindMap)
forall a. TcS a -> TcM (a, EvBindMap)
runTcS (TcS Bool -> TcM (Bool, EvBindMap))
-> TcS Bool -> TcM (Bool, EvBindMap)
forall a b. (a -> b) -> a -> b
$
             do { String -> SDoc -> TcS ()
traceTcS String
"checkSatisfiability {" (Bag TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TcTyVar
given_ids)
                ; let given_cts :: [Ct]
given_cts = CtLoc -> [TcTyVar] -> [Ct]
mkGivens CtLoc
given_loc (Bag TcTyVar -> [TcTyVar]
forall a. Bag a -> [a]
bagToList Bag TcTyVar
given_ids)
                     -- See Note [Superclasses and satisfiability]
                ; [Ct] -> TcS ()
solveSimpleGivens [Ct]
given_cts
                ; Cts
insols <- TcS Cts
getInertInsols
                ; Cts
insols <- Cts -> TcS Cts
try_harder Cts
insols
                ; String -> SDoc -> TcS ()
traceTcS String
"checkSatisfiability }" (Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
insols)
                ; Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (Cts -> Bool
forall a. Bag a -> Bool
isEmptyBag Cts
insols) }
       ; Bool -> TcM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
res }
 where
    try_harder :: Cts -> TcS Cts
    -- Maybe we have to search up the superclass chain to find
    -- an unsatisfiable constraint.  Example: pmcheck/T3927b.
    -- At the moment we try just once
    try_harder :: Cts -> TcS Cts
try_harder Cts
insols
      | Bool -> Bool
not (Cts -> Bool
forall a. Bag a -> Bool
isEmptyBag Cts
insols)   -- We've found that it's definitely unsatisfiable
      = Cts -> TcS Cts
forall (m :: * -> *) a. Monad m => a -> m a
return Cts
insols             -- Hurrah -- stop now.
      | Bool
otherwise
      = do { [Ct]
pending_given <- TcS [Ct]
getPendingGivenScs
           ; [Ct]
new_given <- [Ct] -> TcS [Ct]
makeSuperClasses [Ct]
pending_given
           ; [Ct] -> TcS ()
solveSimpleGivens [Ct]
new_given
           ; TcS Cts
getInertInsols }

-- | Normalise a type as much as possible using the given constraints.
-- See @Note [tcNormalise]@.
tcNormalise :: Bag EvVar -> Type -> TcM Type
tcNormalise :: Bag TcTyVar -> Type -> TcM Type
tcNormalise Bag TcTyVar
given_ids Type
ty
  = do { TcLclEnv
lcl_env <- TcRnIf TcGblEnv TcLclEnv TcLclEnv
forall gbl lcl. TcRnIf gbl lcl lcl
TcM.getLclEnv
       ; let given_loc :: CtLoc
given_loc = TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
mkGivenLoc TcLevel
topTcLevel SkolemInfo
UnkSkol TcLclEnv
lcl_env
       ; CtLoc
norm_loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
PatCheckOrigin Maybe TypeOrKind
forall a. Maybe a
Nothing
       ; (Type
res, EvBindMap
_ev_binds) <- TcS Type -> TcM (Type, EvBindMap)
forall a. TcS a -> TcM (a, EvBindMap)
runTcS (TcS Type -> TcM (Type, EvBindMap))
-> TcS Type -> TcM (Type, EvBindMap)
forall a b. (a -> b) -> a -> b
$
             do { String -> SDoc -> TcS ()
traceTcS String
"tcNormalise {" (Bag TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag TcTyVar
given_ids)
                ; let given_cts :: [Ct]
given_cts = CtLoc -> [TcTyVar] -> [Ct]
mkGivens CtLoc
given_loc (Bag TcTyVar -> [TcTyVar]
forall a. Bag a -> [a]
bagToList Bag TcTyVar
given_ids)
                ; [Ct] -> TcS ()
solveSimpleGivens [Ct]
given_cts
                ; Type
ty' <- CtLoc -> Type -> TcS Type
flattenType CtLoc
norm_loc Type
ty
                ; String -> SDoc -> TcS ()
traceTcS String
"tcNormalise }" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
ty')
                ; Type -> TcS Type
forall (f :: * -> *) a. Applicative f => a -> f a
pure Type
ty' }
       ; Type -> TcM Type
forall (m :: * -> *) a. Monad m => a -> m a
return Type
res }

{- Note [Superclasses and satisfiability]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand superclasses before starting, because (Int ~ Bool), has
(Int ~~ Bool) as a superclass, which in turn has (Int ~N# Bool)
as a superclass, and it's the latter that is insoluble.  See
Note [The equality types story] in GHC.Builtin.Types.Prim.

If we fail to prove unsatisfiability we (arbitrarily) try just once to
find superclasses, using try_harder.  Reason: we might have a type
signature
   f :: F op (Implements push) => ..
where F is a type function.  This happened in #3972.

We could do more than once but we'd have to have /some/ limit: in the
the recursive case, we would go on forever in the common case where
the constraints /are/ satisfiable (#10592 comment:12!).

For stratightforard situations without type functions the try_harder
step does nothing.

Note [tcNormalise]
~~~~~~~~~~~~~~~~~~
tcNormalise is a rather atypical entrypoint to the constraint solver. Whereas
most invocations of the constraint solver are intended to simplify a set of
constraints or to decide if a particular set of constraints is satisfiable,
the purpose of tcNormalise is to take a type, plus some local constraints, and
normalise the type as much as possible with respect to those constraints.

It does *not* reduce type or data family applications or look through newtypes.

Why is this useful? As one example, when coverage-checking an EmptyCase
expression, it's possible that the type of the scrutinee will only reduce
if some local equalities are solved for. See "Wrinkle: Local equalities"
in Note [Type normalisation] in "GHC.HsToCore.PmCheck".

To accomplish its stated goal, tcNormalise first feeds the local constraints
into solveSimpleGivens, then uses flattenType to simplify the desired type
with respect to the givens.

***********************************************************************************
*                                                                                 *
*                            Inference
*                                                                                 *
***********************************************************************************

Note [Inferring the type of a let-bound variable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   f x = rhs

To infer f's type we do the following:
 * Gather the constraints for the RHS with ambient level *one more than*
   the current one.  This is done by the call
        pushLevelAndCaptureConstraints (tcMonoBinds...)
   in GHC.Tc.Gen.Bind.tcPolyInfer

 * Call simplifyInfer to simplify the constraints and decide what to
   quantify over. We pass in the level used for the RHS constraints,
   here called rhs_tclvl.

This ensures that the implication constraint we generate, if any,
has a strictly-increased level compared to the ambient level outside
the let binding.

-}

-- | How should we choose which constraints to quantify over?
data InferMode = ApplyMR          -- ^ Apply the monomorphism restriction,
                                  -- never quantifying over any constraints
               | EagerDefaulting  -- ^ See Note [TcRnExprMode] in "GHC.Tc.Module",
                                  -- the :type +d case; this mode refuses
                                  -- to quantify over any defaultable constraint
               | NoRestrictions   -- ^ Quantify over any constraint that
                                  -- satisfies 'GHC.Tc.Utils.TcType.pickQuantifiablePreds'

instance Outputable InferMode where
  ppr :: InferMode -> SDoc
ppr InferMode
ApplyMR         = String -> SDoc
text String
"ApplyMR"
  ppr InferMode
EagerDefaulting = String -> SDoc
text String
"EagerDefaulting"
  ppr InferMode
NoRestrictions  = String -> SDoc
text String
"NoRestrictions"

simplifyInfer :: TcLevel               -- Used when generating the constraints
              -> InferMode
              -> [TcIdSigInst]         -- Any signatures (possibly partial)
              -> [(Name, TcTauType)]   -- Variables to be generalised,
                                       -- and their tau-types
              -> WantedConstraints
              -> TcM ([TcTyVar],    -- Quantify over these type variables
                      [EvVar],      -- ... and these constraints (fully zonked)
                      TcEvBinds,    -- ... binding these evidence variables
                      WantedConstraints, -- Redidual as-yet-unsolved constraints
                      Bool)         -- True <=> the residual constraints are insoluble

simplifyInfer :: TcLevel
-> InferMode
-> [TcIdSigInst]
-> [(Name, Type)]
-> WantedConstraints
-> TcM ([TcTyVar], [TcTyVar], TcEvBinds, WantedConstraints, Bool)
simplifyInfer TcLevel
rhs_tclvl InferMode
infer_mode [TcIdSigInst]
sigs [(Name, Type)]
name_taus WantedConstraints
wanteds
  | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanteds
   = do { -- When quantifying, we want to preserve any order of variables as they
          -- appear in partial signatures. cf. decideQuantifiedTyVars
          let psig_tv_tys :: [Type]
psig_tv_tys = [ TcTyVar -> Type
mkTyVarTy TcTyVar
tv | TcIdSigInst
sig <- [TcIdSigInst]
partial_sigs
                                          , (Name
_,Bndr TcTyVar
tv Specificity
_) <- TcIdSigInst -> [(Name, InvisTVBinder)]
sig_inst_skols TcIdSigInst
sig ]
              psig_theta :: [Type]
psig_theta  = [ Type
pred | TcIdSigInst
sig <- [TcIdSigInst]
partial_sigs
                                   , Type
pred <- TcIdSigInst -> [Type]
sig_inst_theta TcIdSigInst
sig ]

       ; CandidatesQTvs
dep_vars <- [Type] -> TcM CandidatesQTvs
candidateQTyVarsOfTypes ([Type]
psig_tv_tys [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
psig_theta [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ ((Name, Type) -> Type) -> [(Name, Type)] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map (Name, Type) -> Type
forall a b. (a, b) -> b
snd [(Name, Type)]
name_taus)
       ; [TcTyVar]
qtkvs <- CandidatesQTvs -> TcM [TcTyVar]
quantifyTyVars CandidatesQTvs
dep_vars
       ; String -> SDoc -> TcM ()
traceTc String
"simplifyInfer: empty WC" ([(Name, Type)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, Type)]
name_taus SDoc -> SDoc -> SDoc
$$ [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
qtkvs)
       ; ([TcTyVar], [TcTyVar], TcEvBinds, WantedConstraints, Bool)
-> TcM ([TcTyVar], [TcTyVar], TcEvBinds, WantedConstraints, Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar]
qtkvs, [], TcEvBinds
emptyTcEvBinds, WantedConstraints
emptyWC, Bool
False) }

  | Bool
otherwise
  = do { String -> SDoc -> TcM ()
traceTc String
"simplifyInfer {"  (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
vcat
             [ String -> SDoc
text String
"sigs =" SDoc -> SDoc -> SDoc
<+> [TcIdSigInst] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcIdSigInst]
sigs
             , String -> SDoc
text String
"binds =" SDoc -> SDoc -> SDoc
<+> [(Name, Type)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(Name, Type)]
name_taus
             , String -> SDoc
text String
"rhs_tclvl =" SDoc -> SDoc -> SDoc
<+> TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
rhs_tclvl
             , String -> SDoc
text String
"infer_mode =" SDoc -> SDoc -> SDoc
<+> InferMode -> SDoc
forall a. Outputable a => a -> SDoc
ppr InferMode
infer_mode
             , String -> SDoc
text String
"(unzonked) wanted =" SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wanteds
             ]

       ; let psig_theta :: [Type]
psig_theta = (TcIdSigInst -> [Type]) -> [TcIdSigInst] -> [Type]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap TcIdSigInst -> [Type]
sig_inst_theta [TcIdSigInst]
partial_sigs

       -- First do full-blown solving
       -- NB: we must gather up all the bindings from doing
       -- this solving; hence (runTcSWithEvBinds ev_binds_var).
       -- And note that since there are nested implications,
       -- calling solveWanteds will side-effect their evidence
       -- bindings, so we can't just revert to the input
       -- constraint.

       ; Env TcGblEnv TcLclEnv
tc_env          <- IOEnv (Env TcGblEnv TcLclEnv) (Env TcGblEnv TcLclEnv)
forall env. IOEnv env env
TcM.getEnv
       ; EvBindsVar
ev_binds_var    <- TcM EvBindsVar
TcM.newTcEvBinds
       ; [TcTyVar]
psig_theta_vars <- (Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> [Type] -> TcM [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall gbl lcl. Type -> TcRnIf gbl lcl TcTyVar
TcM.newEvVar [Type]
psig_theta
       ; WantedConstraints
wanted_transformed_incl_derivs
            <- TcLevel
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a. TcLevel -> TcM a -> TcM a
setTcLevel TcLevel
rhs_tclvl (TcRnIf TcGblEnv TcLclEnv WantedConstraints
 -> TcRnIf TcGblEnv TcLclEnv WantedConstraints)
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a b. (a -> b) -> a -> b
$
               EvBindsVar
-> TcS WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a. EvBindsVar -> TcS a -> TcM a
runTcSWithEvBinds EvBindsVar
ev_binds_var (TcS WantedConstraints
 -> TcRnIf TcGblEnv TcLclEnv WantedConstraints)
-> TcS WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a b. (a -> b) -> a -> b
$
               do { let loc :: CtLoc
loc         = TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
mkGivenLoc TcLevel
rhs_tclvl SkolemInfo
UnkSkol (TcLclEnv -> CtLoc) -> TcLclEnv -> CtLoc
forall a b. (a -> b) -> a -> b
$
                                      Env TcGblEnv TcLclEnv -> TcLclEnv
forall gbl lcl. Env gbl lcl -> lcl
env_lcl Env TcGblEnv TcLclEnv
tc_env
                        psig_givens :: [Ct]
psig_givens = CtLoc -> [TcTyVar] -> [Ct]
mkGivens CtLoc
loc [TcTyVar]
psig_theta_vars
                  ; ()
_ <- [Ct] -> TcS ()
solveSimpleGivens [Ct]
psig_givens
                         -- See Note [Add signature contexts as givens]
                  ; WantedConstraints -> TcS WantedConstraints
solveWanteds WantedConstraints
wanteds }

       -- Find quant_pred_candidates, the predicates that
       -- we'll consider quantifying over
       -- NB1: wanted_transformed does not include anything provable from
       --      the psig_theta; it's just the extra bit
       -- NB2: We do not do any defaulting when inferring a type, this can lead
       --      to less polymorphic types, see Note [Default while Inferring]
       ; WantedConstraints
wanted_transformed_incl_derivs <- WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
TcM.zonkWC WantedConstraints
wanted_transformed_incl_derivs
       ; let definite_error :: Bool
definite_error = WantedConstraints -> Bool
insolubleWC WantedConstraints
wanted_transformed_incl_derivs
                              -- See Note [Quantification with errors]
                              -- NB: must include derived errors in this test,
                              --     hence "incl_derivs"
             wanted_transformed :: WantedConstraints
wanted_transformed = WantedConstraints -> WantedConstraints
dropDerivedWC WantedConstraints
wanted_transformed_incl_derivs
             quant_pred_candidates :: [Type]
quant_pred_candidates
               | Bool
definite_error = []
               | Bool
otherwise      = Cts -> [Type]
ctsPreds (Bool -> WantedConstraints -> Cts
approximateWC Bool
False WantedConstraints
wanted_transformed)

       -- Decide what type variables and constraints to quantify
       -- NB: quant_pred_candidates is already fully zonked
       -- NB: bound_theta are constraints we want to quantify over,
       --     including the psig_theta, which we always quantify over
       -- NB: bound_theta are fully zonked
       ; ([TcTyVar]
qtvs, [Type]
bound_theta, VarSet
co_vars) <- InferMode
-> TcLevel
-> [(Name, Type)]
-> [TcIdSigInst]
-> [Type]
-> TcM ([TcTyVar], [Type], VarSet)
decideQuantification InferMode
infer_mode TcLevel
rhs_tclvl
                                                     [(Name, Type)]
name_taus [TcIdSigInst]
partial_sigs
                                                     [Type]
quant_pred_candidates
       ; [TcTyVar]
bound_theta_vars <- (Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> [Type] -> TcM [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Type -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
forall gbl lcl. Type -> TcRnIf gbl lcl TcTyVar
TcM.newEvVar [Type]
bound_theta

       -- We must produce bindings for the psig_theta_vars, because we may have
       -- used them in evidence bindings constructed by solveWanteds earlier
       -- Easiest way to do this is to emit them as new Wanteds (#14643)
       ; CtLoc
ct_loc <- CtOrigin -> Maybe TypeOrKind -> TcM CtLoc
getCtLocM CtOrigin
AnnOrigin Maybe TypeOrKind
forall a. Maybe a
Nothing
       ; let psig_wanted :: [CtEvidence]
psig_wanted = [ CtWanted :: Type -> TcEvDest -> ShadowInfo -> CtLoc -> CtEvidence
CtWanted { ctev_pred :: Type
ctev_pred = TcTyVar -> Type
idType TcTyVar
psig_theta_var
                                      , ctev_dest :: TcEvDest
ctev_dest = TcTyVar -> TcEvDest
EvVarDest TcTyVar
psig_theta_var
                                      , ctev_nosh :: ShadowInfo
ctev_nosh = ShadowInfo
WDeriv
                                      , ctev_loc :: CtLoc
ctev_loc  = CtLoc
ct_loc }
                           | TcTyVar
psig_theta_var <- [TcTyVar]
psig_theta_vars ]

       -- Now construct the residual constraint
       ; WantedConstraints
residual_wanted <- TcLevel
-> EvBindsVar
-> [(Name, Type)]
-> VarSet
-> [TcTyVar]
-> [TcTyVar]
-> WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
mkResidualConstraints TcLevel
rhs_tclvl EvBindsVar
ev_binds_var
                                 [(Name, Type)]
name_taus VarSet
co_vars [TcTyVar]
qtvs [TcTyVar]
bound_theta_vars
                                 (WantedConstraints
wanted_transformed WantedConstraints -> WantedConstraints -> WantedConstraints
`andWC` [CtEvidence] -> WantedConstraints
mkSimpleWC [CtEvidence]
psig_wanted)

         -- All done!
       ; String -> SDoc -> TcM ()
traceTc String
"} simplifyInfer/produced residual implication for quantification" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"quant_pred_candidates =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
quant_pred_candidates
              , String -> SDoc
text String
"psig_theta =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
psig_theta
              , String -> SDoc
text String
"bound_theta =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
bound_theta
              , String -> SDoc
text String
"qtvs ="       SDoc -> SDoc -> SDoc
<+> [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
qtvs
              , String -> SDoc
text String
"definite_error =" SDoc -> SDoc -> SDoc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
definite_error ]

       ; ([TcTyVar], [TcTyVar], TcEvBinds, WantedConstraints, Bool)
-> TcM ([TcTyVar], [TcTyVar], TcEvBinds, WantedConstraints, Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return ( [TcTyVar]
qtvs, [TcTyVar]
bound_theta_vars, EvBindsVar -> TcEvBinds
TcEvBinds EvBindsVar
ev_binds_var
                , WantedConstraints
residual_wanted, Bool
definite_error ) }
         -- NB: bound_theta_vars must be fully zonked
  where
    partial_sigs :: [TcIdSigInst]
partial_sigs = (TcIdSigInst -> Bool) -> [TcIdSigInst] -> [TcIdSigInst]
forall a. (a -> Bool) -> [a] -> [a]
filter TcIdSigInst -> Bool
isPartialSig [TcIdSigInst]
sigs

--------------------
mkResidualConstraints :: TcLevel -> EvBindsVar
                      -> [(Name, TcTauType)]
                      -> VarSet -> [TcTyVar] -> [EvVar]
                      -> WantedConstraints -> TcM WantedConstraints
-- Emit the remaining constraints from the RHS.
-- See Note [Emitting the residual implication in simplifyInfer]
mkResidualConstraints :: TcLevel
-> EvBindsVar
-> [(Name, Type)]
-> VarSet
-> [TcTyVar]
-> [TcTyVar]
-> WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
mkResidualConstraints TcLevel
rhs_tclvl EvBindsVar
ev_binds_var
                        [(Name, Type)]
name_taus VarSet
co_vars [TcTyVar]
qtvs [TcTyVar]
full_theta_vars WantedConstraints
wanteds
  | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanteds
  = WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
wanteds

  | Bool
otherwise
  = do { Cts
wanted_simple <- Cts -> TcM Cts
TcM.zonkSimples (WantedConstraints -> Cts
wc_simple WantedConstraints
wanteds)
       ; let (Cts
outer_simple, Cts
inner_simple) = (Ct -> Bool) -> Cts -> (Cts, Cts)
forall a. (a -> Bool) -> Bag a -> (Bag a, Bag a)
partitionBag Ct -> Bool
is_mono Cts
wanted_simple
             is_mono :: Ct -> Bool
is_mono Ct
ct = Ct -> Bool
isWantedCt Ct
ct Bool -> Bool -> Bool
&& Ct -> TcTyVar
ctEvId Ct
ct TcTyVar -> VarSet -> Bool
`elemVarSet` VarSet
co_vars

        ; Bool
_ <- VarSet -> TcM Bool
promoteTyVarSet (Cts -> VarSet
tyCoVarsOfCts Cts
outer_simple)

        ; let inner_wanted :: WantedConstraints
inner_wanted = WantedConstraints
wanteds { wc_simple :: Cts
wc_simple = Cts
inner_simple }
        ; Bag Implication
implics <- if WantedConstraints -> Bool
isEmptyWC WantedConstraints
inner_wanted
                     then Bag Implication -> IOEnv (Env TcGblEnv TcLclEnv) (Bag Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return Bag Implication
forall a. Bag a
emptyBag
                     else do Implication
implic1 <- TcM Implication
newImplication
                             Bag Implication -> IOEnv (Env TcGblEnv TcLclEnv) (Bag Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Bag Implication
 -> IOEnv (Env TcGblEnv TcLclEnv) (Bag Implication))
-> Bag Implication
-> IOEnv (Env TcGblEnv TcLclEnv) (Bag Implication)
forall a b. (a -> b) -> a -> b
$ Implication -> Bag Implication
forall a. a -> Bag a
unitBag (Implication -> Bag Implication) -> Implication -> Bag Implication
forall a b. (a -> b) -> a -> b
$
                                      Implication
implic1  { ic_tclvl :: TcLevel
ic_tclvl  = TcLevel
rhs_tclvl
                                               , ic_skols :: [TcTyVar]
ic_skols  = [TcTyVar]
qtvs
                                               , ic_given :: [TcTyVar]
ic_given  = [TcTyVar]
full_theta_vars
                                               , ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
inner_wanted
                                               , ic_binds :: EvBindsVar
ic_binds  = EvBindsVar
ev_binds_var
                                               , ic_no_eqs :: Bool
ic_no_eqs = Bool
False
                                               , ic_info :: SkolemInfo
ic_info   = SkolemInfo
skol_info }

        ; WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return (WantedConstraints
emptyWC { wc_simple :: Cts
wc_simple = Cts
outer_simple
                          , wc_impl :: Bag Implication
wc_impl   = Bag Implication
implics })}
  where
    full_theta :: [Type]
full_theta = (TcTyVar -> Type) -> [TcTyVar] -> [Type]
forall a b. (a -> b) -> [a] -> [b]
map TcTyVar -> Type
idType [TcTyVar]
full_theta_vars
    skol_info :: SkolemInfo
skol_info  = [(Name, Type)] -> SkolemInfo
InferSkol [ (Name
name, [TyCoVarBinder] -> [Type] -> Type -> Type
mkSigmaTy [] [Type]
full_theta Type
ty)
                           | (Name
name, Type
ty) <- [(Name, Type)]
name_taus ]
                 -- Don't add the quantified variables here, because
                 -- they are also bound in ic_skols and we want them
                 -- to be tidied uniformly

--------------------
ctsPreds :: Cts -> [PredType]
ctsPreds :: Cts -> [Type]
ctsPreds Cts
cts = [ CtEvidence -> Type
ctEvPred CtEvidence
ev | Ct
ct <- Cts -> [Ct]
forall a. Bag a -> [a]
bagToList Cts
cts
                             , let ev :: CtEvidence
ev = Ct -> CtEvidence
ctEvidence Ct
ct ]

{- Note [Emitting the residual implication in simplifyInfer]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   f = e
where f's type is inferred to be something like (a, Proxy k (Int |> co))
and we have an as-yet-unsolved, or perhaps insoluble, constraint
   [W] co :: Type ~ k
We can't form types like (forall co. blah), so we can't generalise over
the coercion variable, and hence we can't generalise over things free in
its kind, in the case 'k'.  But we can still generalise over 'a'.  So
we'll generalise to
   f :: forall a. (a, Proxy k (Int |> co))
Now we do NOT want to form the residual implication constraint
   forall a. [W] co :: Type ~ k
because then co's eventual binding (which will be a value binding if we
use -fdefer-type-errors) won't scope over the entire binding for 'f' (whose
type mentions 'co').  Instead, just as we don't generalise over 'co', we
should not bury its constraint inside the implication.  Instead, we must
put it outside.

That is the reason for the partitionBag in emitResidualConstraints,
which takes the CoVars free in the inferred type, and pulls their
constraints out.  (NB: this set of CoVars should be closed-over-kinds.)

All rather subtle; see #14584.

Note [Add signature contexts as givens]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#11016):
  f2 :: (?x :: Int) => _
  f2 = ?x
or this
  f3 :: a ~ Bool => (a, _)
  f3 = (True, False)
or theis
  f4 :: (Ord a, _) => a -> Bool
  f4 x = x==x

We'll use plan InferGen because there are holes in the type.  But:
 * For f2 we want to have the (?x :: Int) constraint floating around
   so that the functional dependencies kick in.  Otherwise the
   occurrence of ?x on the RHS produces constraint (?x :: alpha), and
   we won't unify alpha:=Int.
 * For f3 we want the (a ~ Bool) available to solve the wanted (a ~ Bool)
   in the RHS
 * For f4 we want to use the (Ord a) in the signature to solve the Eq a
   constraint.

Solution: in simplifyInfer, just before simplifying the constraints
gathered from the RHS, add Given constraints for the context of any
type signatures.

************************************************************************
*                                                                      *
                Quantification
*                                                                      *
************************************************************************

Note [Deciding quantification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the monomorphism restriction does not apply, then we quantify as follows:

* Step 1. Take the global tyvars, and "grow" them using the equality
  constraints
     E.g.  if x:alpha is in the environment, and alpha ~ [beta] (which can
          happen because alpha is untouchable here) then do not quantify over
          beta, because alpha fixes beta, and beta is effectively free in
          the environment too

  We also account for the monomorphism restriction; if it applies,
  add the free vars of all the constraints.

  Result is mono_tvs; we will not quantify over these.

* Step 2. Default any non-mono tyvars (i.e ones that are definitely
  not going to become further constrained), and re-simplify the
  candidate constraints.

  Motivation for re-simplification (#7857): imagine we have a
  constraint (C (a->b)), where 'a :: TYPE l1' and 'b :: TYPE l2' are
  not free in the envt, and instance forall (a::*) (b::*). (C a) => C
  (a -> b) The instance doesn't match while l1,l2 are polymorphic, but
  it will match when we default them to LiftedRep.

  This is all very tiresome.

* Step 3: decide which variables to quantify over, as follows:

  - Take the free vars of the tau-type (zonked_tau_tvs) and "grow"
    them using all the constraints.  These are tau_tvs_plus

  - Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being
    careful to close over kinds, and to skolemise the quantified tyvars.
    (This actually unifies each quantifies meta-tyvar with a fresh skolem.)

  Result is qtvs.

* Step 4: Filter the constraints using pickQuantifiablePreds and the
  qtvs. We have to zonk the constraints first, so they "see" the
  freshly created skolems.

-}

decideQuantification
  :: InferMode
  -> TcLevel
  -> [(Name, TcTauType)]   -- Variables to be generalised
  -> [TcIdSigInst]         -- Partial type signatures (if any)
  -> [PredType]            -- Candidate theta; already zonked
  -> TcM ( [TcTyVar]       -- Quantify over these (skolems)
         , [PredType]      -- and this context (fully zonked)
         , VarSet)
-- See Note [Deciding quantification]
decideQuantification :: InferMode
-> TcLevel
-> [(Name, Type)]
-> [TcIdSigInst]
-> [Type]
-> TcM ([TcTyVar], [Type], VarSet)
decideQuantification InferMode
infer_mode TcLevel
rhs_tclvl [(Name, Type)]
name_taus [TcIdSigInst]
psigs [Type]
candidates
  = do { -- Step 1: find the mono_tvs
       ; (VarSet
mono_tvs, [Type]
candidates, VarSet
co_vars) <- InferMode
-> [(Name, Type)]
-> [TcIdSigInst]
-> [Type]
-> TcM (VarSet, [Type], VarSet)
decideMonoTyVars InferMode
infer_mode
                                              [(Name, Type)]
name_taus [TcIdSigInst]
psigs [Type]
candidates

       -- Step 2: default any non-mono tyvars, and re-simplify
       -- This step may do some unification, but result candidates is zonked
       ; [Type]
candidates <- TcLevel -> VarSet -> [Type] -> TcM [Type]
defaultTyVarsAndSimplify TcLevel
rhs_tclvl VarSet
mono_tvs [Type]
candidates

       -- Step 3: decide which kind/type variables to quantify over
       ; [TcTyVar]
qtvs <- [(Name, Type)] -> [TcIdSigInst] -> [Type] -> TcM [TcTyVar]
decideQuantifiedTyVars [(Name, Type)]
name_taus [TcIdSigInst]
psigs [Type]
candidates

       -- Step 4: choose which of the remaining candidate
       --         predicates to actually quantify over
       -- NB: decideQuantifiedTyVars turned some meta tyvars
       -- into quantified skolems, so we have to zonk again
       ; [Type]
candidates <- [Type] -> TcM [Type]
TcM.zonkTcTypes [Type]
candidates
       ; [Type]
psig_theta <- [Type] -> TcM [Type]
TcM.zonkTcTypes ((TcIdSigInst -> [Type]) -> [TcIdSigInst] -> [Type]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap TcIdSigInst -> [Type]
sig_inst_theta [TcIdSigInst]
psigs)
       ; let quantifiable_candidates :: [Type]
quantifiable_candidates
               = VarSet -> [Type] -> [Type]
pickQuantifiablePreds ([TcTyVar] -> VarSet
mkVarSet [TcTyVar]
qtvs) [Type]
candidates
             -- NB: do /not/ run pickQuantifiablePreds over psig_theta,
             -- because we always want to quantify over psig_theta, and not
             -- drop any of them; e.g. CallStack constraints.  c.f #14658

             theta :: [Type]
theta = (Type -> Type) -> [Type] -> [Type]
forall a. (a -> Type) -> [a] -> [a]
mkMinimalBySCs Type -> Type
forall a. a -> a
id ([Type] -> [Type]) -> [Type] -> [Type]
forall a b. (a -> b) -> a -> b
$  -- See Note [Minimize by Superclasses]
                     ([Type]
psig_theta [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
quantifiable_candidates)

       ; String -> SDoc -> TcM ()
traceTc String
"decideQuantification"
           ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"infer_mode:" SDoc -> SDoc -> SDoc
<+> InferMode -> SDoc
forall a. Outputable a => a -> SDoc
ppr InferMode
infer_mode
                 , String -> SDoc
text String
"candidates:" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
candidates
                 , String -> SDoc
text String
"psig_theta:" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
psig_theta
                 , String -> SDoc
text String
"mono_tvs:"   SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
mono_tvs
                 , String -> SDoc
text String
"co_vars:"    SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
co_vars
                 , String -> SDoc
text String
"qtvs:"       SDoc -> SDoc -> SDoc
<+> [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
qtvs
                 , String -> SDoc
text String
"theta:"      SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
theta ])
       ; ([TcTyVar], [Type], VarSet) -> TcM ([TcTyVar], [Type], VarSet)
forall (m :: * -> *) a. Monad m => a -> m a
return ([TcTyVar]
qtvs, [Type]
theta, VarSet
co_vars) }

------------------
decideMonoTyVars :: InferMode
                 -> [(Name,TcType)]
                 -> [TcIdSigInst]
                 -> [PredType]
                 -> TcM (TcTyCoVarSet, [PredType], CoVarSet)
-- Decide which tyvars and covars cannot be generalised:
--   (a) Free in the environment
--   (b) Mentioned in a constraint we can't generalise
--   (c) Connected by an equality to (a) or (b)
-- Also return CoVars that appear free in the final quantified types
--   we can't quantify over these, and we must make sure they are in scope
decideMonoTyVars :: InferMode
-> [(Name, Type)]
-> [TcIdSigInst]
-> [Type]
-> TcM (VarSet, [Type], VarSet)
decideMonoTyVars InferMode
infer_mode [(Name, Type)]
name_taus [TcIdSigInst]
psigs [Type]
candidates
  = do { ([Type]
no_quant, [Type]
maybe_quant) <- InferMode -> [Type] -> TcM ([Type], [Type])
pick InferMode
infer_mode [Type]
candidates

       -- If possible, we quantify over partial-sig qtvs, so they are
       -- not mono. Need to zonk them because they are meta-tyvar TyVarTvs
       ; [TcTyVar]
psig_qtvs <- (TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar)
-> [TcTyVar] -> TcM [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM HasDebugCallStack =>
TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
TcTyVar -> IOEnv (Env TcGblEnv TcLclEnv) TcTyVar
zonkTcTyVarToTyVar ([TcTyVar] -> TcM [TcTyVar]) -> [TcTyVar] -> TcM [TcTyVar]
forall a b. (a -> b) -> a -> b
$ [InvisTVBinder] -> [TcTyVar]
forall tv argf. [VarBndr tv argf] -> [tv]
binderVars ([InvisTVBinder] -> [TcTyVar]) -> [InvisTVBinder] -> [TcTyVar]
forall a b. (a -> b) -> a -> b
$
                      (TcIdSigInst -> [InvisTVBinder])
-> [TcIdSigInst] -> [InvisTVBinder]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (((Name, InvisTVBinder) -> InvisTVBinder)
-> [(Name, InvisTVBinder)] -> [InvisTVBinder]
forall a b. (a -> b) -> [a] -> [b]
map (Name, InvisTVBinder) -> InvisTVBinder
forall a b. (a, b) -> b
snd ([(Name, InvisTVBinder)] -> [InvisTVBinder])
-> (TcIdSigInst -> [(Name, InvisTVBinder)])
-> TcIdSigInst
-> [InvisTVBinder]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TcIdSigInst -> [(Name, InvisTVBinder)]
sig_inst_skols) [TcIdSigInst]
psigs

       ; [Type]
psig_theta <- (Type -> TcM Type) -> [Type] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Type -> TcM Type
TcM.zonkTcType ([Type] -> TcM [Type]) -> [Type] -> TcM [Type]
forall a b. (a -> b) -> a -> b
$
                       (TcIdSigInst -> [Type]) -> [TcIdSigInst] -> [Type]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap TcIdSigInst -> [Type]
sig_inst_theta [TcIdSigInst]
psigs

       ; [Type]
taus <- ((Name, Type) -> TcM Type) -> [(Name, Type)] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Type -> TcM Type
TcM.zonkTcType (Type -> TcM Type)
-> ((Name, Type) -> Type) -> (Name, Type) -> TcM Type
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name, Type) -> Type
forall a b. (a, b) -> b
snd) [(Name, Type)]
name_taus

       ; TcLevel
tc_lvl <- TcM TcLevel
TcM.getTcLevel
       ; let psig_tys :: [Type]
psig_tys = [TcTyVar] -> [Type]
mkTyVarTys [TcTyVar]
psig_qtvs [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
psig_theta

             co_vars :: VarSet
co_vars = [Type] -> VarSet
coVarsOfTypes ([Type]
psig_tys [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
taus)
             co_var_tvs :: VarSet
co_var_tvs = VarSet -> VarSet
closeOverKinds VarSet
co_vars
               -- The co_var_tvs are tvs mentioned in the types of covars or
               -- coercion holes. We can't quantify over these covars, so we
               -- must include the variable in their types in the mono_tvs.
               -- E.g.  If we can't quantify over co :: k~Type, then we can't
               --       quantify over k either!  Hence closeOverKinds

             mono_tvs0 :: VarSet
mono_tvs0 = (TcTyVar -> Bool) -> VarSet -> VarSet
filterVarSet (Bool -> Bool
not (Bool -> Bool) -> (TcTyVar -> Bool) -> TcTyVar -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TcLevel -> TcTyVar -> Bool
isQuantifiableTv TcLevel
tc_lvl) (VarSet -> VarSet) -> VarSet -> VarSet
forall a b. (a -> b) -> a -> b
$
                         [Type] -> VarSet
tyCoVarsOfTypes [Type]
candidates
               -- We need to grab all the non-quantifiable tyvars in the
               -- candidates so that we can grow this set to find other
               -- non-quantifiable tyvars. This can happen with something
               -- like
               --    f x y = ...
               --      where z = x 3
               -- The body of z tries to unify the type of x (call it alpha[1])
               -- with (beta[2] -> gamma[2]). This unification fails because
               -- alpha is untouchable. But we need to know not to quantify over
               -- beta or gamma, because they are in the equality constraint with
               -- alpha. Actual test case: typecheck/should_compile/tc213

             mono_tvs1 :: VarSet
mono_tvs1 = VarSet
mono_tvs0 VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
co_var_tvs

             eq_constraints :: [Type]
eq_constraints = (Type -> Bool) -> [Type] -> [Type]
forall a. (a -> Bool) -> [a] -> [a]
filter Type -> Bool
isEqPrimPred [Type]
candidates
             mono_tvs2 :: VarSet
mono_tvs2      = [Type] -> VarSet -> VarSet
growThetaTyVars [Type]
eq_constraints VarSet
mono_tvs1

             constrained_tvs :: VarSet
constrained_tvs = (TcTyVar -> Bool) -> VarSet -> VarSet
filterVarSet (TcLevel -> TcTyVar -> Bool
isQuantifiableTv TcLevel
tc_lvl) (VarSet -> VarSet) -> VarSet -> VarSet
forall a b. (a -> b) -> a -> b
$
                               ([Type] -> VarSet -> VarSet
growThetaTyVars [Type]
eq_constraints
                                               ([Type] -> VarSet
tyCoVarsOfTypes [Type]
no_quant)
                                VarSet -> VarSet -> VarSet
`minusVarSet` VarSet
mono_tvs2)
                               VarSet -> [TcTyVar] -> VarSet
`delVarSetList` [TcTyVar]
psig_qtvs
             -- constrained_tvs: the tyvars that we are not going to
             -- quantify solely because of the monomorphism restriction
             --
             -- (`minusVarSet` mono_tvs2`): a type variable is only
             --   "constrained" (so that the MR bites) if it is not
             --   free in the environment (#13785)
             --
             -- (`delVarSetList` psig_qtvs): if the user has explicitly
             --   asked for quantification, then that request "wins"
             --   over the MR.  Note: do /not/ delete psig_qtvs from
             --   mono_tvs1, because mono_tvs1 cannot under any circumstances
             --   be quantified (#14479); see
             --   Note [Quantification and partial signatures], Wrinkle 3, 4

             mono_tvs :: VarSet
mono_tvs = VarSet
mono_tvs2 VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
constrained_tvs

           -- Warn about the monomorphism restriction
       ; Bool
warn_mono <- WarningFlag -> TcM Bool
forall gbl lcl. WarningFlag -> TcRnIf gbl lcl Bool
woptM WarningFlag
Opt_WarnMonomorphism
       ; Bool -> TcM () -> TcM ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (case InferMode
infer_mode of { InferMode
ApplyMR -> Bool
warn_mono; InferMode
_ -> Bool
False}) (TcM () -> TcM ()) -> TcM () -> TcM ()
forall a b. (a -> b) -> a -> b
$
         WarnReason -> Bool -> SDoc -> TcM ()
warnTc (WarningFlag -> WarnReason
Reason WarningFlag
Opt_WarnMonomorphism)
                (VarSet
constrained_tvs VarSet -> VarSet -> Bool
`intersectsVarSet` [Type] -> VarSet
tyCoVarsOfTypes [Type]
taus)
                SDoc
mr_msg

       ; String -> SDoc -> TcM ()
traceTc String
"decideMonoTyVars" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
vcat
           [ String -> SDoc
text String
"mono_tvs0 =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
mono_tvs0
           , String -> SDoc
text String
"no_quant =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
no_quant
           , String -> SDoc
text String
"maybe_quant =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
maybe_quant
           , String -> SDoc
text String
"eq_constraints =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
eq_constraints
           , String -> SDoc
text String
"mono_tvs =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
mono_tvs
           , String -> SDoc
text String
"co_vars =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
co_vars ]

       ; (VarSet, [Type], VarSet) -> TcM (VarSet, [Type], VarSet)
forall (m :: * -> *) a. Monad m => a -> m a
return (VarSet
mono_tvs, [Type]
maybe_quant, VarSet
co_vars) }
  where
    pick :: InferMode -> [PredType] -> TcM ([PredType], [PredType])
    -- Split the candidates into ones we definitely
    -- won't quantify, and ones that we might
    pick :: InferMode -> [Type] -> TcM ([Type], [Type])
pick InferMode
NoRestrictions  [Type]
cand = ([Type], [Type]) -> TcM ([Type], [Type])
forall (m :: * -> *) a. Monad m => a -> m a
return ([], [Type]
cand)
    pick InferMode
ApplyMR         [Type]
cand = ([Type], [Type]) -> TcM ([Type], [Type])
forall (m :: * -> *) a. Monad m => a -> m a
return ([Type]
cand, [])
    pick InferMode
EagerDefaulting [Type]
cand = do { Bool
os <- Extension -> TcM Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.OverloadedStrings
                                   ; ([Type], [Type]) -> TcM ([Type], [Type])
forall (m :: * -> *) a. Monad m => a -> m a
return ((Type -> Bool) -> [Type] -> ([Type], [Type])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (Bool -> Type -> Bool
is_int_ct Bool
os) [Type]
cand) }

    -- For EagerDefaulting, do not quantify over
    -- over any interactive class constraint
    is_int_ct :: Bool -> Type -> Bool
is_int_ct Bool
ovl_strings Type
pred
      | Just (Class
cls, [Type]
_) <- Type -> Maybe (Class, [Type])
getClassPredTys_maybe Type
pred
      = Bool -> Class -> Bool
isInteractiveClass Bool
ovl_strings Class
cls
      | Bool
otherwise
      = Bool
False

    pp_bndrs :: SDoc
pp_bndrs = ((Name, Type) -> SDoc) -> [(Name, Type)] -> SDoc
forall a. (a -> SDoc) -> [a] -> SDoc
pprWithCommas (SDoc -> SDoc
quotes (SDoc -> SDoc) -> ((Name, Type) -> SDoc) -> (Name, Type) -> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Name -> SDoc
forall a. Outputable a => a -> SDoc
ppr (Name -> SDoc) -> ((Name, Type) -> Name) -> (Name, Type) -> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name, Type) -> Name
forall a b. (a, b) -> a
fst) [(Name, Type)]
name_taus
    mr_msg :: SDoc
mr_msg =
         SDoc -> Int -> SDoc -> SDoc
hang ([SDoc] -> SDoc
sep [ String -> SDoc
text String
"The Monomorphism Restriction applies to the binding"
                     SDoc -> SDoc -> SDoc
<> [(Name, Type)] -> SDoc
forall a. [a] -> SDoc
plural [(Name, Type)]
name_taus
                   , String -> SDoc
text String
"for" SDoc -> SDoc -> SDoc
<+> SDoc
pp_bndrs ])
            Int
2 ([SDoc] -> SDoc
hsep [ String -> SDoc
text String
"Consider giving"
                    , String -> SDoc
text (if [(Name, Type)] -> Bool
forall a. [a] -> Bool
isSingleton [(Name, Type)]
name_taus then String
"it" else String
"them")
                    , String -> SDoc
text String
"a type signature"])

-------------------
defaultTyVarsAndSimplify :: TcLevel
                         -> TyCoVarSet
                         -> [PredType]          -- Assumed zonked
                         -> TcM [PredType]      -- Guaranteed zonked
-- Default any tyvar free in the constraints,
-- and re-simplify in case the defaulting allows further simplification
defaultTyVarsAndSimplify :: TcLevel -> VarSet -> [Type] -> TcM [Type]
defaultTyVarsAndSimplify TcLevel
rhs_tclvl VarSet
mono_tvs [Type]
candidates
  = do {  -- Promote any tyvars that we cannot generalise
          -- See Note [Promote momomorphic tyvars]
       ; String -> SDoc -> TcM ()
traceTc String
"decideMonoTyVars: promotion:" (VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
mono_tvs)
       ; Bool
any_promoted <- VarSet -> TcM Bool
promoteTyVarSet VarSet
mono_tvs

       -- Default any kind/levity vars
       ; DV {dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
cand_kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
cand_tvs}
                <- [Type] -> TcM CandidatesQTvs
candidateQTyVarsOfTypes [Type]
candidates
                -- any covars should already be handled by
                -- the logic in decideMonoTyVars, which looks at
                -- the constraints generated

       ; Bool
poly_kinds  <- Extension -> TcM Bool
forall gbl lcl. Extension -> TcRnIf gbl lcl Bool
xoptM Extension
LangExt.PolyKinds
       ; [Bool]
default_kvs <- (TcTyVar -> TcM Bool)
-> [TcTyVar] -> IOEnv (Env TcGblEnv TcLclEnv) [Bool]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Bool -> Bool -> TcTyVar -> TcM Bool
default_one Bool
poly_kinds Bool
True)
                             (DTyVarSet -> [TcTyVar]
dVarSetElems DTyVarSet
cand_kvs)
       ; [Bool]
default_tvs <- (TcTyVar -> TcM Bool)
-> [TcTyVar] -> IOEnv (Env TcGblEnv TcLclEnv) [Bool]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Bool -> Bool -> TcTyVar -> TcM Bool
default_one Bool
poly_kinds Bool
False)
                             (DTyVarSet -> [TcTyVar]
dVarSetElems (DTyVarSet
cand_tvs DTyVarSet -> DTyVarSet -> DTyVarSet
`minusDVarSet` DTyVarSet
cand_kvs))
       ; let some_default :: Bool
some_default = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or [Bool]
default_kvs Bool -> Bool -> Bool
|| [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or [Bool]
default_tvs

       ; case () of
           ()
_ | Bool
some_default -> [Type] -> TcM [Type]
simplify_cand [Type]
candidates
             | Bool
any_promoted -> (Type -> TcM Type) -> [Type] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Type -> TcM Type
TcM.zonkTcType [Type]
candidates
             | Bool
otherwise    -> [Type] -> TcM [Type]
forall (m :: * -> *) a. Monad m => a -> m a
return [Type]
candidates
       }
  where
    default_one :: Bool -> Bool -> TcTyVar -> TcM Bool
default_one Bool
poly_kinds Bool
is_kind_var TcTyVar
tv
      | Bool -> Bool
not (TcTyVar -> Bool
isMetaTyVar TcTyVar
tv)
      = Bool -> TcM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
      | TcTyVar
tv TcTyVar -> VarSet -> Bool
`elemVarSet` VarSet
mono_tvs
      = Bool -> TcM Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
      | Bool
otherwise
      = Bool -> TcTyVar -> TcM Bool
defaultTyVar (Bool -> Bool
not Bool
poly_kinds Bool -> Bool -> Bool
&& Bool
is_kind_var) TcTyVar
tv

    simplify_cand :: [Type] -> TcM [Type]
simplify_cand [Type]
candidates
      = do { [CtEvidence]
clone_wanteds <- CtOrigin -> [Type] -> TcM [CtEvidence]
newWanteds CtOrigin
DefaultOrigin [Type]
candidates
           ; WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples } <- TcLevel
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a. TcLevel -> TcM a -> TcM a
setTcLevel TcLevel
rhs_tclvl (TcRnIf TcGblEnv TcLclEnv WantedConstraints
 -> TcRnIf TcGblEnv TcLclEnv WantedConstraints)
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
-> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall a b. (a -> b) -> a -> b
$
                                           [CtEvidence] -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
simplifyWantedsTcM [CtEvidence]
clone_wanteds
              -- Discard evidence; simples is fully zonked

           ; let new_candidates :: [Type]
new_candidates = Cts -> [Type]
ctsPreds Cts
simples
           ; String -> SDoc -> TcM ()
traceTc String
"Simplified after defaulting" (SDoc -> TcM ()) -> SDoc -> TcM ()
forall a b. (a -> b) -> a -> b
$
                      [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Before:" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
candidates
                           , String -> SDoc
text String
"After:"  SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
new_candidates ]
           ; [Type] -> TcM [Type]
forall (m :: * -> *) a. Monad m => a -> m a
return [Type]
new_candidates }

------------------
decideQuantifiedTyVars
   :: [(Name,TcType)]   -- Annotated theta and (name,tau) pairs
   -> [TcIdSigInst]     -- Partial signatures
   -> [PredType]        -- Candidates, zonked
   -> TcM [TyVar]
-- Fix what tyvars we are going to quantify over, and quantify them
decideQuantifiedTyVars :: [(Name, Type)] -> [TcIdSigInst] -> [Type] -> TcM [TcTyVar]
decideQuantifiedTyVars [(Name, Type)]
name_taus [TcIdSigInst]
psigs [Type]
candidates
  = do {     -- Why psig_tys? We try to quantify over everything free in here
             -- See Note [Quantification and partial signatures]
             --     Wrinkles 2 and 3
       ; [Type]
psig_tv_tys <- (TcTyVar -> TcM Type) -> [TcTyVar] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcTyVar -> TcM Type
TcM.zonkTcTyVar [ TcTyVar
tv | TcIdSigInst
sig <- [TcIdSigInst]
psigs
                                                  , (Name
_,Bndr TcTyVar
tv Specificity
_) <- TcIdSigInst -> [(Name, InvisTVBinder)]
sig_inst_skols TcIdSigInst
sig ]
       ; [Type]
psig_theta <- (Type -> TcM Type) -> [Type] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Type -> TcM Type
TcM.zonkTcType [ Type
pred | TcIdSigInst
sig <- [TcIdSigInst]
psigs
                                                  , Type
pred <- TcIdSigInst -> [Type]
sig_inst_theta TcIdSigInst
sig ]
       ; [Type]
tau_tys  <- ((Name, Type) -> TcM Type) -> [(Name, Type)] -> TcM [Type]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Type -> TcM Type
TcM.zonkTcType (Type -> TcM Type)
-> ((Name, Type) -> Type) -> (Name, Type) -> TcM Type
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name, Type) -> Type
forall a b. (a, b) -> b
snd) [(Name, Type)]
name_taus

       ; let -- Try to quantify over variables free in these types
             psig_tys :: [Type]
psig_tys = [Type]
psig_tv_tys [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
psig_theta
             seed_tys :: [Type]
seed_tys = [Type]
psig_tys [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
tau_tys

             -- Now "grow" those seeds to find ones reachable via 'candidates'
             grown_tcvs :: VarSet
grown_tcvs = [Type] -> VarSet -> VarSet
growThetaTyVars [Type]
candidates ([Type] -> VarSet
tyCoVarsOfTypes [Type]
seed_tys)

       -- Now we have to classify them into kind variables and type variables
       -- (sigh) just for the benefit of -XNoPolyKinds; see quantifyTyVars
       --
       -- Keep the psig_tys first, so that candidateQTyVarsOfTypes produces
       -- them in that order, so that the final qtvs quantifies in the same
       -- order as the partial signatures do (#13524)
       ; dv :: CandidatesQTvs
dv@DV {dv_kvs :: CandidatesQTvs -> DTyVarSet
dv_kvs = DTyVarSet
cand_kvs, dv_tvs :: CandidatesQTvs -> DTyVarSet
dv_tvs = DTyVarSet
cand_tvs} <- [Type] -> TcM CandidatesQTvs
candidateQTyVarsOfTypes ([Type] -> TcM CandidatesQTvs) -> [Type] -> TcM CandidatesQTvs
forall a b. (a -> b) -> a -> b
$
                                                         [Type]
psig_tys [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
candidates [Type] -> [Type] -> [Type]
forall a. [a] -> [a] -> [a]
++ [Type]
tau_tys
       ; let pick :: DTyVarSet -> DTyVarSet
pick     = (DTyVarSet -> VarSet -> DTyVarSet
`dVarSetIntersectVarSet` VarSet
grown_tcvs)
             dvs_plus :: CandidatesQTvs
dvs_plus = CandidatesQTvs
dv { dv_kvs :: DTyVarSet
dv_kvs = DTyVarSet -> DTyVarSet
pick DTyVarSet
cand_kvs, dv_tvs :: DTyVarSet
dv_tvs = DTyVarSet -> DTyVarSet
pick DTyVarSet
cand_tvs }

       ; String -> SDoc -> TcM ()
traceTc String
"decideQuantifiedTyVars" ([SDoc] -> SDoc
vcat
           [ String -> SDoc
text String
"candidates =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
candidates
           , String -> SDoc
text String
"tau_tys =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
tau_tys
           , String -> SDoc
text String
"seed_tys =" SDoc -> SDoc -> SDoc
<+> [Type] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Type]
seed_tys
           , String -> SDoc
text String
"seed_tcvs =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr ([Type] -> VarSet
tyCoVarsOfTypes [Type]
seed_tys)
           , String -> SDoc
text String
"grown_tcvs =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
grown_tcvs
           , String -> SDoc
text String
"dvs =" SDoc -> SDoc -> SDoc
<+> CandidatesQTvs -> SDoc
forall a. Outputable a => a -> SDoc
ppr CandidatesQTvs
dvs_plus])

       ; CandidatesQTvs -> TcM [TcTyVar]
quantifyTyVars CandidatesQTvs
dvs_plus }

------------------
growThetaTyVars :: ThetaType -> TyCoVarSet -> TyCoVarSet
-- See Note [Growing the tau-tvs using constraints]
growThetaTyVars :: [Type] -> VarSet -> VarSet
growThetaTyVars [Type]
theta VarSet
tcvs
  | [Type] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
theta = VarSet
tcvs
  | Bool
otherwise  = (VarSet -> VarSet) -> VarSet -> VarSet
transCloVarSet VarSet -> VarSet
mk_next VarSet
seed_tcvs
  where
    seed_tcvs :: VarSet
seed_tcvs = VarSet
tcvs VarSet -> VarSet -> VarSet
`unionVarSet` [Type] -> VarSet
tyCoVarsOfTypes [Type]
ips
    ([Type]
ips, [Type]
non_ips) = (Type -> Bool) -> [Type] -> ([Type], [Type])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition Type -> Bool
isIPLikePred [Type]
theta
                         -- See Note [Inheriting implicit parameters] in GHC.Tc.Utils.TcType

    mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones
    mk_next :: VarSet -> VarSet
mk_next VarSet
so_far = (Type -> VarSet -> VarSet) -> VarSet -> [Type] -> VarSet
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (VarSet -> Type -> VarSet -> VarSet
grow_one VarSet
so_far) VarSet
emptyVarSet [Type]
non_ips
    grow_one :: VarSet -> Type -> VarSet -> VarSet
grow_one VarSet
so_far Type
pred VarSet
tcvs
       | VarSet
pred_tcvs VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
so_far = VarSet
tcvs VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
pred_tcvs
       | Bool
otherwise                           = VarSet
tcvs
       where
         pred_tcvs :: VarSet
pred_tcvs = Type -> VarSet
tyCoVarsOfType Type
pred


{- Note [Promote momomorphic tyvars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Promote any type variables that are free in the environment.  Eg
   f :: forall qtvs. bound_theta => zonked_tau
The free vars of f's type become free in the envt, and hence will show
up whenever 'f' is called.  They may currently at rhs_tclvl, but they
had better be unifiable at the outer_tclvl!  Example: envt mentions
alpha[1]
           tau_ty = beta[2] -> beta[2]
           constraints = alpha ~ [beta]
we don't quantify over beta (since it is fixed by envt)
so we must promote it!  The inferred type is just
  f :: beta -> beta

NB: promoteTyVar ignores coercion variables

Note [Quantification and partial signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When choosing type variables to quantify, the basic plan is to
quantify over all type variables that are
 * free in the tau_tvs, and
 * not forced to be monomorphic (mono_tvs),
   for example by being free in the environment.

However, in the case of a partial type signature, be doing inference
*in the presence of a type signature*. For example:
   f :: _ -> a
   f x = ...
or
   g :: (Eq _a) => _b -> _b
In both cases we use plan InferGen, and hence call simplifyInfer.  But
those 'a' variables are skolems (actually TyVarTvs), and we should be
sure to quantify over them.  This leads to several wrinkles:

* Wrinkle 1.  In the case of a type error
     f :: _ -> Maybe a
     f x = True && x
  The inferred type of 'f' is f :: Bool -> Bool, but there's a
  left-over error of form (HoleCan (Maybe a ~ Bool)).  The error-reporting
  machine expects to find a binding site for the skolem 'a', so we
  add it to the quantified tyvars.

* Wrinkle 2.  Consider the partial type signature
     f :: (Eq _) => Int -> Int
     f x = x
  In normal cases that makes sense; e.g.
     g :: Eq _a => _a -> _a
     g x = x
  where the signature makes the type less general than it could
  be. But for 'f' we must therefore quantify over the user-annotated
  constraints, to get
     f :: forall a. Eq a => Int -> Int
  (thereby correctly triggering an ambiguity error later).  If we don't
  we'll end up with a strange open type
     f :: Eq alpha => Int -> Int
  which isn't ambiguous but is still very wrong.

  Bottom line: Try to quantify over any variable free in psig_theta,
  just like the tau-part of the type.

* Wrinkle 3 (#13482). Also consider
    f :: forall a. _ => Int -> Int
    f x = if (undefined :: a) == undefined then x else 0
  Here we get an (Eq a) constraint, but it's not mentioned in the
  psig_theta nor the type of 'f'.  But we still want to quantify
  over 'a' even if the monomorphism restriction is on.

* Wrinkle 4 (#14479)
    foo :: Num a => a -> a
    foo xxx = g xxx
      where
        g :: forall b. Num b => _ -> b
        g y = xxx + y

  In the signature for 'g', we cannot quantify over 'b' because it turns out to
  get unified with 'a', which is free in g's environment.  So we carefully
  refrain from bogusly quantifying, in GHC.Tc.Solver.decideMonoTyVars.  We
  report the error later, in GHC.Tc.Gen.Bind.chooseInferredQuantifiers.

Note [Growing the tau-tvs using constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(growThetaTyVars insts tvs) is the result of extending the set
    of tyvars, tvs, using all conceivable links from pred

E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e}
Then growThetaTyVars preds tvs = {a,b,c}

Notice that
   growThetaTyVars is conservative       if v might be fixed by vs
                                         => v `elem` grow(vs,C)

Note [Quantification with errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we find that the RHS of the definition has some absolutely-insoluble
constraints (including especially "variable not in scope"), we

* Abandon all attempts to find a context to quantify over,
  and instead make the function fully-polymorphic in whatever
  type we have found

* Return a flag from simplifyInfer, indicating that we found an
  insoluble constraint.  This flag is used to suppress the ambiguity
  check for the inferred type, which may well be bogus, and which
  tends to obscure the real error.  This fix feels a bit clunky,
  but I failed to come up with anything better.

Reasons:
    - Avoid downstream errors
    - Do not perform an ambiguity test on a bogus type, which might well
      fail spuriously, thereby obfuscating the original insoluble error.
      #14000 is an example

I tried an alternative approach: simply failM, after emitting the
residual implication constraint; the exception will be caught in
GHC.Tc.Gen.Bind.tcPolyBinds, which gives all the binders in the group the type
(forall a. a).  But that didn't work with -fdefer-type-errors, because
the recovery from failM emits no code at all, so there is no function
to run!   But -fdefer-type-errors aspires to produce a runnable program.

NB that we must include *derived* errors in the check for insolubles.
Example:
    (a::*) ~ Int#
We get an insoluble derived error *~#, and we don't want to discard
it before doing the isInsolubleWC test!  (#8262)

Note [Default while Inferring]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Our current plan is that defaulting only happens at simplifyTop and
not simplifyInfer.  This may lead to some insoluble deferred constraints.
Example:

instance D g => C g Int b

constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha
type inferred       = gamma -> gamma

Now, if we try to default (alpha := Int) we will be able to refine the implication to
  (forall b. 0 => C gamma Int b)
which can then be simplified further to
  (forall b. 0 => D gamma)
Finally, we /can/ approximate this implication with (D gamma) and infer the quantified
type:  forall g. D g => g -> g

Instead what will currently happen is that we will get a quantified type
(forall g. g -> g) and an implication:
       forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha

Which, even if the simplifyTop defaults (alpha := Int) we will still be left with an
unsolvable implication:
       forall g. 0 => (forall b. 0 => D g)

The concrete example would be:
       h :: C g a s => g -> a -> ST s a
       f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1)

But it is quite tedious to do defaulting and resolve the implication constraints, and
we have not observed code breaking because of the lack of defaulting in inference, so
we don't do it for now.



Note [Minimize by Superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we quantify over a constraint, in simplifyInfer we need to
quantify over a constraint that is minimal in some sense: For
instance, if the final wanted constraint is (Eq alpha, Ord alpha),
we'd like to quantify over Ord alpha, because we can just get Eq alpha
from superclass selection from Ord alpha. This minimization is what
mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
to check the original wanted.


Note [Avoid unnecessary constraint simplification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -------- NB NB NB (Jun 12) -------------
    This note not longer applies; see the notes with #4361.
    But I'm leaving it in here so we remember the issue.)
    ----------------------------------------
When inferring the type of a let-binding, with simplifyInfer,
try to avoid unnecessarily simplifying class constraints.
Doing so aids sharing, but it also helps with delicate
situations like

   instance C t => C [t] where ..

   f :: C [t] => ....
   f x = let g y = ...(constraint C [t])...
         in ...
When inferring a type for 'g', we don't want to apply the
instance decl, because then we can't satisfy (C t).  So we
just notice that g isn't quantified over 't' and partition
the constraints before simplifying.

This only half-works, but then let-generalisation only half-works.

*********************************************************************************
*                                                                                 *
*                                 Main Simplifier                                 *
*                                                                                 *
***********************************************************************************

-}

simplifyWantedsTcM :: [CtEvidence] -> TcM WantedConstraints
-- Solve the specified Wanted constraints
-- Discard the evidence binds
-- Discards all Derived stuff in result
-- Postcondition: fully zonked and unflattened constraints
simplifyWantedsTcM :: [CtEvidence] -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
simplifyWantedsTcM [CtEvidence]
wanted
  = do { String -> SDoc -> TcM ()
traceTc String
"simplifyWantedsTcM {" ([CtEvidence] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [CtEvidence]
wanted)
       ; (WantedConstraints
result, EvBindMap
_) <- TcS WantedConstraints -> TcM (WantedConstraints, EvBindMap)
forall a. TcS a -> TcM (a, EvBindMap)
runTcS (WantedConstraints -> TcS WantedConstraints
solveWantedsAndDrop ([CtEvidence] -> WantedConstraints
mkSimpleWC [CtEvidence]
wanted))
       ; WantedConstraints
result <- WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
TcM.zonkWC WantedConstraints
result
       ; String -> SDoc -> TcM ()
traceTc String
"simplifyWantedsTcM }" (WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
result)
       ; WantedConstraints -> TcRnIf TcGblEnv TcLclEnv WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
result }

solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints
-- Since solveWanteds returns the residual WantedConstraints,
-- it should always be called within a runTcS or something similar,
-- Result is not zonked
solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints
solveWantedsAndDrop WantedConstraints
wanted
  = do { WantedConstraints
wc <- WantedConstraints -> TcS WantedConstraints
solveWanteds WantedConstraints
wanted
       ; WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return (WantedConstraints -> WantedConstraints
dropDerivedWC WantedConstraints
wc) }

solveWanteds :: WantedConstraints -> TcS WantedConstraints
-- so that the inert set doesn't mindlessly propagate.
-- NB: wc_simples may be wanted /or/ derived now
solveWanteds :: WantedConstraints -> TcS WantedConstraints
solveWanteds wc :: WantedConstraints
wc@(WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples, wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implics, wc_holes :: WantedConstraints -> Bag Hole
wc_holes = Bag Hole
holes })
  = do { TcLevel
cur_lvl <- TcS TcLevel
TcS.getTcLevel
       ; String -> SDoc -> TcS ()
traceTcS String
"solveWanteds {" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
         [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Level =" SDoc -> SDoc -> SDoc
<+> TcLevel -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcLevel
cur_lvl
              , WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wc ]

       ; WantedConstraints
wc1 <- Cts -> TcS WantedConstraints
solveSimpleWanteds Cts
simples
                -- Any insoluble constraints are in 'simples' and so get rewritten
                -- See Note [Rewrite insolubles] in GHC.Tc.Solver.Monad

       ; (Cts
floated_eqs, Bag Implication
implics2) <- Bag Implication -> TcS (Cts, Bag Implication)
solveNestedImplications (Bag Implication -> TcS (Cts, Bag Implication))
-> Bag Implication -> TcS (Cts, Bag Implication)
forall a b. (a -> b) -> a -> b
$
                                    Bag Implication
implics Bag Implication -> Bag Implication -> Bag Implication
forall a. Bag a -> Bag a -> Bag a
`unionBags` WantedConstraints -> Bag Implication
wc_impl WantedConstraints
wc1

       ; DynFlags
dflags   <- TcS DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       ; WantedConstraints
solved_wc <- Int
-> IntWithInf -> Cts -> WantedConstraints -> TcS WantedConstraints
simpl_loop Int
0 (DynFlags -> IntWithInf
solverIterations DynFlags
dflags) Cts
floated_eqs
                                (WantedConstraints
wc1 { wc_impl :: Bag Implication
wc_impl = Bag Implication
implics2 })

       ; Bag Hole
holes' <- Bag Hole -> TcS (Bag Hole)
simplifyHoles Bag Hole
holes
       ; let final_wc :: WantedConstraints
final_wc = WantedConstraints
solved_wc { wc_holes :: Bag Hole
wc_holes = Bag Hole
holes' }

       ; EvBindsVar
ev_binds_var <- TcS EvBindsVar
getTcEvBindsVar
       ; EvBindMap
bb <- EvBindsVar -> TcS EvBindMap
TcS.getTcEvBindsMap EvBindsVar
ev_binds_var
       ; String -> SDoc -> TcS ()
traceTcS String
"solveWanteds }" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
                 [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"final wc =" SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
final_wc
                      , String -> SDoc
text String
"current evbinds  =" SDoc -> SDoc -> SDoc
<+> Bag EvBind -> SDoc
forall a. Outputable a => a -> SDoc
ppr (EvBindMap -> Bag EvBind
evBindMapBinds EvBindMap
bb) ]

       ; WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
final_wc }

simpl_loop :: Int -> IntWithInf -> Cts
           -> WantedConstraints -> TcS WantedConstraints
simpl_loop :: Int
-> IntWithInf -> Cts -> WantedConstraints -> TcS WantedConstraints
simpl_loop Int
n IntWithInf
limit Cts
floated_eqs wc :: WantedConstraints
wc@(WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples })
  | Int
n Int -> IntWithInf -> Bool
`intGtLimit` IntWithInf
limit
  = do { -- Add an error (not a warning) if we blow the limit,
         -- Typically if we blow the limit we are going to report some other error
         -- (an unsolved constraint), and we don't want that error to suppress
         -- the iteration limit warning!
         SDoc -> TcS ()
addErrTcS (SDoc -> Int -> SDoc -> SDoc
hang (String -> SDoc
text String
"solveWanteds: too many iterations"
                   SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
parens (String -> SDoc
text String
"limit =" SDoc -> SDoc -> SDoc
<+> IntWithInf -> SDoc
forall a. Outputable a => a -> SDoc
ppr IntWithInf
limit))
                Int
2 ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Unsolved:" SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wc
                        , Bool -> SDoc -> SDoc
ppUnless (Cts -> Bool
forall a. Bag a -> Bool
isEmptyBag Cts
floated_eqs) (SDoc -> SDoc) -> SDoc -> SDoc
forall a b. (a -> b) -> a -> b
$
                          String -> SDoc
text String
"Floated equalities:" SDoc -> SDoc -> SDoc
<+> Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
floated_eqs
                        , String -> SDoc
text String
"Set limit with -fconstraint-solver-iterations=n; n=0 for no limit"
                  ]))
       ; WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
wc }

  | Bool -> Bool
not (Cts -> Bool
forall a. Bag a -> Bool
isEmptyBag Cts
floated_eqs)
  = Int
-> IntWithInf -> Bool -> WantedConstraints -> TcS WantedConstraints
simplify_again Int
n IntWithInf
limit Bool
True (WantedConstraints
wc { wc_simple :: Cts
wc_simple = Cts
floated_eqs Cts -> Cts -> Cts
forall a. Bag a -> Bag a -> Bag a
`unionBags` Cts
simples })
            -- Put floated_eqs first so they get solved first
            -- NB: the floated_eqs may include /derived/ equalities
            -- arising from fundeps inside an implication

  | WantedConstraints -> Bool
superClassesMightHelp WantedConstraints
wc
  = -- We still have unsolved goals, and apparently no way to solve them,
    -- so try expanding superclasses at this level, both Given and Wanted
    do { [Ct]
pending_given <- TcS [Ct]
getPendingGivenScs
       ; let ([Ct]
pending_wanted, Cts
simples1) = Cts -> ([Ct], Cts)
getPendingWantedScs Cts
simples
       ; if [Ct] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Ct]
pending_given Bool -> Bool -> Bool
&& [Ct] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Ct]
pending_wanted
           then WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
wc  -- After all, superclasses did not help
           else
    do { [Ct]
new_given  <- [Ct] -> TcS [Ct]
makeSuperClasses [Ct]
pending_given
       ; [Ct]
new_wanted <- [Ct] -> TcS [Ct]
makeSuperClasses [Ct]
pending_wanted
       ; [Ct] -> TcS ()
solveSimpleGivens [Ct]
new_given -- Add the new Givens to the inert set
       ; Int
-> IntWithInf -> Bool -> WantedConstraints -> TcS WantedConstraints
simplify_again Int
n IntWithInf
limit ([Ct] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Ct]
pending_given)
         WantedConstraints
wc { wc_simple :: Cts
wc_simple = Cts
simples1 Cts -> Cts -> Cts
forall a. Bag a -> Bag a -> Bag a
`unionBags` [Ct] -> Cts
forall a. [a] -> Bag a
listToBag [Ct]
new_wanted } } }

  | Bool
otherwise
  = WantedConstraints -> TcS WantedConstraints
forall (m :: * -> *) a. Monad m => a -> m a
return WantedConstraints
wc

simplify_again :: Int -> IntWithInf -> Bool
               -> WantedConstraints -> TcS WantedConstraints
-- We have definitely decided to have another go at solving
-- the wanted constraints (we have tried at least once already
simplify_again :: Int
-> IntWithInf -> Bool -> WantedConstraints -> TcS WantedConstraints
simplify_again Int
n IntWithInf
limit Bool
no_new_given_scs
               wc :: WantedConstraints
wc@(WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples, wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implics })
  = do { SDoc -> TcS ()
csTraceTcS (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
         String -> SDoc
text String
"simpl_loop iteration=" SDoc -> SDoc -> SDoc
<> Int -> SDoc
int Int
n
         SDoc -> SDoc -> SDoc
<+> (SDoc -> SDoc
parens (SDoc -> SDoc) -> SDoc -> SDoc
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
hsep [ String -> SDoc
text String
"no new given superclasses =" SDoc -> SDoc -> SDoc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
no_new_given_scs SDoc -> SDoc -> SDoc
<> SDoc
comma
                            , Int -> SDoc
int (Cts -> Int
forall a. Bag a -> Int
lengthBag Cts
simples) SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
"simples to solve" ])
       ; String -> SDoc -> TcS ()
traceTcS String
"simpl_loop: wc =" (WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wc)

       ; (Int
unifs1, WantedConstraints
wc1) <- TcS WantedConstraints -> TcS (Int, WantedConstraints)
forall a. TcS a -> TcS (Int, a)
reportUnifications (TcS WantedConstraints -> TcS (Int, WantedConstraints))
-> TcS WantedConstraints -> TcS (Int, WantedConstraints)
forall a b. (a -> b) -> a -> b
$
                          Cts -> TcS WantedConstraints
solveSimpleWanteds (Cts -> TcS WantedConstraints) -> Cts -> TcS WantedConstraints
forall a b. (a -> b) -> a -> b
$
                          Cts
simples

       -- See Note [Cutting off simpl_loop]
       -- We have already tried to solve the nested implications once
       -- Try again only if we have unified some meta-variables
       -- (which is a bit like adding more givens), or we have some
       -- new Given superclasses
       ; let new_implics :: Bag Implication
new_implics = WantedConstraints -> Bag Implication
wc_impl WantedConstraints
wc1
       ; if Int
unifs1 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0       Bool -> Bool -> Bool
&&
            Bool
no_new_given_scs  Bool -> Bool -> Bool
&&
            Bag Implication -> Bool
forall a. Bag a -> Bool
isEmptyBag Bag Implication
new_implics

           then -- Do not even try to solve the implications
                Int
-> IntWithInf -> Cts -> WantedConstraints -> TcS WantedConstraints
simpl_loop (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1) IntWithInf
limit Cts
forall a. Bag a
emptyBag (WantedConstraints
wc1 { wc_impl :: Bag Implication
wc_impl = Bag Implication
implics })

           else -- Try to solve the implications
                do { (Cts
floated_eqs2, Bag Implication
implics2) <- Bag Implication -> TcS (Cts, Bag Implication)
solveNestedImplications (Bag Implication -> TcS (Cts, Bag Implication))
-> Bag Implication -> TcS (Cts, Bag Implication)
forall a b. (a -> b) -> a -> b
$
                                                 Bag Implication
implics Bag Implication -> Bag Implication -> Bag Implication
forall a. Bag a -> Bag a -> Bag a
`unionBags` Bag Implication
new_implics
                   ; Int
-> IntWithInf -> Cts -> WantedConstraints -> TcS WantedConstraints
simpl_loop (Int
nInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1) IntWithInf
limit Cts
floated_eqs2 (WantedConstraints
wc1 { wc_impl :: Bag Implication
wc_impl = Bag Implication
implics2 })
    } }

solveNestedImplications :: Bag Implication
                        -> TcS (Cts, Bag Implication)
-- Precondition: the TcS inerts may contain unsolved simples which have
-- to be converted to givens before we go inside a nested implication.
solveNestedImplications :: Bag Implication -> TcS (Cts, Bag Implication)
solveNestedImplications Bag Implication
implics
  | Bag Implication -> Bool
forall a. Bag a -> Bool
isEmptyBag Bag Implication
implics
  = (Cts, Bag Implication) -> TcS (Cts, Bag Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Cts
forall a. Bag a
emptyBag, Bag Implication
forall a. Bag a
emptyBag)
  | Bool
otherwise
  = do { String -> SDoc -> TcS ()
traceTcS String
"solveNestedImplications starting {" SDoc
empty
       ; (Bag Cts
floated_eqs_s, Bag (Maybe Implication)
unsolved_implics) <- (Implication -> TcS (Cts, Maybe Implication))
-> Bag Implication -> TcS (Bag Cts, Bag (Maybe Implication))
forall (m :: * -> *) a b c.
Monad m =>
(a -> m (b, c)) -> Bag a -> m (Bag b, Bag c)
mapAndUnzipBagM Implication -> TcS (Cts, Maybe Implication)
solveImplication Bag Implication
implics
       ; let floated_eqs :: Cts
floated_eqs = Bag Cts -> Cts
forall a. Bag (Bag a) -> Bag a
concatBag Bag Cts
floated_eqs_s

       -- ... and we are back in the original TcS inerts
       -- Notice that the original includes the _insoluble_simples so it was safe to ignore
       -- them in the beginning of this function.
       ; String -> SDoc -> TcS ()
traceTcS String
"solveNestedImplications end }" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
                  [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"all floated_eqs ="  SDoc -> SDoc -> SDoc
<+> Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
floated_eqs
                       , String -> SDoc
text String
"unsolved_implics =" SDoc -> SDoc -> SDoc
<+> Bag (Maybe Implication) -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bag (Maybe Implication)
unsolved_implics ]

       ; (Cts, Bag Implication) -> TcS (Cts, Bag Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Cts
floated_eqs, Bag (Maybe Implication) -> Bag Implication
forall a. Bag (Maybe a) -> Bag a
catBagMaybes Bag (Maybe Implication)
unsolved_implics) }

solveImplication :: Implication    -- Wanted
                 -> TcS (Cts,      -- All wanted or derived floated equalities: var = type
                         Maybe Implication) -- Simplified implication (empty or singleton)
-- Precondition: The TcS monad contains an empty worklist and given-only inerts
-- which after trying to solve this implication we must restore to their original value
solveImplication :: Implication -> TcS (Cts, Maybe Implication)
solveImplication imp :: Implication
imp@(Implic { ic_tclvl :: Implication -> TcLevel
ic_tclvl  = TcLevel
tclvl
                             , ic_binds :: Implication -> EvBindsVar
ic_binds  = EvBindsVar
ev_binds_var
                             , ic_skols :: Implication -> [TcTyVar]
ic_skols  = [TcTyVar]
skols
                             , ic_given :: Implication -> [TcTyVar]
ic_given  = [TcTyVar]
given_ids
                             , ic_wanted :: Implication -> WantedConstraints
ic_wanted = WantedConstraints
wanteds
                             , ic_info :: Implication -> SkolemInfo
ic_info   = SkolemInfo
info
                             , ic_status :: Implication -> ImplicStatus
ic_status = ImplicStatus
status })
  | ImplicStatus -> Bool
isSolvedStatus ImplicStatus
status
  = (Cts, Maybe Implication) -> TcS (Cts, Maybe Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Cts
emptyCts, Implication -> Maybe Implication
forall a. a -> Maybe a
Just Implication
imp)  -- Do nothing

  | Bool
otherwise  -- Even for IC_Insoluble it is worth doing more work
               -- The insoluble stuff might be in one sub-implication
               -- and other unsolved goals in another; and we want to
               -- solve the latter as much as possible
  = do { InertSet
inerts <- TcS InertSet
getTcSInerts
       ; String -> SDoc -> TcS ()
traceTcS String
"solveImplication {" (Implication -> SDoc
forall a. Outputable a => a -> SDoc
ppr Implication
imp SDoc -> SDoc -> SDoc
$$ String -> SDoc
text String
"Inerts" SDoc -> SDoc -> SDoc
<+> InertSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr InertSet
inerts)

       -- commented out; see `where` clause below
       -- ; when debugIsOn check_tc_level

         -- Solve the nested constraints
       ; (Bool
no_given_eqs, Cts
given_insols, WantedConstraints
residual_wanted)
            <- EvBindsVar
-> TcLevel
-> TcS (Bool, Cts, WantedConstraints)
-> TcS (Bool, Cts, WantedConstraints)
forall a. EvBindsVar -> TcLevel -> TcS a -> TcS a
nestImplicTcS EvBindsVar
ev_binds_var TcLevel
tclvl (TcS (Bool, Cts, WantedConstraints)
 -> TcS (Bool, Cts, WantedConstraints))
-> TcS (Bool, Cts, WantedConstraints)
-> TcS (Bool, Cts, WantedConstraints)
forall a b. (a -> b) -> a -> b
$
               do { let loc :: CtLoc
loc    = TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
mkGivenLoc TcLevel
tclvl SkolemInfo
info (Implication -> TcLclEnv
ic_env Implication
imp)
                        givens :: [Ct]
givens = CtLoc -> [TcTyVar] -> [Ct]
mkGivens CtLoc
loc [TcTyVar]
given_ids
                  ; [Ct] -> TcS ()
solveSimpleGivens [Ct]
givens

                  ; WantedConstraints
residual_wanted <- WantedConstraints -> TcS WantedConstraints
solveWanteds WantedConstraints
wanteds
                        -- solveWanteds, *not* solveWantedsAndDrop, because
                        -- we want to retain derived equalities so we can float
                        -- them out in floatEqualities

                  ; (Bool
no_eqs, Cts
given_insols) <- TcLevel -> [TcTyVar] -> TcS (Bool, Cts)
getNoGivenEqs TcLevel
tclvl [TcTyVar]
skols
                        -- Call getNoGivenEqs /after/ solveWanteds, because
                        -- solveWanteds can augment the givens, via expandSuperClasses,
                        -- to reveal given superclass equalities

                  ; (Bool, Cts, WantedConstraints)
-> TcS (Bool, Cts, WantedConstraints)
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
no_eqs, Cts
given_insols, WantedConstraints
residual_wanted) }

       ; (Cts
floated_eqs, WantedConstraints
residual_wanted)
             <- [TcTyVar]
-> [TcTyVar]
-> EvBindsVar
-> Bool
-> WantedConstraints
-> TcS (Cts, WantedConstraints)
floatEqualities [TcTyVar]
skols [TcTyVar]
given_ids EvBindsVar
ev_binds_var
                                Bool
no_given_eqs WantedConstraints
residual_wanted

       ; String -> SDoc -> TcS ()
traceTcS String
"solveImplication 2"
           (Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
given_insols SDoc -> SDoc -> SDoc
$$ WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
residual_wanted)
       ; let final_wanted :: WantedConstraints
final_wanted = WantedConstraints
residual_wanted WantedConstraints -> Cts -> WantedConstraints
`addInsols` Cts
given_insols
             -- Don't lose track of the insoluble givens,
             -- which signal unreachable code; put them in ic_wanted

       ; Maybe Implication
res_implic <- Implication -> TcS (Maybe Implication)
setImplicationStatus (Implication
imp { ic_no_eqs :: Bool
ic_no_eqs = Bool
no_given_eqs
                                                 , ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
final_wanted })

       ; EvBindMap
evbinds <- EvBindsVar -> TcS EvBindMap
TcS.getTcEvBindsMap EvBindsVar
ev_binds_var
       ; VarSet
tcvs    <- EvBindsVar -> TcS VarSet
TcS.getTcEvTyCoVars EvBindsVar
ev_binds_var
       ; String -> SDoc -> TcS ()
traceTcS String
"solveImplication end }" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$ [SDoc] -> SDoc
vcat
             [ String -> SDoc
text String
"no_given_eqs =" SDoc -> SDoc -> SDoc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
no_given_eqs
             , String -> SDoc
text String
"floated_eqs =" SDoc -> SDoc -> SDoc
<+> Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
floated_eqs
             , String -> SDoc
text String
"res_implic =" SDoc -> SDoc -> SDoc
<+> Maybe Implication -> SDoc
forall a. Outputable a => a -> SDoc
ppr Maybe Implication
res_implic
             , String -> SDoc
text String
"implication evbinds =" SDoc -> SDoc -> SDoc
<+> Bag EvBind -> SDoc
forall a. Outputable a => a -> SDoc
ppr (EvBindMap -> Bag EvBind
evBindMapBinds EvBindMap
evbinds)
             , String -> SDoc
text String
"implication tvcs =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
tcvs ]

       ; (Cts, Maybe Implication) -> TcS (Cts, Maybe Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Cts
floated_eqs, Maybe Implication
res_implic) }

  where
    -- TcLevels must be strictly increasing (see (ImplicInv) in
    -- Note [TcLevel and untouchable type variables] in GHC.Tc.Utils.TcType),
    -- and in fact I think they should always increase one level at a time.

    -- Though sensible, this check causes lots of testsuite failures. It is
    -- remaining commented out for now.
    {-
    check_tc_level = do { cur_lvl <- TcS.getTcLevel
                        ; MASSERT2( tclvl == pushTcLevel cur_lvl , text "Cur lvl =" <+> ppr cur_lvl $$ text "Imp lvl =" <+> ppr tclvl ) }
    -}

----------------------
setImplicationStatus :: Implication -> TcS (Maybe Implication)
-- Finalise the implication returned from solveImplication:
--    * Set the ic_status field
--    * Trim the ic_wanted field to remove Derived constraints
-- Precondition: the ic_status field is not already IC_Solved
-- Return Nothing if we can discard the implication altogether
setImplicationStatus :: Implication -> TcS (Maybe Implication)
setImplicationStatus implic :: Implication
implic@(Implic { ic_status :: Implication -> ImplicStatus
ic_status     = ImplicStatus
status
                                    , ic_info :: Implication -> SkolemInfo
ic_info       = SkolemInfo
info
                                    , ic_wanted :: Implication -> WantedConstraints
ic_wanted     = WantedConstraints
wc
                                    , ic_given :: Implication -> [TcTyVar]
ic_given      = [TcTyVar]
givens })
 | ASSERT2( not (isSolvedStatus status ), ppr info )
   -- Precondition: we only set the status if it is not already solved
   Bool -> Bool
not (WantedConstraints -> Bool
isSolvedWC WantedConstraints
pruned_wc)
 = do { String -> SDoc -> TcS ()
traceTcS String
"setImplicationStatus(not-all-solved) {" (Implication -> SDoc
forall a. Outputable a => a -> SDoc
ppr Implication
implic)

      ; Implication
implic <- Implication -> TcS Implication
neededEvVars Implication
implic

      ; let new_status :: ImplicStatus
new_status | WantedConstraints -> Bool
insolubleWC WantedConstraints
pruned_wc = ImplicStatus
IC_Insoluble
                       | Bool
otherwise             = ImplicStatus
IC_Unsolved
            new_implic :: Implication
new_implic = Implication
implic { ic_status :: ImplicStatus
ic_status = ImplicStatus
new_status
                                , ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
pruned_wc }

      ; String -> SDoc -> TcS ()
traceTcS String
"setImplicationStatus(not-all-solved) }" (Implication -> SDoc
forall a. Outputable a => a -> SDoc
ppr Implication
new_implic)

      ; Maybe Implication -> TcS (Maybe Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Implication -> TcS (Maybe Implication))
-> Maybe Implication -> TcS (Maybe Implication)
forall a b. (a -> b) -> a -> b
$ Implication -> Maybe Implication
forall a. a -> Maybe a
Just Implication
new_implic }

 | Bool
otherwise  -- Everything is solved
              -- Set status to IC_Solved,
              -- and compute the dead givens and outer needs
              -- See Note [Tracking redundant constraints]
 = do { String -> SDoc -> TcS ()
traceTcS String
"setImplicationStatus(all-solved) {" (Implication -> SDoc
forall a. Outputable a => a -> SDoc
ppr Implication
implic)

      ; implic :: Implication
implic@(Implic { ic_need_inner :: Implication -> VarSet
ic_need_inner = VarSet
need_inner
                       , ic_need_outer :: Implication -> VarSet
ic_need_outer = VarSet
need_outer }) <- Implication -> TcS Implication
neededEvVars Implication
implic

      ; Bool
bad_telescope <- Implication -> TcS Bool
checkBadTelescope Implication
implic

      ; let dead_givens :: [TcTyVar]
dead_givens | SkolemInfo -> Bool
warnRedundantGivens SkolemInfo
info
                        = (TcTyVar -> Bool) -> [TcTyVar] -> [TcTyVar]
forall a. (a -> Bool) -> [a] -> [a]
filterOut (TcTyVar -> VarSet -> Bool
`elemVarSet` VarSet
need_inner) [TcTyVar]
givens
                        | Bool
otherwise = []   -- None to report

            discard_entire_implication :: Bool
discard_entire_implication  -- Can we discard the entire implication?
              =  [TcTyVar] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
dead_givens           -- No warning from this implication
              Bool -> Bool -> Bool
&& Bool -> Bool
not Bool
bad_telescope
              Bool -> Bool -> Bool
&& WantedConstraints -> Bool
isEmptyWC WantedConstraints
pruned_wc        -- No live children
              Bool -> Bool -> Bool
&& VarSet -> Bool
isEmptyVarSet VarSet
need_outer   -- No needed vars to pass up to parent

            final_status :: ImplicStatus
final_status
              | Bool
bad_telescope = ImplicStatus
IC_BadTelescope
              | Bool
otherwise     = IC_Solved :: [TcTyVar] -> ImplicStatus
IC_Solved { ics_dead :: [TcTyVar]
ics_dead = [TcTyVar]
dead_givens }
            final_implic :: Implication
final_implic = Implication
implic { ic_status :: ImplicStatus
ic_status = ImplicStatus
final_status
                                  , ic_wanted :: WantedConstraints
ic_wanted = WantedConstraints
pruned_wc }

      ; String -> SDoc -> TcS ()
traceTcS String
"setImplicationStatus(all-solved) }" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
        [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"discard:" SDoc -> SDoc -> SDoc
<+> Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
discard_entire_implication
             , String -> SDoc
text String
"new_implic:" SDoc -> SDoc -> SDoc
<+> Implication -> SDoc
forall a. Outputable a => a -> SDoc
ppr Implication
final_implic ]

      ; Maybe Implication -> TcS (Maybe Implication)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Implication -> TcS (Maybe Implication))
-> Maybe Implication -> TcS (Maybe Implication)
forall a b. (a -> b) -> a -> b
$ if Bool
discard_entire_implication
                 then Maybe Implication
forall a. Maybe a
Nothing
                 else Implication -> Maybe Implication
forall a. a -> Maybe a
Just Implication
final_implic }
 where
   WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples, wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implics, wc_holes :: WantedConstraints -> Bag Hole
wc_holes = Bag Hole
holes } = WantedConstraints
wc

   pruned_simples :: Cts
pruned_simples = Cts -> Cts
dropDerivedSimples Cts
simples
   pruned_implics :: Bag Implication
pruned_implics = (Implication -> Bool) -> Bag Implication -> Bag Implication
forall a. (a -> Bool) -> Bag a -> Bag a
filterBag Implication -> Bool
keep_me Bag Implication
implics
   pruned_wc :: WantedConstraints
pruned_wc = WC :: Cts -> Bag Implication -> Bag Hole -> WantedConstraints
WC { wc_simple :: Cts
wc_simple = Cts
pruned_simples
                  , wc_impl :: Bag Implication
wc_impl   = Bag Implication
pruned_implics
                  , wc_holes :: Bag Hole
wc_holes  = Bag Hole
holes }   -- do not prune holes; these should be reported

   keep_me :: Implication -> Bool
   keep_me :: Implication -> Bool
keep_me Implication
ic
     | IC_Solved { ics_dead :: ImplicStatus -> [TcTyVar]
ics_dead = [TcTyVar]
dead_givens } <- Implication -> ImplicStatus
ic_status Implication
ic
                          -- Fully solved
     , [TcTyVar] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [TcTyVar]
dead_givens   -- No redundant givens to report
     , Bag Implication -> Bool
forall a. Bag a -> Bool
isEmptyBag (WantedConstraints -> Bag Implication
wc_impl (Implication -> WantedConstraints
ic_wanted Implication
ic))
           -- And no children that might have things to report
     = Bool
False       -- Tnen we don't need to keep it
     | Bool
otherwise
     = Bool
True        -- Otherwise, keep it

checkBadTelescope :: Implication -> TcS Bool
-- True <=> the skolems form a bad telescope
-- See Note [Checking telescopes] in GHC.Tc.Types.Constraint
checkBadTelescope :: Implication -> TcS Bool
checkBadTelescope (Implic { ic_info :: Implication -> SkolemInfo
ic_info  = SkolemInfo
info
                          , ic_skols :: Implication -> [TcTyVar]
ic_skols = [TcTyVar]
skols })
  | ForAllSkol {} <- SkolemInfo
info
  = do{ [TcTyVar]
skols <- (TcTyVar -> TcS TcTyVar) -> [TcTyVar] -> TcS [TcTyVar]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TcTyVar -> TcS TcTyVar
TcS.zonkTyCoVarKind [TcTyVar]
skols
      ; Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (VarSet -> [TcTyVar] -> Bool
go VarSet
emptyVarSet ([TcTyVar] -> [TcTyVar]
forall a. [a] -> [a]
reverse [TcTyVar]
skols))}

  | Bool
otherwise
  = Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

  where
    go :: TyVarSet   -- skolems that appear *later* than the current ones
       -> [TcTyVar]  -- ordered skolems, in reverse order
       -> Bool       -- True <=> there is an out-of-order skolem
    go :: VarSet -> [TcTyVar] -> Bool
go VarSet
_ [] = Bool
False
    go VarSet
later_skols (TcTyVar
one_skol : [TcTyVar]
earlier_skols)
      | Type -> VarSet
tyCoVarsOfType (TcTyVar -> Type
tyVarKind TcTyVar
one_skol) VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
later_skols
      = Bool
True
      | Bool
otherwise
      = VarSet -> [TcTyVar] -> Bool
go (VarSet
later_skols VarSet -> TcTyVar -> VarSet
`extendVarSet` TcTyVar
one_skol) [TcTyVar]
earlier_skols

warnRedundantGivens :: SkolemInfo -> Bool
warnRedundantGivens :: SkolemInfo -> Bool
warnRedundantGivens (SigSkol UserTypeCtxt
ctxt Type
_ [(Name, TcTyVar)]
_)
  = case UserTypeCtxt
ctxt of
       FunSigCtxt Name
_ Bool
warn_redundant -> Bool
warn_redundant
       UserTypeCtxt
ExprSigCtxt                 -> Bool
True
       UserTypeCtxt
_                           -> Bool
False

  -- To think about: do we want to report redundant givens for
  -- pattern synonyms, PatSynSigSkol? c.f #9953, comment:21.
warnRedundantGivens (InstSkol {}) = Bool
True
warnRedundantGivens SkolemInfo
_             = Bool
False

neededEvVars :: Implication -> TcS Implication
-- Find all the evidence variables that are "needed",
-- and delete dead evidence bindings
--   See Note [Tracking redundant constraints]
--   See Note [Delete dead Given evidence bindings]
--
--   - Start from initial_seeds (from nested implications)
--
--   - Add free vars of RHS of all Wanted evidence bindings
--     and coercion variables accumulated in tcvs (all Wanted)
--
--   - Generate 'needed', the needed set of EvVars, by doing transitive
--     closure through Given bindings
--     e.g.   Needed {a,b}
--            Given  a = sc_sel a2
--            Then a2 is needed too
--
--   - Prune out all Given bindings that are not needed
--
--   - From the 'needed' set, delete ev_bndrs, the binders of the
--     evidence bindings, to give the final needed variables
--
neededEvVars :: Implication -> TcS Implication
neededEvVars implic :: Implication
implic@(Implic { ic_given :: Implication -> [TcTyVar]
ic_given = [TcTyVar]
givens
                            , ic_binds :: Implication -> EvBindsVar
ic_binds = EvBindsVar
ev_binds_var
                            , ic_wanted :: Implication -> WantedConstraints
ic_wanted = WC { wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implics }
                            , ic_need_inner :: Implication -> VarSet
ic_need_inner = VarSet
old_needs })
 = do { EvBindMap
ev_binds <- EvBindsVar -> TcS EvBindMap
TcS.getTcEvBindsMap EvBindsVar
ev_binds_var
      ; VarSet
tcvs     <- EvBindsVar -> TcS VarSet
TcS.getTcEvTyCoVars EvBindsVar
ev_binds_var

      ; let seeds1 :: VarSet
seeds1        = (Implication -> VarSet -> VarSet)
-> VarSet -> Bag Implication -> VarSet
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Implication -> VarSet -> VarSet
add_implic_seeds VarSet
old_needs Bag Implication
implics
            seeds2 :: VarSet
seeds2        = (EvBind -> VarSet -> VarSet) -> VarSet -> EvBindMap -> VarSet
forall a. (EvBind -> a -> a) -> a -> EvBindMap -> a
nonDetStrictFoldEvBindMap EvBind -> VarSet -> VarSet
add_wanted VarSet
seeds1 EvBindMap
ev_binds
                            -- It's OK to use a non-deterministic fold here
                            -- because add_wanted is commutative
            seeds3 :: VarSet
seeds3        = VarSet
seeds2 VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
tcvs
            need_inner :: VarSet
need_inner    = EvBindMap -> VarSet -> VarSet
findNeededEvVars EvBindMap
ev_binds VarSet
seeds3
            live_ev_binds :: EvBindMap
live_ev_binds = (EvBind -> Bool) -> EvBindMap -> EvBindMap
filterEvBindMap (VarSet -> EvBind -> Bool
needed_ev_bind VarSet
need_inner) EvBindMap
ev_binds
            need_outer :: VarSet
need_outer    = VarSet -> EvBindMap -> VarSet
varSetMinusEvBindMap VarSet
need_inner EvBindMap
live_ev_binds
                            VarSet -> [TcTyVar] -> VarSet
`delVarSetList` [TcTyVar]
givens

      ; EvBindsVar -> EvBindMap -> TcS ()
TcS.setTcEvBindsMap EvBindsVar
ev_binds_var EvBindMap
live_ev_binds
           -- See Note [Delete dead Given evidence bindings]

      ; String -> SDoc -> TcS ()
traceTcS String
"neededEvVars" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
        [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"old_needs:" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
old_needs
             , String -> SDoc
text String
"seeds3:" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
seeds3
             , String -> SDoc
text String
"tcvs:" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
tcvs
             , String -> SDoc
text String
"ev_binds:" SDoc -> SDoc -> SDoc
<+> EvBindMap -> SDoc
forall a. Outputable a => a -> SDoc
ppr EvBindMap
ev_binds
             , String -> SDoc
text String
"live_ev_binds:" SDoc -> SDoc -> SDoc
<+> EvBindMap -> SDoc
forall a. Outputable a => a -> SDoc
ppr EvBindMap
live_ev_binds ]

      ; Implication -> TcS Implication
forall (m :: * -> *) a. Monad m => a -> m a
return (Implication
implic { ic_need_inner :: VarSet
ic_need_inner = VarSet
need_inner
                       , ic_need_outer :: VarSet
ic_need_outer = VarSet
need_outer }) }
 where
   add_implic_seeds :: Implication -> VarSet -> VarSet
add_implic_seeds (Implic { ic_need_outer :: Implication -> VarSet
ic_need_outer = VarSet
needs }) VarSet
acc
      = VarSet
needs VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
acc

   needed_ev_bind :: VarSet -> EvBind -> Bool
needed_ev_bind VarSet
needed (EvBind { eb_lhs :: EvBind -> TcTyVar
eb_lhs = TcTyVar
ev_var
                                 , eb_is_given :: EvBind -> Bool
eb_is_given = Bool
is_given })
     | Bool
is_given  = TcTyVar
ev_var TcTyVar -> VarSet -> Bool
`elemVarSet` VarSet
needed
     | Bool
otherwise = Bool
True   -- Keep all wanted bindings

   add_wanted :: EvBind -> VarSet -> VarSet
   add_wanted :: EvBind -> VarSet -> VarSet
add_wanted (EvBind { eb_is_given :: EvBind -> Bool
eb_is_given = Bool
is_given, eb_rhs :: EvBind -> EvTerm
eb_rhs = EvTerm
rhs }) VarSet
needs
     | Bool
is_given  = VarSet
needs  -- Add the rhs vars of the Wanted bindings only
     | Bool
otherwise = EvTerm -> VarSet
evVarsOfTerm EvTerm
rhs VarSet -> VarSet -> VarSet
`unionVarSet` VarSet
needs

-------------------------------------------------
simplifyHoles :: Bag Hole -> TcS (Bag Hole)
simplifyHoles :: Bag Hole -> TcS (Bag Hole)
simplifyHoles = (Hole -> TcS Hole) -> Bag Hole -> TcS (Bag Hole)
forall (m :: * -> *) a b.
Monad m =>
(a -> m b) -> Bag a -> m (Bag b)
mapBagM Hole -> TcS Hole
simpl_hole
  where
    simpl_hole :: Hole -> TcS Hole
    simpl_hole :: Hole -> TcS Hole
simpl_hole h :: Hole
h@(Hole { hole_ty :: Hole -> Type
hole_ty = Type
ty, hole_loc :: Hole -> CtLoc
hole_loc = CtLoc
loc })
      = do { Type
ty' <- CtLoc -> Type -> TcS Type
flattenType CtLoc
loc Type
ty
           ; Hole -> TcS Hole
forall (m :: * -> *) a. Monad m => a -> m a
return (Hole
h { hole_ty :: Type
hole_ty = Type
ty' }) }

{- Note [Delete dead Given evidence bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As a result of superclass expansion, we speculatively
generate evidence bindings for Givens. E.g.
   f :: (a ~ b) => a -> b -> Bool
   f x y = ...
We'll have
   [G] d1 :: (a~b)
and we'll speculatively generate the evidence binding
   [G] d2 :: (a ~# b) = sc_sel d

Now d2 is available for solving.  But it may not be needed!  Usually
such dead superclass selections will eventually be dropped as dead
code, but:

 * It won't always be dropped (#13032).  In the case of an
   unlifted-equality superclass like d2 above, we generate
       case heq_sc d1 of d2 -> ...
   and we can't (in general) drop that case expression in case
   d1 is bottom.  So it's technically unsound to have added it
   in the first place.

 * Simply generating all those extra superclasses can generate lots of
   code that has to be zonked, only to be discarded later.  Better not
   to generate it in the first place.

   Moreover, if we simplify this implication more than once
   (e.g. because we can't solve it completely on the first iteration
   of simpl_looop), we'll generate all the same bindings AGAIN!

Easy solution: take advantage of the work we are doing to track dead
(unused) Givens, and use it to prune the Given bindings too.  This is
all done by neededEvVars.

This led to a remarkable 25% overall compiler allocation decrease in
test T12227.

But we don't get to discard all redundant equality superclasses, alas;
see #15205.

Note [Tracking redundant constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With Opt_WarnRedundantConstraints, GHC can report which
constraints of a type signature (or instance declaration) are
redundant, and can be omitted.  Here is an overview of how it
works:

----- What is a redundant constraint?

* The things that can be redundant are precisely the Given
  constraints of an implication.

* A constraint can be redundant in two different ways:
  a) It is implied by other givens.  E.g.
       f :: (Eq a, Ord a)     => blah   -- Eq a unnecessary
       g :: (Eq a, a~b, Eq b) => blah   -- Either Eq a or Eq b unnecessary
  b) It is not needed by the Wanted constraints covered by the
     implication E.g.
       f :: Eq a => a -> Bool
       f x = True  -- Equality not used

*  To find (a), when we have two Given constraints,
   we must be careful to drop the one that is a naked variable (if poss).
   So if we have
       f :: (Eq a, Ord a) => blah
   then we may find [G] sc_sel (d1::Ord a) :: Eq a
                    [G] d2 :: Eq a
   We want to discard d2 in favour of the superclass selection from
   the Ord dictionary.  This is done by GHC.Tc.Solver.Interact.solveOneFromTheOther
   See Note [Replacement vs keeping].

* To find (b) we need to know which evidence bindings are 'wanted';
  hence the eb_is_given field on an EvBind.

----- How tracking works

* The ic_need fields of an Implic records in-scope (given) evidence
  variables bound by the context, that were needed to solve this
  implication (so far).  See the declaration of Implication.

* When the constraint solver finishes solving all the wanteds in
  an implication, it sets its status to IC_Solved

  - The ics_dead field, of IC_Solved, records the subset of this
    implication's ic_given that are redundant (not needed).

* We compute which evidence variables are needed by an implication
  in setImplicationStatus.  A variable is needed if
    a) it is free in the RHS of a Wanted EvBind,
    b) it is free in the RHS of an EvBind whose LHS is needed,
    c) it is in the ics_need of a nested implication.

* We need to be careful not to discard an implication
  prematurely, even one that is fully solved, because we might
  thereby forget which variables it needs, and hence wrongly
  report a constraint as redundant.  But we can discard it once
  its free vars have been incorporated into its parent; or if it
  simply has no free vars. This careful discarding is also
  handled in setImplicationStatus.

----- Reporting redundant constraints

* GHC.Tc.Errors does the actual warning, in warnRedundantConstraints.

* We don't report redundant givens for *every* implication; only
  for those which reply True to GHC.Tc.Solver.warnRedundantGivens:

   - For example, in a class declaration, the default method *can*
     use the class constraint, but it certainly doesn't *have* to,
     and we don't want to report an error there.

   - More subtly, in a function definition
       f :: (Ord a, Ord a, Ix a) => a -> a
       f x = rhs
     we do an ambiguity check on the type (which would find that one
     of the Ord a constraints was redundant), and then we check that
     the definition has that type (which might find that both are
     redundant).  We don't want to report the same error twice, so we
     disable it for the ambiguity check.  Hence using two different
     FunSigCtxts, one with the warn-redundant field set True, and the
     other set False in
        - GHC.Tc.Gen.Bind.tcSpecPrag
        - GHC.Tc.Gen.Bind.tcTySig

  This decision is taken in setImplicationStatus, rather than GHC.Tc.Errors
  so that we can discard implication constraints that we don't need.
  So ics_dead consists only of the *reportable* redundant givens.

----- Shortcomings

Consider (see #9939)
    f2 :: (Eq a, Ord a) => a -> a -> Bool
    -- Ord a redundant, but Eq a is reported
    f2 x y = (x == y)

We report (Eq a) as redundant, whereas actually (Ord a) is.  But it's
really not easy to detect that!


Note [Cutting off simpl_loop]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is very important not to iterate in simpl_loop unless there is a chance
of progress.  #8474 is a classic example:

  * There's a deeply-nested chain of implication constraints.
       ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int

  * From the innermost one we get a [D] alpha ~ Int,
    but alpha is untouchable until we get out to the outermost one

  * We float [D] alpha~Int out (it is in floated_eqs), but since alpha
    is untouchable, the solveInteract in simpl_loop makes no progress

  * So there is no point in attempting to re-solve
       ?yn:betan => [W] ?x:Int
    via solveNestedImplications, because we'll just get the
    same [D] again

  * If we *do* re-solve, we'll get an infinite loop. It is cut off by
    the fixed bound of 10, but solving the next takes 10*10*...*10 (ie
    exponentially many) iterations!

Conclusion: we should call solveNestedImplications only if we did
some unification in solveSimpleWanteds; because that's the only way
we'll get more Givens (a unification is like adding a Given) to
allow the implication to make progress.
-}

promoteTyVarTcS :: TcTyVar  -> TcS ()
-- When we float a constraint out of an implication we must restore
-- invariant (WantedInv) in Note [TcLevel and untouchable type variables] in GHC.Tc.Utils.TcType
-- See Note [Promoting unification variables]
-- We don't just call promoteTyVar because we want to use unifyTyVar,
-- not writeMetaTyVar
promoteTyVarTcS :: TcTyVar -> TcS ()
promoteTyVarTcS TcTyVar
tv
  = do { TcLevel
tclvl <- TcS TcLevel
TcS.getTcLevel
       ; Bool -> TcS () -> TcS ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (TcLevel -> TcTyVar -> Bool
isFloatedTouchableMetaTyVar TcLevel
tclvl TcTyVar
tv) (TcS () -> TcS ()) -> TcS () -> TcS ()
forall a b. (a -> b) -> a -> b
$
         do { TcTyVar
cloned_tv <- TcTyVar -> TcS TcTyVar
TcS.cloneMetaTyVar TcTyVar
tv
            ; let rhs_tv :: TcTyVar
rhs_tv = TcTyVar -> TcLevel -> TcTyVar
setMetaTyVarTcLevel TcTyVar
cloned_tv TcLevel
tclvl
            ; TcTyVar -> Type -> TcS ()
unifyTyVar TcTyVar
tv (TcTyVar -> Type
mkTyVarTy TcTyVar
rhs_tv) } }

-- | Like 'defaultTyVar', but in the TcS monad.
defaultTyVarTcS :: TcTyVar -> TcS Bool
defaultTyVarTcS :: TcTyVar -> TcS Bool
defaultTyVarTcS TcTyVar
the_tv
  | TcTyVar -> Bool
isRuntimeRepVar TcTyVar
the_tv
  , Bool -> Bool
not (TcTyVar -> Bool
isTyVarTyVar TcTyVar
the_tv)
    -- TyVarTvs should only be unified with a tyvar
    -- never with a type; c.f. GHC.Tc.Utils.TcMType.defaultTyVar
    -- and Note [Inferring kinds for type declarations] in GHC.Tc.TyCl
  = do { String -> SDoc -> TcS ()
traceTcS String
"defaultTyVarTcS RuntimeRep" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
the_tv)
       ; TcTyVar -> Type -> TcS ()
unifyTyVar TcTyVar
the_tv Type
liftedRepTy
       ; Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }
  | TcTyVar -> Bool
isMultiplicityVar TcTyVar
the_tv
  , Bool -> Bool
not (TcTyVar -> Bool
isTyVarTyVar TcTyVar
the_tv)  -- TyVarTvs should only be unified with a tyvar
                             -- never with a type; c.f. TcMType.defaultTyVar
                             -- See Note [Kind generalisation and SigTvs]
  = do { String -> SDoc -> TcS ()
traceTcS String
"defaultTyVarTcS Multiplicity" (TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
the_tv)
       ; TcTyVar -> Type -> TcS ()
unifyTyVar TcTyVar
the_tv Type
manyDataConTy
       ; Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }
  | Bool
otherwise
  = Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False  -- the common case

approximateWC :: Bool -> WantedConstraints -> Cts
-- Postcondition: Wanted or Derived Cts
-- See Note [ApproximateWC]
approximateWC :: Bool -> WantedConstraints -> Cts
approximateWC Bool
float_past_equalities WantedConstraints
wc
  = VarSet -> WantedConstraints -> Cts
float_wc VarSet
emptyVarSet WantedConstraints
wc
  where
    float_wc :: TcTyCoVarSet -> WantedConstraints -> Cts
    float_wc :: VarSet -> WantedConstraints -> Cts
float_wc VarSet
trapping_tvs (WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples, wc_impl :: WantedConstraints -> Bag Implication
wc_impl = Bag Implication
implics })
      = (Ct -> Bool) -> Cts -> Cts
forall a. (a -> Bool) -> Bag a -> Bag a
filterBag (VarSet -> Ct -> Bool
is_floatable VarSet
trapping_tvs) Cts
simples Cts -> Cts -> Cts
forall a. Bag a -> Bag a -> Bag a
`unionBags`
        (Implication -> Cts) -> Bag Implication -> Cts
forall a b. (a -> Bag b) -> Bag a -> Bag b
concatMapBag (VarSet -> Implication -> Cts
float_implic VarSet
trapping_tvs) Bag Implication
implics
      where

    float_implic :: TcTyCoVarSet -> Implication -> Cts
    float_implic :: VarSet -> Implication -> Cts
float_implic VarSet
trapping_tvs Implication
imp
      | Bool
float_past_equalities Bool -> Bool -> Bool
|| Implication -> Bool
ic_no_eqs Implication
imp
      = VarSet -> WantedConstraints -> Cts
float_wc VarSet
new_trapping_tvs (Implication -> WantedConstraints
ic_wanted Implication
imp)
      | Bool
otherwise   -- Take care with equalities
      = Cts
emptyCts    -- See (1) under Note [ApproximateWC]
      where
        new_trapping_tvs :: VarSet
new_trapping_tvs = VarSet
trapping_tvs VarSet -> [TcTyVar] -> VarSet
`extendVarSetList` Implication -> [TcTyVar]
ic_skols Implication
imp

    is_floatable :: VarSet -> Ct -> Bool
is_floatable VarSet
skol_tvs Ct
ct
       | Ct -> Bool
isGivenCt Ct
ct     = Bool
False
       | Ct -> Bool
insolubleEqCt Ct
ct = Bool
False
       | Bool
otherwise        = Ct -> VarSet
tyCoVarsOfCt Ct
ct VarSet -> VarSet -> Bool
`disjointVarSet` VarSet
skol_tvs

{- Note [ApproximateWC]
~~~~~~~~~~~~~~~~~~~~~~~
approximateWC takes a constraint, typically arising from the RHS of a
let-binding whose type we are *inferring*, and extracts from it some
*simple* constraints that we might plausibly abstract over.  Of course
the top-level simple constraints are plausible, but we also float constraints
out from inside, if they are not captured by skolems.

The same function is used when doing type-class defaulting (see the call
to applyDefaultingRules) to extract constraints that might be defaulted.

There is one caveat:

1.  When inferring most-general types (in simplifyInfer), we do *not*
    float anything out if the implication binds equality constraints,
    because that defeats the OutsideIn story.  Consider
       data T a where
         TInt :: T Int
         MkT :: T a

       f TInt = 3::Int

    We get the implication (a ~ Int => res ~ Int), where so far we've decided
      f :: T a -> res
    We don't want to float (res~Int) out because then we'll infer
      f :: T a -> Int
    which is only on of the possible types. (GHC 7.6 accidentally *did*
    float out of such implications, which meant it would happily infer
    non-principal types.)

   HOWEVER (#12797) in findDefaultableGroups we are not worried about
   the most-general type; and we /do/ want to float out of equalities.
   Hence the boolean flag to approximateWC.

------ Historical note -----------
There used to be a second caveat, driven by #8155

   2. We do not float out an inner constraint that shares a type variable
      (transitively) with one that is trapped by a skolem.  Eg
          forall a.  F a ~ beta, Integral beta
      We don't want to float out (Integral beta).  Doing so would be bad
      when defaulting, because then we'll default beta:=Integer, and that
      makes the error message much worse; we'd get
          Can't solve  F a ~ Integer
      rather than
          Can't solve  Integral (F a)

      Moreover, floating out these "contaminated" constraints doesn't help
      when generalising either. If we generalise over (Integral b), we still
      can't solve the retained implication (forall a. F a ~ b).  Indeed,
      arguably that too would be a harder error to understand.

But this transitive closure stuff gives rise to a complex rule for
when defaulting actually happens, and one that was never documented.
Moreover (#12923), the more complex rule is sometimes NOT what
you want.  So I simply removed the extra code to implement the
contamination stuff.  There was zero effect on the testsuite (not even
#8155).
------ End of historical note -----------


Note [DefaultTyVar]
~~~~~~~~~~~~~~~~~~~
defaultTyVar is used on any un-instantiated meta type variables to
default any RuntimeRep variables to LiftedRep.  This is important
to ensure that instance declarations match.  For example consider

     instance Show (a->b)
     foo x = show (\_ -> True)

Then we'll get a constraint (Show (p ->q)) where p has kind (TYPE r),
and that won't match the tcTypeKind (*) in the instance decl.  See tests
tc217 and tc175.

We look only at touchable type variables. No further constraints
are going to affect these type variables, so it's time to do it by
hand.  However we aren't ready to default them fully to () or
whatever, because the type-class defaulting rules have yet to run.

An alternate implementation would be to emit a derived constraint setting
the RuntimeRep variable to LiftedRep, but this seems unnecessarily indirect.

Note [Promote _and_ default when inferring]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we are inferring a type, we simplify the constraint, and then use
approximateWC to produce a list of candidate constraints.  Then we MUST

  a) Promote any meta-tyvars that have been floated out by
     approximateWC, to restore invariant (WantedInv) described in
     Note [TcLevel and untouchable type variables] in GHC.Tc.Utils.TcType.

  b) Default the kind of any meta-tyvars that are not mentioned in
     in the environment.

To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we
have an instance (C ((x:*) -> Int)).  The instance doesn't match -- but it
should!  If we don't solve the constraint, we'll stupidly quantify over
(C (a->Int)) and, worse, in doing so skolemiseQuantifiedTyVar will quantify over
(b:*) instead of (a:OpenKind), which can lead to disaster; see #7332.
#7641 is a simpler example.

Note [Promoting unification variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we float an equality out of an implication we must "promote" free
unification variables of the equality, in order to maintain Invariant
(WantedInv) from Note [TcLevel and untouchable type variables] in
TcType.  for the leftover implication.

This is absolutely necessary. Consider the following example. We start
with two implications and a class with a functional dependency.

    class C x y | x -> y
    instance C [a] [a]

    (I1)      [untch=beta]forall b. 0 => F Int ~ [beta]
    (I2)      [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]

We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
They may react to yield that (beta := [alpha]) which can then be pushed inwards
the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
(alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:

    class C x y | x -> y where
     op :: x -> y -> ()

    instance C [a] [a]

    type family F a :: *

    h :: F Int -> ()
    h = undefined

    data TEx where
      TEx :: a -> TEx

    f (x::beta) =
        let g1 :: forall b. b -> ()
            g1 _ = h [x]
            g2 z = case z of TEx y -> (h [[undefined]], op x [y])
        in (g1 '3', g2 undefined)



*********************************************************************************
*                                                                               *
*                          Floating equalities                                  *
*                                                                               *
*********************************************************************************

Note [Float Equalities out of Implications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For ordinary pattern matches (including existentials) we float
equalities out of implications, for instance:
     data T where
       MkT :: Eq a => a -> T
     f x y = case x of MkT _ -> (y::Int)
We get the implication constraint (x::T) (y::alpha):
     forall a. [untouchable=alpha] Eq a => alpha ~ Int
We want to float out the equality into a scope where alpha is no
longer untouchable, to solve the implication!

But we cannot float equalities out of implications whose givens may
yield or contain equalities:

      data T a where
        T1 :: T Int
        T2 :: T Bool
        T3 :: T a

      h :: T a -> a -> Int

      f x y = case x of
                T1 -> y::Int
                T2 -> y::Bool
                T3 -> h x y

We generate constraint, for (x::T alpha) and (y :: beta):
   [untouchables = beta] (alpha ~ Int => beta ~ Int)   -- From 1st branch
   [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
   (alpha ~ beta)                                      -- From 3rd branch

If we float the equality (beta ~ Int) outside of the first implication and
the equality (beta ~ Bool) out of the second we get an insoluble constraint.
But if we just leave them inside the implications, we unify alpha := beta and
solve everything.

Principle:
    We do not want to float equalities out which may
    need the given *evidence* to become soluble.

Consequence: classes with functional dependencies don't matter (since there is
no evidence for a fundep equality), but equality superclasses do matter (since
they carry evidence).
-}

floatEqualities :: [TcTyVar] -> [EvId] -> EvBindsVar -> Bool
                -> WantedConstraints
                -> TcS (Cts, WantedConstraints)
-- Main idea: see Note [Float Equalities out of Implications]
--
-- Precondition: the wc_simple of the incoming WantedConstraints are
--               fully zonked, so that we can see their free variables
--
-- Postcondition: The returned floated constraints (Cts) are only
--                Wanted or Derived
--
-- Also performs some unifications (via promoteTyVar), adding to
-- monadically-carried ty_binds. These will be used when processing
-- floated_eqs later
--
-- Subtleties: Note [Float equalities from under a skolem binding]
--             Note [Skolem escape]
--             Note [What prevents a constraint from floating]
floatEqualities :: [TcTyVar]
-> [TcTyVar]
-> EvBindsVar
-> Bool
-> WantedConstraints
-> TcS (Cts, WantedConstraints)
floatEqualities [TcTyVar]
skols [TcTyVar]
given_ids EvBindsVar
ev_binds_var Bool
no_given_eqs
                wanteds :: WantedConstraints
wanteds@(WC { wc_simple :: WantedConstraints -> Cts
wc_simple = Cts
simples })
  | Bool -> Bool
not Bool
no_given_eqs  -- There are some given equalities, so don't float
  = (Cts, WantedConstraints) -> TcS (Cts, WantedConstraints)
forall (m :: * -> *) a. Monad m => a -> m a
return (Cts
forall a. Bag a
emptyBag, WantedConstraints
wanteds)   -- Note [Float Equalities out of Implications]

  | Bool
otherwise
  = do { -- First zonk: the inert set (from whence they came) is fully
         -- zonked, but unflattening may have filled in unification
         -- variables, and we /must/ see them.  Otherwise we may float
         -- constraints that mention the skolems!
         Cts
simples <- Cts -> TcS Cts
TcS.zonkSimples Cts
simples
       ; EvBindMap
binds   <- EvBindsVar -> TcS EvBindMap
TcS.getTcEvBindsMap EvBindsVar
ev_binds_var

       -- Now we can pick the ones to float
       -- The constraints are un-flattened and de-canonicalised
       ; let (Cts
candidate_eqs, Cts
no_float_cts) = (Ct -> Bool) -> Cts -> (Cts, Cts)
forall a. (a -> Bool) -> Bag a -> (Bag a, Bag a)
partitionBag Ct -> Bool
is_float_eq_candidate Cts
simples

             seed_skols :: VarSet
seed_skols = [TcTyVar] -> VarSet
mkVarSet [TcTyVar]
skols     VarSet -> VarSet -> VarSet
`unionVarSet`
                          [TcTyVar] -> VarSet
mkVarSet [TcTyVar]
given_ids VarSet -> VarSet -> VarSet
`unionVarSet`
                          (Ct -> VarSet -> VarSet) -> VarSet -> Cts -> VarSet
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Ct -> VarSet -> VarSet
add_non_flt_ct VarSet
emptyVarSet Cts
no_float_cts VarSet -> VarSet -> VarSet
`unionVarSet`
                          EvBindMap -> VarSet
evBindMapToVarSet EvBindMap
binds
             -- seed_skols: See Note [What prevents a constraint from floating] (1,2,3)
             -- Include the EvIds of any non-floating constraints

             extended_skols :: VarSet
extended_skols = (VarSet -> VarSet) -> VarSet -> VarSet
transCloVarSet (Cts -> VarSet -> VarSet
add_captured_ev_ids Cts
candidate_eqs) VarSet
seed_skols
                 -- extended_skols contains the EvIds of all the trapped constraints
                 -- See Note [What prevents a constraint from floating] (3)

             (Cts
flt_eqs, Cts
no_flt_eqs) = (Ct -> Bool) -> Cts -> (Cts, Cts)
forall a. (a -> Bool) -> Bag a -> (Bag a, Bag a)
partitionBag (VarSet -> Ct -> Bool
is_floatable VarSet
extended_skols)
                                                  Cts
candidate_eqs

             remaining_simples :: Cts
remaining_simples = Cts
no_float_cts Cts -> Cts -> Cts
`andCts` Cts
no_flt_eqs

       -- Promote any unification variables mentioned in the floated equalities
       -- See Note [Promoting unification variables]
       ; (TcTyVar -> TcS ()) -> [TcTyVar] -> TcS ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ TcTyVar -> TcS ()
promoteTyVarTcS (Cts -> [TcTyVar]
tyCoVarsOfCtsList Cts
flt_eqs)

       ; String -> SDoc -> TcS ()
traceTcS String
"floatEqualities" ([SDoc] -> SDoc
vcat [ String -> SDoc
text String
"Skols =" SDoc -> SDoc -> SDoc
<+> [TcTyVar] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [TcTyVar]
skols
                                          , String -> SDoc
text String
"Extended skols =" SDoc -> SDoc -> SDoc
<+> VarSet -> SDoc
forall a. Outputable a => a -> SDoc
ppr VarSet
extended_skols
                                          , String -> SDoc
text String
"Simples =" SDoc -> SDoc -> SDoc
<+> Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
simples
                                          , String -> SDoc
text String
"Candidate eqs =" SDoc -> SDoc -> SDoc
<+> Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
candidate_eqs
                                          , String -> SDoc
text String
"Floated eqs =" SDoc -> SDoc -> SDoc
<+> Cts -> SDoc
forall a. Outputable a => a -> SDoc
ppr Cts
flt_eqs])
       ; (Cts, WantedConstraints) -> TcS (Cts, WantedConstraints)
forall (m :: * -> *) a. Monad m => a -> m a
return ( Cts
flt_eqs, WantedConstraints
wanteds { wc_simple :: Cts
wc_simple = Cts
remaining_simples } ) }

  where
    add_non_flt_ct :: Ct -> VarSet -> VarSet
    add_non_flt_ct :: Ct -> VarSet -> VarSet
add_non_flt_ct Ct
ct VarSet
acc | Ct -> Bool
isDerivedCt Ct
ct = VarSet
acc
                          | Bool
otherwise      = VarSet -> TcTyVar -> VarSet
extendVarSet VarSet
acc (Ct -> TcTyVar
ctEvId Ct
ct)

    is_floatable :: VarSet -> Ct -> Bool
    is_floatable :: VarSet -> Ct -> Bool
is_floatable VarSet
skols Ct
ct
      | Ct -> Bool
isDerivedCt Ct
ct = Ct -> VarSet
tyCoVarsOfCt Ct
ct VarSet -> VarSet -> Bool
`disjointVarSet` VarSet
skols
      | Bool
otherwise      = Bool -> Bool
not (Ct -> TcTyVar
ctEvId Ct
ct TcTyVar -> VarSet -> Bool
`elemVarSet` VarSet
skols)

    add_captured_ev_ids :: Cts -> VarSet -> VarSet
    add_captured_ev_ids :: Cts -> VarSet -> VarSet
add_captured_ev_ids Cts
cts VarSet
skols = (Ct -> VarSet -> VarSet) -> VarSet -> Cts -> VarSet
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Ct -> VarSet -> VarSet
extra_skol VarSet
emptyVarSet Cts
cts
       where
         extra_skol :: Ct -> VarSet -> VarSet
extra_skol Ct
ct VarSet
acc
           | Ct -> Bool
isDerivedCt Ct
ct                           = VarSet
acc
           | Ct -> VarSet
tyCoVarsOfCt Ct
ct VarSet -> VarSet -> Bool
`intersectsVarSet` VarSet
skols = VarSet -> TcTyVar -> VarSet
extendVarSet VarSet
acc (Ct -> TcTyVar
ctEvId Ct
ct)
           | Bool
otherwise                                = VarSet
acc

    -- Identify which equalities are candidates for floating
    -- Float out alpha ~ ty which might be unified outside
    -- See Note [Which equalities to float]
    is_float_eq_candidate :: Ct -> Bool
is_float_eq_candidate Ct
ct
      | Type
pred <- Ct -> Type
ctPred Ct
ct
      , EqPred EqRel
NomEq Type
ty1 Type
ty2 <- Type -> Pred
classifyPredType Type
pred
      , case Ct
ct of
           CIrredCan {} -> Bool
False   -- See Note [Do not float blocked constraints]
           Ct
_            -> Bool
True    --   See #18855
      = Type -> Type -> Bool
float_eq Type
ty1 Type
ty2 Bool -> Bool -> Bool
|| Type -> Type -> Bool
float_eq Type
ty2 Type
ty1
      | Bool
otherwise
      = Bool
False

    float_eq :: Type -> Type -> Bool
float_eq Type
ty1 Type
ty2
      = case Type -> Maybe TcTyVar
getTyVar_maybe Type
ty1 of
          Just TcTyVar
tv1 -> TcTyVar -> Bool
isMetaTyVar TcTyVar
tv1
                   Bool -> Bool -> Bool
&& (Bool -> Bool
not (TcTyVar -> Bool
isTyVarTyVar TcTyVar
tv1) Bool -> Bool -> Bool
|| Type -> Bool
isTyVarTy Type
ty2)
          Maybe TcTyVar
Nothing  -> Bool
False

{- Note [Do not float blocked constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As #18855 showed, we must not float an equality that is blocked.
Consider
     forall a[4]. [W] co1: alpha[4] ~ Maybe (a[4] |> bco)
                  [W] co2: alpha[4] ~ Maybe (beta[4] |> bco])
                  [W] bco: kappa[2] ~ Type

Now co1, co2 are blocked by bco.  We will eventually float out bco
and solve it at level 2.  But the danger is that we will *also*
float out co2, and that is bad bad bad.  Because we'll promote alpha
and beta to level 2, and then fail to unify the promoted beta
with the skolem a[4].

Solution: don't float out blocked equalities. Remember: we only want
to float out if we can solve; see Note [Which equalities to float].

(Future plan: kill floating altogether.)

Note [Float equalities from under a skolem binding]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which of the simple equalities can we float out?  Obviously, only
ones that don't mention the skolem-bound variables.  But that is
over-eager. Consider
   [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int
The second constraint doesn't mention 'a'.  But if we float it,
we'll promote gamma[2] to gamma'[1].  Now suppose that we learn that
beta := Bool, and F a Bool = a, and G Bool _ = Int.  Then we'll
we left with the constraint
   [2] forall a. a ~ gamma'[1]
which is insoluble because gamma became untouchable.

Solution: float only constraints that stand a jolly good chance of
being soluble simply by being floated, namely ones of form
      a ~ ty
where 'a' is a currently-untouchable unification variable, but may
become touchable by being floated (perhaps by more than one level).

We had a very complicated rule previously, but this is nice and
simple.  (To see the notes, look at this Note in a version of
GHC.Tc.Solver prior to Oct 2014).

Note [Which equalities to float]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which equalities should we float?  We want to float ones where there
is a decent chance that floating outwards will allow unification to
happen.  In particular, float out equalities that are:

* Of form (alpha ~# ty) or (ty ~# alpha), where
   * alpha is a meta-tyvar.
   * And 'alpha' is not a TyVarTv with 'ty' being a non-tyvar.  In that
     case, floating out won't help either, and it may affect grouping
     of error messages.

  NB: generally we won't see (ty ~ alpha), with alpha on the right because
  of Note [Unification variables on the left] in GHC.Tc.Utils.Unify.
  But if we start with (F tys ~ alpha), it will orient as (fmv ~ alpha),
  and unflatten back to (F tys ~ alpha). So we must look for alpha on
  the right too.  Example T4494.

* Nominal.  No point in floating (alpha ~R# ty), because we do not
  unify representational equalities even if alpha is touchable.
  See Note [Do not unify representational equalities] in GHC.Tc.Solver.Interact.

Note [Skolem escape]
~~~~~~~~~~~~~~~~~~~~
You might worry about skolem escape with all this floating.
For example, consider
    [2] forall a. (a ~ F beta[2] delta,
                   Maybe beta[2] ~ gamma[1])

The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and
solve with gamma := beta. But what if later delta:=Int, and
  F b Int = b.
Then we'd get a ~ beta[2], and solve to get beta:=a, and now the
skolem has escaped!

But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2]
to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be.

Note [What prevents a constraint from floating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What /prevents/ a constraint from floating?  If it mentions one of the
"bound variables of the implication".  What are they?

The "bound variables of the implication" are

  1. The skolem type variables `ic_skols`

  2. The "given" evidence variables `ic_given`.  Example:
         forall a. (co :: t1 ~# t2) =>  [W] co2 : (a ~# b |> co)
     Here 'co' is bound

  3. The binders of all evidence bindings in `ic_binds`. Example
         forall a. (d :: t1 ~ t2)
            EvBinds { (co :: t1 ~# t2) = superclass-sel d }
            => [W] co2 : (a ~# b |> co)
     Here `co` is gotten by superclass selection from `d`, and the
     wanted constraint co2 must not float.

  4. And the evidence variable of any equality constraint (incl
     Wanted ones) whose type mentions a bound variable.  Example:
        forall k. [W] co1 :: t1 ~# t2 |> co2
                  [W] co2 :: k ~# *
     Here, since `k` is bound, so is `co2` and hence so is `co1`.

Here (1,2,3) are handled by the "seed_skols" calculation, and
(4) is done by the transCloVarSet call.

The possible dependence on givens, and evidence bindings, is more
subtle than we'd realised at first.  See #14584.

How can (4) arise? Suppose we have (k :: *), (a :: k), and ([G} k ~ *).
Then form an equality like (a ~ Int) we might end up with
    [W] co1 :: k ~ *
    [W] co2 :: (a |> co1) ~ Int


*********************************************************************************
*                                                                               *
*                          Defaulting and disambiguation                        *
*                                                                               *
*********************************************************************************
-}

applyDefaultingRules :: WantedConstraints -> TcS Bool
-- True <=> I did some defaulting, by unifying a meta-tyvar
-- Input WantedConstraints are not necessarily zonked

applyDefaultingRules :: WantedConstraints -> TcS Bool
applyDefaultingRules WantedConstraints
wanteds
  | WantedConstraints -> Bool
isEmptyWC WantedConstraints
wanteds
  = Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
  | Bool
otherwise
  = do { info :: ([Type], (Bool, Bool))
info@([Type]
default_tys, (Bool, Bool)
_) <- TcS ([Type], (Bool, Bool))
getDefaultInfo
       ; WantedConstraints
wanteds               <- WantedConstraints -> TcS WantedConstraints
TcS.zonkWC WantedConstraints
wanteds

       ; let groups :: [(TcTyVar, [Ct])]
groups = ([Type], (Bool, Bool)) -> WantedConstraints -> [(TcTyVar, [Ct])]
findDefaultableGroups ([Type], (Bool, Bool))
info WantedConstraints
wanteds

       ; String -> SDoc -> TcS ()
traceTcS String
"applyDefaultingRules {" (SDoc -> TcS ()) -> SDoc -> TcS ()
forall a b. (a -> b) -> a -> b
$
                  [SDoc] -> SDoc
vcat [ String -> SDoc
text String
"wanteds =" SDoc -> SDoc -> SDoc
<+> WantedConstraints -> SDoc
forall a. Outputable a => a -> SDoc
ppr WantedConstraints
wanteds
                       , String -> SDoc
text String
"groups  =" SDoc -> SDoc -> SDoc
<+> [(TcTyVar, [Ct])] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(TcTyVar, [Ct])]
groups
                       , String -> SDoc
text String
"info    =" SDoc -> SDoc -> SDoc
<+> ([Type], (Bool, Bool)) -> SDoc
forall a. Outputable a => a -> SDoc
ppr ([Type], (Bool, Bool))
info ]

       ; [Bool]
something_happeneds <- ((TcTyVar, [Ct]) -> TcS Bool) -> [(TcTyVar, [Ct])] -> TcS [Bool]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ([Type] -> (TcTyVar, [Ct]) -> TcS Bool
disambigGroup [Type]
default_tys) [(TcTyVar, [Ct])]
groups

       ; String -> SDoc -> TcS ()
traceTcS String
"applyDefaultingRules }" ([Bool] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Bool]
something_happeneds)

       ; Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return ([Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or [Bool]
something_happeneds) }

findDefaultableGroups
    :: ( [Type]
       , (Bool,Bool) )     -- (Overloaded strings, extended default rules)
    -> WantedConstraints   -- Unsolved (wanted or derived)
    -> [(TyVar, [Ct])]
findDefaultableGroups :: ([Type], (Bool, Bool)) -> WantedConstraints -> [(TcTyVar, [Ct])]
findDefaultableGroups ([Type]
default_tys, (Bool
ovl_strings, Bool
extended_defaults)) WantedConstraints
wanteds
  | [Type] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Type]
default_tys
  = []
  | Bool
otherwise
  = [ (TcTyVar
tv, ((Ct, Class, TcTyVar) -> Ct) -> [(Ct, Class, TcTyVar)] -> [Ct]
forall a b. (a -> b) -> [a] -> [b]
map (Ct, Class, TcTyVar) -> Ct
forall a b c. (a, b, c) -> a
fstOf3 [(Ct, Class, TcTyVar)]
group)
    | group' :: NonEmpty (Ct, Class, TcTyVar)
group'@((Ct
_,Class
_,TcTyVar
tv) :| [(Ct, Class, TcTyVar)]
_) <- [NonEmpty (Ct, Class, TcTyVar)]
unary_groups
    , let group :: [(Ct, Class, TcTyVar)]
group = NonEmpty (Ct, Class, TcTyVar) -> [(Ct, Class, TcTyVar)]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NonEmpty (Ct, Class, TcTyVar)
group'
    , TcTyVar -> Bool
defaultable_tyvar TcTyVar
tv
    , [Class] -> Bool
defaultable_classes (((Ct, Class, TcTyVar) -> Class)
-> [(Ct, Class, TcTyVar)] -> [Class]
forall a b. (a -> b) -> [a] -> [b]
map (Ct, Class, TcTyVar) -> Class
forall a b c. (a, b, c) -> b
sndOf3 [(Ct, Class, TcTyVar)]
group) ]
  where
    simples :: Cts
simples                = Bool -> WantedConstraints -> Cts
approximateWC Bool
True WantedConstraints
wanteds
    ([(Ct, Class, TcTyVar)]
unaries, [Ct]
non_unaries) = (Ct -> Either (Ct, Class, TcTyVar) Ct)
-> [Ct] -> ([(Ct, Class, TcTyVar)], [Ct])
forall a b c. (a -> Either b c) -> [a] -> ([b], [c])
partitionWith Ct -> Either (Ct, Class, TcTyVar) Ct
find_unary (Cts -> [Ct]
forall a. Bag a -> [a]
bagToList Cts
simples)
    unary_groups :: [NonEmpty (Ct, Class, TcTyVar)]
unary_groups           = ((Ct, Class, TcTyVar) -> (Ct, Class, TcTyVar) -> Ordering)
-> [(Ct, Class, TcTyVar)] -> [NonEmpty (Ct, Class, TcTyVar)]
forall a. (a -> a -> Ordering) -> [a] -> [NonEmpty a]
equivClasses (Ct, Class, TcTyVar) -> (Ct, Class, TcTyVar) -> Ordering
forall {a} {a} {b} {a} {b}.
Ord a =>
(a, b, a) -> (a, b, a) -> Ordering
cmp_tv [(Ct, Class, TcTyVar)]
unaries

    unary_groups :: [NonEmpty (Ct, Class, TcTyVar)] -- (C tv) constraints
    unaries      :: [(Ct, Class, TcTyVar)]          -- (C tv) constraints
    non_unaries  :: [Ct]                            -- and *other* constraints

        -- Finds unary type-class constraints
        -- But take account of polykinded classes like Typeable,
        -- which may look like (Typeable * (a:*))   (#8931)
    find_unary :: Ct -> Either (Ct, Class, TyVar) Ct
    find_unary :: Ct -> Either (Ct, Class, TcTyVar) Ct
find_unary Ct
cc
        | Just (Class
cls,[Type]
tys)   <- Type -> Maybe (Class, [Type])
getClassPredTys_maybe (Ct -> Type
ctPred Ct
cc)
        , [Type
ty] <- TyCon -> [Type] -> [Type]
filterOutInvisibleTypes (Class -> TyCon
classTyCon Class
cls) [Type]
tys
              -- Ignore invisible arguments for this purpose
        , Just TcTyVar
tv <- Type -> Maybe TcTyVar
tcGetTyVar_maybe Type
ty
        , TcTyVar -> Bool
isMetaTyVar TcTyVar
tv  -- We might have runtime-skolems in GHCi, and
                          -- we definitely don't want to try to assign to those!
        = (Ct, Class, TcTyVar) -> Either (Ct, Class, TcTyVar) Ct
forall a b. a -> Either a b
Left (Ct
cc, Class
cls, TcTyVar
tv)
    find_unary Ct
cc = Ct -> Either (Ct, Class, TcTyVar) Ct
forall a b. b -> Either a b
Right Ct
cc  -- Non unary or non dictionary

    bad_tvs :: TcTyCoVarSet  -- TyVars mentioned by non-unaries
    bad_tvs :: VarSet
bad_tvs = (Ct -> VarSet) -> [Ct] -> VarSet
forall a. (a -> VarSet) -> [a] -> VarSet
mapUnionVarSet Ct -> VarSet
tyCoVarsOfCt [Ct]
non_unaries

    cmp_tv :: (a, b, a) -> (a, b, a) -> Ordering
cmp_tv (a
_,b
_,a
tv1) (a
_,b
_,a
tv2) = a
tv1 a -> a -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` a
tv2

    defaultable_tyvar :: TcTyVar -> Bool
    defaultable_tyvar :: TcTyVar -> Bool
defaultable_tyvar TcTyVar
tv
        = let b1 :: Bool
b1 = TcTyVar -> Bool
isTyConableTyVar TcTyVar
tv  -- Note [Avoiding spurious errors]
              b2 :: Bool
b2 = Bool -> Bool
not (TcTyVar
tv TcTyVar -> VarSet -> Bool
`elemVarSet` VarSet
bad_tvs)
          in Bool
b1 Bool -> Bool -> Bool
&& (Bool
b2 Bool -> Bool -> Bool
|| Bool
extended_defaults) -- Note [Multi-parameter defaults]

    defaultable_classes :: [Class] -> Bool
    defaultable_classes :: [Class] -> Bool
defaultable_classes [Class]
clss
        | Bool
extended_defaults = (Class -> Bool) -> [Class] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Bool -> Class -> Bool
isInteractiveClass Bool
ovl_strings) [Class]
clss
        | Bool
otherwise         = (Class -> Bool) -> [Class] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Class -> Bool
is_std_class [Class]
clss Bool -> Bool -> Bool
&& ((Class -> Bool) -> [Class] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Bool -> Class -> Bool
isNumClass Bool
ovl_strings) [Class]
clss)

    -- is_std_class adds IsString to the standard numeric classes,
    -- when -foverloaded-strings is enabled
    is_std_class :: Class -> Bool
is_std_class Class
cls = Class -> Bool
isStandardClass Class
cls Bool -> Bool -> Bool
||
                       (Bool
ovl_strings Bool -> Bool -> Bool
&& (Class
cls Class -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
isStringClassKey))

------------------------------
disambigGroup :: [Type]            -- The default types
              -> (TcTyVar, [Ct])   -- All classes of the form (C a)
                                   --  sharing same type variable
              -> TcS Bool   -- True <=> something happened, reflected in ty_binds

disambigGroup :: [Type] -> (TcTyVar, [Ct]) -> TcS Bool
disambigGroup [] (TcTyVar, [Ct])
_
  = Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
disambigGroup (Type
default_ty:[Type]
default_tys) group :: (TcTyVar, [Ct])
group@(TcTyVar
the_tv, [Ct]
wanteds)
  = do { String -> SDoc -> TcS ()
traceTcS String
"disambigGroup {" ([SDoc] -> SDoc
vcat [ Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
default_ty, TcTyVar -> SDoc
forall a. Outputable a => a -> SDoc
ppr TcTyVar
the_tv, [Ct] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [Ct]
wanteds ])
       ; EvBindsVar
fake_ev_binds_var <- TcS EvBindsVar
TcS.newTcEvBinds
       ; TcLevel
tclvl             <- TcS TcLevel
TcS.getTcLevel
       ; Bool
success <- EvBindsVar -> TcLevel -> TcS Bool -> TcS Bool
forall a. EvBindsVar -> TcLevel -> TcS a -> TcS a
nestImplicTcS EvBindsVar
fake_ev_binds_var (TcLevel -> TcLevel
pushTcLevel TcLevel
tclvl) TcS Bool
try_group

       ; if Bool
success then
             -- Success: record the type variable binding, and return
             do { TcTyVar -> Type -> TcS ()
unifyTyVar TcTyVar
the_tv Type
default_ty
                ; TcM () -> TcS ()
forall a. TcM a -> TcS a
wrapWarnTcS (TcM () -> TcS ()) -> TcM () -> TcS ()
forall a b. (a -> b) -> a -> b
$ [Ct] -> Type -> TcM ()
warnDefaulting [Ct]
wanteds Type
default_ty
                ; String -> SDoc -> TcS ()
traceTcS String
"disambigGroup succeeded }" (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
default_ty)
                ; Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True }
         else
             -- Failure: try with the next type
             do { String -> SDoc -> TcS ()
traceTcS String
"disambigGroup failed, will try other default types }"
                           (Type -> SDoc
forall a. Outputable a => a -> SDoc
ppr Type
default_ty)
                ; [Type] -> (TcTyVar, [Ct]) -> TcS Bool
disambigGroup [Type]
default_tys (TcTyVar, [Ct])
group } }
  where
    try_group :: TcS Bool
try_group
      | Just TCvSubst
subst <- Maybe TCvSubst
mb_subst
      = do { TcLclEnv
lcl_env <- TcS TcLclEnv
TcS.getLclEnv
           ; TcLevel
tc_lvl <- TcS TcLevel
TcS.getTcLevel
           ; let loc :: CtLoc
loc = TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
mkGivenLoc TcLevel
tc_lvl SkolemInfo
UnkSkol TcLclEnv
lcl_env
           ; [CtEvidence]
wanted_evs <- (Ct -> TcS CtEvidence) -> [Ct] -> TcS [CtEvidence]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (CtLoc -> Type -> TcS CtEvidence
newWantedEvVarNC CtLoc
loc (Type -> TcS CtEvidence) -> (Ct -> Type) -> Ct -> TcS CtEvidence
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasCallStack => TCvSubst -> Type -> Type
TCvSubst -> Type -> Type
substTy TCvSubst
subst (Type -> Type) -> (Ct -> Type) -> Ct -> Type
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Ct -> Type
ctPred)
                                [Ct]
wanteds
           ; (WantedConstraints -> Bool) -> TcS WantedConstraints -> TcS Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap WantedConstraints -> Bool
isEmptyWC (TcS WantedConstraints -> TcS Bool)
-> TcS WantedConstraints -> TcS Bool
forall a b. (a -> b) -> a -> b
$
             Cts -> TcS WantedConstraints
solveSimpleWanteds (Cts -> TcS WantedConstraints) -> Cts -> TcS WantedConstraints
forall a b. (a -> b) -> a -> b
$ [Ct] -> Cts
forall a. [a] -> Bag a
listToBag ([Ct] -> Cts) -> [Ct] -> Cts
forall a b. (a -> b) -> a -> b
$
             (CtEvidence -> Ct) -> [CtEvidence] -> [Ct]
forall a b. (a -> b) -> [a] -> [b]
map CtEvidence -> Ct
mkNonCanonical [CtEvidence]
wanted_evs }

      | Bool
otherwise
      = Bool -> TcS Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

    the_ty :: Type
the_ty   = TcTyVar -> Type
mkTyVarTy TcTyVar
the_tv
    mb_subst :: Maybe TCvSubst
mb_subst = Type -> Type -> Maybe TCvSubst
tcMatchTyKi Type
the_ty Type
default_ty
      -- Make sure the kinds match too; hence this call to tcMatchTyKi
      -- E.g. suppose the only constraint was (Typeable k (a::k))
      -- With the addition of polykinded defaulting we also want to reject
      -- ill-kinded defaulting attempts like (Eq []) or (Foldable Int) here.

-- In interactive mode, or with -XExtendedDefaultRules,
-- we default Show a to Show () to avoid graututious errors on "show []"
isInteractiveClass :: Bool   -- -XOverloadedStrings?
                   -> Class -> Bool
isInteractiveClass :: Bool -> Class -> Bool
isInteractiveClass Bool
ovl_strings Class
cls
    = Bool -> Class -> Bool
isNumClass Bool
ovl_strings Class
cls Bool -> Bool -> Bool
|| (Class -> Unique
classKey Class
cls Unique -> [Unique] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Unique]
interactiveClassKeys)

    -- isNumClass adds IsString to the standard numeric classes,
    -- when -foverloaded-strings is enabled
isNumClass :: Bool   -- -XOverloadedStrings?
           -> Class -> Bool
isNumClass :: Bool -> Class -> Bool
isNumClass Bool
ovl_strings Class
cls
  = Class -> Bool
isNumericClass Class
cls Bool -> Bool -> Bool
|| (Bool
ovl_strings Bool -> Bool -> Bool
&& (Class
cls Class -> Unique -> Bool
forall a. Uniquable a => a -> Unique -> Bool
`hasKey` Unique
isStringClassKey))


{-
Note [Avoiding spurious errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When doing the unification for defaulting, we check for skolem
type variables, and simply don't default them.  For example:
   f = (*)      -- Monomorphic
   g :: Num a => a -> a
   g x = f x x
Here, we get a complaint when checking the type signature for g,
that g isn't polymorphic enough; but then we get another one when
dealing with the (Num a) context arising from f's definition;
we try to unify a with Int (to default it), but find that it's
already been unified with the rigid variable from g's type sig.

Note [Multi-parameter defaults]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With -XExtendedDefaultRules, we default only based on single-variable
constraints, but do not exclude from defaulting any type variables which also
appear in multi-variable constraints. This means that the following will
default properly:

   default (Integer, Double)

   class A b (c :: Symbol) where
      a :: b -> Proxy c

   instance A Integer c where a _ = Proxy

   main = print (a 5 :: Proxy "5")

Note that if we change the above instance ("instance A Integer") to
"instance A Double", we get an error:

   No instance for (A Integer "5")

This is because the first defaulted type (Integer) has successfully satisfied
its single-parameter constraints (in this case Num).
-}