TcCanonical.hs 100 KB
Newer Older
1 2
{-# LANGUAGE CPP #-}

3
module TcCanonical(
4 5
     canonicalize,
     unifyDerived,
6
     makeSuperClasses, maybeSym,
7 8
     StopOrContinue(..), stopWith, continueWith,
     solveCallStack    -- For TcSimplify
9
  ) where
10 11 12

#include "HsVersions.h"

13 14
import GhcPrelude

15
import TcRnTypes
16
import TcUnify( swapOverTyVars, metaTyVarUpdateOK )
17
import TcType
18
import Type
19 20
import TcFlatten
import TcSMonad
21
import TcEvidence
22
import TcEvTerm
23 24
import Class
import TyCon
25
import TyCoRep   -- cleverly decomposes types, good for completeness checking
26
import TysWiredIn( cTupleTyConName )
27
import Coercion
28 29
import CoreSyn
import Id( idType, mkTemplateLocals )
30 31
import FamInstEnv ( FamInstEnvs )
import FamInst ( tcTopNormaliseNewTypeTF_maybe )
32
import Var
33
import VarEnv( mkInScopeSet )
34
import VarSet( delVarSetList )
35
import Outputable
36
import DynFlags( DynFlags )
37
import NameSet
38
import RdrName
39
import HsTypes( HsIPName(..) )
40

41
import Pair
42
import Util
43
import Bag
44 45
import MonadUtils
import Control.Monad
46
import Data.Maybe ( isJust )
47
import Data.List  ( zip4, foldl' )
48
import BasicTypes
49

50 51
import Data.Bifunctor ( bimap )

Austin Seipp's avatar
Austin Seipp committed
52 53 54 55 56 57
{-
************************************************************************
*                                                                      *
*                      The Canonicaliser                               *
*                                                                      *
************************************************************************
58

59 60
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
61

62
Canonicalization converts a simple constraint to a canonical form. It is
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
unary (i.e. treats individual constraints one at a time).

Constraints originating from user-written code come into being as
CNonCanonicals (except for CHoleCans, arising from holes). We know nothing
about these constraints. So, first:

     Classify CNonCanoncal constraints, depending on whether they
     are equalities, class predicates, or other.

Then proceed depending on the shape of the constraint. Generally speaking,
each constraint gets flattened and then decomposed into one of several forms
(see type Ct in TcRnTypes).

When an already-canonicalized constraint gets kicked out of the inert set,
it must be recanonicalized. But we know a bit about its shape from the
last time through, so we can skip the classification step.

Austin Seipp's avatar
Austin Seipp committed
80
-}
81

82 83 84
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

85
canonicalize :: Ct -> TcS (StopOrContinue Ct)
86 87
canonicalize (CNonCanonical { cc_ev = ev })
  = {-# SCC "canNC" #-}
88
    case classifyPredType pred of
89 90 91 92
      ClassPred cls tys     -> do traceTcS "canEvNC:cls" (ppr cls <+> ppr tys)
                                  canClassNC ev cls tys
      EqPred eq_rel ty1 ty2 -> do traceTcS "canEvNC:eq" (ppr ty1 $$ ppr ty2)
                                  canEqNC    ev eq_rel ty1 ty2
93
      IrredPred {}          -> do traceTcS "canEvNC:irred" (ppr pred)
94
                                  canIrred ev
95 96 97 98 99 100 101
      ForAllPred _ _ pred   -> do traceTcS "canEvNC:forall" (ppr pred)
                                  canForAll ev (isClassPred pred)
  where
    pred = ctEvPred ev

canonicalize (CQuantCan (QCI { qci_ev = ev, qci_pend_sc = pend_sc }))
  = canForAll ev pend_sc
102 103

canonicalize (CIrredCan { cc_ev = ev })
104 105 106 107 108 109 110 111 112
  | EqPred eq_rel ty1 ty2 <- classifyPredType (ctEvPred ev)
  = -- For insolubles (all of which are equalities, do /not/ flatten the arguments
    -- In Trac #14350 doing so led entire-unnecessary and ridiculously large
    -- type function expansion.  Instead, canEqNC just applies
    -- the substitution to the predicate, and may do decomposition;
    --    e.g. a ~ [a], where [G] a ~ [Int], can decompose
    canEqNC ev eq_rel ty1 ty2

  | otherwise
113
  = canIrred ev
114

115 116
canonicalize (CDictCan { cc_ev = ev, cc_class  = cls
                       , cc_tyargs = xis, cc_pend_sc = pend_sc })
117
  = {-# SCC "canClass" #-}
118 119
    canClass ev cls xis pend_sc

120
canonicalize (CTyEqCan { cc_ev = ev
121
                       , cc_tyvar  = tv
122 123
                       , cc_rhs    = xi
                       , cc_eq_rel = eq_rel })
124
  = {-# SCC "canEqLeafTyVarEq" #-}
125 126 127
    canEqNC ev eq_rel (mkTyVarTy tv) xi
      -- NB: Don't use canEqTyVar because that expects flattened types,
      -- and tv and xi may not be flat w.r.t. an updated inert set
128

129
canonicalize (CFunEqCan { cc_ev = ev
130 131
                        , cc_fun    = fn
                        , cc_tyargs = xis1
132
                        , cc_fsk    = fsk })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
133
  = {-# SCC "canEqLeafFunEq" #-}
134
    canCFunEqCan ev fn xis1 fsk
135

136 137
canonicalize (CHoleCan { cc_ev = ev, cc_hole = hole })
  = canHole ev hole
138

Austin Seipp's avatar
Austin Seipp committed
139 140 141 142 143 144 145
{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}
146

147
canClassNC :: CtEvidence -> Class -> [Type] -> TcS (StopOrContinue Ct)
148
-- "NC" means "non-canonical"; that is, we have got here
Gabor Greif's avatar
Gabor Greif committed
149
-- from a NonCanonical constraint, not from a CDictCan
Simon Peyton Jones's avatar
Simon Peyton Jones committed
150
-- Precondition: EvVar is class evidence
151 152
canClassNC ev cls tys
  | isGiven ev  -- See Note [Eagerly expand given superclasses]
153
  = do { sc_cts <- mkStrictSuperClasses ev [] [] cls tys
154 155
       ; emitWork sc_cts
       ; canClass ev cls tys False }
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

  | isWanted ev
  , Just ip_name <- isCallStackPred cls tys
  , OccurrenceOf func <- ctLocOrigin loc
  -- If we're given a CallStack constraint that arose from a function
  -- call, we need to push the current call-site onto the stack instead
  -- of solving it directly from a given.
  -- See Note [Overview of implicit CallStacks] in TcEvidence
  -- and Note [Solving CallStack constraints] in TcSMonad
  = do { -- First we emit a new constraint that will capture the
         -- given CallStack.
       ; let new_loc = setCtLocOrigin loc (IPOccOrigin (HsIPName ip_name))
                            -- We change the origin to IPOccOrigin so
                            -- this rule does not fire again.
                            -- See Note [Overview of implicit CallStacks]

       ; new_ev <- newWantedEvVarNC new_loc pred

         -- Then we solve the wanted by pushing the call-site
         -- onto the newly emitted CallStack
176
       ; let ev_cs = EvCsPushCall func (ctLocSpan loc) (ctEvExpr new_ev)
177 178 179 180
       ; solveCallStack ev ev_cs

       ; canClass new_ev cls tys False }

181 182
  | otherwise
  = canClass ev cls tys (has_scs cls)
183

184 185
  where
    has_scs cls = not (null (classSCTheta cls))
186 187 188 189 190 191 192 193 194
    loc  = ctEvLoc ev
    pred = ctEvPred ev

solveCallStack :: CtEvidence -> EvCallStack -> TcS ()
-- Also called from TcSimplify when defaulting call stacks
solveCallStack ev ev_cs = do
  -- We're given ev_cs :: CallStack, but the evidence term should be a
  -- dictionary, so we have to coerce ev_cs to a dictionary for
  -- `IP ip CallStack`. See Note [Overview of implicit CallStacks]
195 196
  cs_tm <- evCallStack ev_cs
  let ev_tm = mkEvCast cs_tm (wrapIP (ctEvPred ev))
197
  setEvBindIfWanted ev ev_tm
198

199 200 201 202
canClass :: CtEvidence
         -> Class -> [Type]
         -> Bool            -- True <=> un-explored superclasses
         -> TcS (StopOrContinue Ct)
203
-- Precondition: EvVar is class evidence
204

205
canClass ev cls tys pend_sc
206 207
  =   -- all classes do *nominal* matching
    ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
208 209 210
    do { (xis, cos, _kind_co) <- flattenArgsNom ev cls_tc tys
       ; MASSERT( isTcReflCo _kind_co )
       ; let co = mkTcTyConAppCo Nominal cls_tc cos
211
             xi = mkClassPred cls xis
212
             mk_ct new_ev = CDictCan { cc_ev = new_ev
213 214 215
                                     , cc_tyargs = xis
                                     , cc_class = cls
                                     , cc_pend_sc = pend_sc }
216
       ; mb <- rewriteEvidence ev xi co
217
       ; traceTcS "canClass" (vcat [ ppr ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
218
                                   , ppr xi, ppr mb ])
219
       ; return (fmap mk_ct mb) }
220 221
  where
    cls_tc = classTyCon cls
dimitris's avatar
dimitris committed
222

223 224 225 226
{- Note [The superclass story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to add superclass constraints for two reasons:

227
* For givens [G], they give us a route to proof.  E.g.
228 229 230 231 232
    f :: Ord a => a -> Bool
    f x = x == x
  We get a Wanted (Eq a), which can only be solved from the superclass
  of the Given (Ord a).

233 234
* For wanteds [W], and deriveds [WD], [D], they may give useful
  functional dependencies.  E.g.
235 236
     class C a b | a -> b where ...
     class C a b => D a b where ...
237
  Now a [W] constraint (D Int beta) has (C Int beta) as a superclass
238
  and that might tell us about beta, via C's fundeps.  We can get this
239
  by generating a [D] (C Int beta) constraint.  It's derived because
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  we don't actually have to cough up any evidence for it; it's only there
  to generate fundep equalities.

See Note [Why adding superclasses can help].

For these reasons we want to generate superclass constraints for both
Givens and Wanteds. But:

* (Minor) they are often not needed, so generating them aggressively
  is a waste of time.

* (Major) if we want recursive superclasses, there would be an infinite
  number of them.  Here is a real-life example (Trac #10318);

     class (Frac (Frac a) ~ Frac a,
            Fractional (Frac a),
            IntegralDomain (Frac a))
         => IntegralDomain a where
      type Frac a :: *

  Notice that IntegralDomain has an associated type Frac, and one
  of IntegralDomain's superclasses is another IntegralDomain constraint.

So here's the plan:

265 266
1. Eagerly generate superclasses for given (but not wanted)
   constraints; see Note [Eagerly expand given superclasses].
267 268
   This is done using mkStrictSuperClasses in canClassNC, when
   we take a non-canonical Given constraint and cannonicalise it.
269 270

   However stop if you encounter the same class twice.  That is,
271 272
   mkStrictSuperClasses expands eagerly, but has a conservative
   termination condition: see Note [Expanding superclasses] in TcType.
273

274 275 276 277
2. Solve the wanteds as usual, but do no further expansion of
   superclasses for canonical CDictCans in solveSimpleGivens or
   solveSimpleWanteds; Note [Danger of adding superclasses during solving]

278 279
   However, /do/ continue to eagerly expand superlasses for new /given/
   /non-canonical/ constraints (canClassNC does this).  As Trac #12175
280 281 282
   showed, a type-family application can expand to a class constraint,
   and we want to see its superclasses for just the same reason as
   Note [Eagerly expand given superclasses].
283

284 285 286
3. If we have any remaining unsolved wanteds
        (see Note [When superclasses help] in TcRnTypes)
   try harder: take both the Givens and Wanteds, and expand
287 288 289 290 291
   superclasses again.  See the calls to expandSuperClasses in
   TcSimplify.simpl_loop and solveWanteds.

   This may succeed in generating (a finite number of) extra Givens,
   and extra Deriveds. Both may help the proof.
292

293 294 295 296 297 298 299 300 301
3a An important wrinkle: only expand Givens from the current level.
   Two reasons:
      - We only want to expand it once, and that is best done at
        the level it is bound, rather than repeatedly at the leaves
        of the implication tree
      - We may be inside a type where we can't create term-level
        evidence anyway, so we can't superclass-expand, say,
        (a ~ b) to get (a ~# b).  This happened in Trac #15290.

302 303 304
4. Go round to (2) again.  This loop (2,3,4) is implemented
   in TcSimplify.simpl_loop.

305 306 307
The cc_pend_sc flag in a CDictCan records whether the superclasses of
this constraint have been expanded.  Specifically, in Step 3 we only
expand superclasses for constraints with cc_pend_sc set to true (i.e.
308 309
isPendingScDict holds).

310 311 312 313 314 315 316 317 318
Why do we do this?  Two reasons:

* To avoid repeated work, by repeatedly expanding the superclasses of
  same constraint,

* To terminate the above loop, at least in the -XNoRecursiveSuperClasses
  case.  If there are recursive superclasses we could, in principle,
  expand forever, always encountering new constraints.

319 320 321
When we take a CNonCanonical or CIrredCan, but end up classifying it
as a CDictCan, we set the cc_pend_sc flag to False.

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
Note [Superclass loops]
~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
  class C a => D a
  class D a => C a

Then, when we expand superclasses, we'll get back to the self-same
predicate, so we have reached a fixpoint in expansion and there is no
point in fruitlessly expanding further.  This case just falls out from
our strategy.  Consider
  f :: C a => a -> Bool
  f x = x==x
Then canClassNC gets the [G] d1: C a constraint, and eager emits superclasses
G] d2: D a, [G] d3: C a (psc).  (The "psc" means it has its sc_pend flag set.)
When processing d3 we find a match with d1 in the inert set, and we always
keep the inert item (d1) if possible: see Note [Replacement vs keeping] in
TcInteract.  So d3 dies a quick, happy death.

340 341 342
Note [Eagerly expand given superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In step (1) of Note [The superclass story], why do we eagerly expand
343 344 345 346
Given superclasses by one layer?  (By "one layer" we mean expand transitively
until you meet the same class again -- the conservative criterion embodied
in expandSuperClasses.  So a "layer" might be a whole stack of superclasses.)
We do this eagerly for Givens mainly because of some very obscure
347
cases like this:
348 349 350 351 352 353 354 355 356 357 358

   instance Bad a => Eq (T a)

   f :: (Ord (T a)) => blah
   f x = ....needs Eq (T a), Ord (T a)....

Here if we can't satisfy (Eq (T a)) from the givens we'll use the
instance declaration; but then we are stuck with (Bad a).  Sigh.
This is really a case of non-confluent proofs, but to stop our users
complaining we expand one layer in advance.

359 360 361 362 363 364 365 366 367 368 369 370 371
Note [Instance and Given overlap] in TcInteract.

We also want to do this if we have

   f :: F (T a) => blah

where
   type instance F (T a) = Ord (T a)

So we may need to do a little work on the givens to expose the
class that has the superclasses.  That's why the superclass
expansion for Givens happens in canClassNC.

372 373 374
Note [Why adding superclasses can help]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Examples of how adding superclasses can help:
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    --- Example 1
        class C a b | a -> b
    Suppose we want to solve
         [G] C a b
         [W] C a beta
    Then adding [D] beta~b will let us solve it.

    -- Example 2 (similar but using a type-equality superclass)
        class (F a ~ b) => C a b
    And try to sllve:
         [G] C a b
         [W] C a beta
    Follow the superclass rules to add
         [G] F a ~ b
         [D] F a ~ beta
391
    Now we get [D] beta ~ b, and can solve that.
392

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    -- Example (tcfail138)
      class L a b | a -> b
      class (G a, L a b) => C a b

      instance C a b' => G (Maybe a)
      instance C a b  => C (Maybe a) a
      instance L (Maybe a) a

    When solving the superclasses of the (C (Maybe a) a) instance, we get
      [G] C a b, and hance by superclasses, [G] G a, [G] L a b
      [W] G (Maybe a)
    Use the instance decl to get
      [W] C a beta
    Generate its derived superclass
      [D] L a beta.  Now using fundeps, combine with [G] L a b to get
      [D] beta ~ b
    which is what we want.

411 412
Note [Danger of adding superclasses during solving]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
413
Here's a serious, but now out-dated example, from Trac #4497:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
414

415 416 417
   class Num (RealOf t) => Normed t
   type family RealOf x

Simon Peyton Jones's avatar
Simon Peyton Jones committed
418
Assume the generated wanted constraint is:
419 420 421
   [W] RealOf e ~ e
   [W] Normed e

Simon Peyton Jones's avatar
Simon Peyton Jones committed
422
If we were to be adding the superclasses during simplification we'd get:
423 424 425 426
   [W] RealOf e ~ e
   [W] Normed e
   [D] RealOf e ~ fuv
   [D] Num fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
427
==>
428
   e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
429

430 431 432
While looks exactly like our original constraint. If we add the
superclass of (Normed fuv) again we'd loop.  By adding superclasses
definitely only once, during canonicalisation, this situation can't
433
happen.
434 435 436 437

Mind you, now that Wanteds cannot rewrite Derived, I think this particular
situation can't happen.
  -}
438

439 440 441 442
makeSuperClasses :: [Ct] -> TcS [Ct]
-- Returns strict superclasses, transitively, see Note [The superclasses story]
-- See Note [The superclass story]
-- The loop-breaking here follows Note [Expanding superclasses] in TcType
443 444 445 446 447 448 449 450 451 452
-- Specifically, for an incoming (C t) constraint, we return all of (C t)'s
--    superclasses, up to /and including/ the first repetition of C
--
-- Example:  class D a => C a
--           class C [a] => D a
-- makeSuperClasses (C x) will return (D x, C [x])
--
-- NB: the incoming constraints have had their cc_pend_sc flag already
--     flipped to False, by isPendingScDict, so we are /obliged/ to at
--     least produce the immediate superclasses
453 454 455
makeSuperClasses cts = concatMapM go cts
  where
    go (CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys })
456 457 458 459 460 461 462
      = mkStrictSuperClasses ev [] [] cls tys
    go (CQuantCan (QCI { qci_pred = pred, qci_ev = ev }))
      = ASSERT2( isClassPred pred, ppr pred )  -- The cts should all have
                                               -- class pred heads
        mkStrictSuperClasses ev tvs theta cls tys
      where
        (tvs, theta, cls, tys) = tcSplitDFunTy (ctEvPred ev)
463 464
    go ct = pprPanic "makeSuperClasses" (ppr ct)

465 466 467 468 469 470 471 472 473 474 475 476 477 478
mkStrictSuperClasses
    :: CtEvidence
    -> [TyVar] -> ThetaType  -- These two args are non-empty only when taking
                             -- superclasses of a /quantified/ constraint
    -> Class -> [Type] -> TcS [Ct]
-- Return constraints for the strict superclasses of
--   ev :: forall as. theta => cls tys
mkStrictSuperClasses ev tvs theta cls tys
  = mk_strict_superclasses (unitNameSet (className cls))
                           ev tvs theta cls tys

mk_strict_superclasses :: NameSet -> CtEvidence
                       -> [TyVar] -> ThetaType
                       -> Class -> [Type] -> TcS [Ct]
479 480 481
-- Always return the immediate superclasses of (cls tys);
-- and expand their superclasses, provided none of them are in rec_clss
-- nor are repeated
482
mk_strict_superclasses rec_clss ev tvs theta cls tys
483
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
484 485 486 487 488
  = concatMapM (do_one_given evar (mk_given_loc loc)) $
    classSCSelIds cls
  where
    dict_ids  = mkTemplateLocals theta
    size      = sizeTypes tys
dimitris's avatar
dimitris committed
489

490
    do_one_given evar given_loc sel_id
491 492 493 494 495 496 497 498 499 500 501 502 503
      | not (null tvs)
      , null theta
      , isUnliftedType sc_pred
      -- Very special case for equality
      -- See Note [Equality superclasses in quantified constraints]
      = do { empty_ctuple_cls <- tcLookupClass (cTupleTyConName 0)
           ; let theta1    = [mkClassPred empty_ctuple_cls []]
                 dict_ids1 = mkTemplateLocals theta1
           ; given_ev <- new_given theta1 dict_ids1 []
           ; return [mkNonCanonical given_ev] }

      | otherwise  -- Normal case
      = do { given_ev <- new_given theta dict_ids dict_ids
504 505
           ; mk_superclasses rec_clss given_ev tvs theta sc_pred }

506 507 508 509 510 511 512 513 514 515
      where
        sc_pred = funResultTy (piResultTys (idType sel_id) tys)

        new_given theta_abs dict_ids_abs dict_ids_app
          = newGivenEvVar given_loc (given_ty, given_ev)
          where
            given_ty = mkInfSigmaTy tvs theta_abs sc_pred
            given_ev = EvExpr $ mkLams tvs $ mkLams dict_ids_abs $
                       Var sel_id `mkTyApps` tys `App`
                       (evId evar `mkTyApps` mkTyVarTys tvs `mkVarApps` dict_ids_app)
516

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    mk_given_loc loc
       | isCTupleClass cls
       = loc   -- For tuple predicates, just take them apart, without
               -- adding their (large) size into the chain.  When we
               -- get down to a base predicate, we'll include its size.
               -- Trac #10335

       | GivenOrigin skol_info <- ctLocOrigin loc
         -- See Note [Solving superclass constraints] in TcInstDcls
         -- for explantation of this transformation for givens
       = case skol_info of
            InstSkol -> loc { ctl_origin = GivenOrigin (InstSC size) }
            InstSC n -> loc { ctl_origin = GivenOrigin (InstSC (n `max` size)) }
            _        -> loc

       | otherwise  -- Probably doesn't happen, since this function
       = loc        -- is only used for Givens, but does no harm
534

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
mk_strict_superclasses rec_clss ev tvs theta cls tys
  | all noFreeVarsOfType tys
  = return [] -- Wanteds with no variables yield no deriveds.
              -- See Note [Improvement from Ground Wanteds]

  | otherwise -- Wanted/Derived case, just add Derived superclasses
              -- that can lead to improvement.
  = ASSERT2( null tvs && null theta, ppr tvs $$ ppr theta )
    concatMapM do_one_derived (immSuperClasses cls tys)
  where
    loc = ctEvLoc ev

    do_one_derived sc_pred
      = do { sc_ev <- newDerivedNC loc sc_pred
           ; mk_superclasses rec_clss sc_ev [] [] sc_pred }

mk_superclasses :: NameSet -> CtEvidence
                -> [TyVar] -> ThetaType -> PredType -> TcS [Ct]
-- Return this constraint, plus its superclasses, if any
mk_superclasses rec_clss ev tvs theta pred
  | ClassPred cls tys <- classifyPredType pred
  = mk_superclasses_of rec_clss ev tvs theta cls tys

  | otherwise   -- Superclass is not a class predicate
  = return [mkNonCanonical ev]

mk_superclasses_of :: NameSet -> CtEvidence
                   -> [TyVar] -> ThetaType -> Class -> [Type]
                   -> TcS [Ct]
-- Always return this class constraint,
-- and expand its superclasses
mk_superclasses_of rec_clss ev tvs theta cls tys
  | loop_found = do { traceTcS "mk_superclasses_of: loop" (ppr cls <+> ppr tys)
                    ; return [this_ct] }  -- cc_pend_sc of this_ct = True
  | otherwise  = do { traceTcS "mk_superclasses_of" (vcat [ ppr cls <+> ppr tys
                                                          , ppr (isCTupleClass cls)
                                                          , ppr rec_clss
                                                          ])
                    ; sc_cts <- mk_strict_superclasses rec_clss' ev tvs theta cls tys
                    ; return (this_ct : sc_cts) }
                                   -- cc_pend_sc of this_ct = False
  where
    cls_nm     = className cls
    loop_found = not (isCTupleClass cls) && cls_nm `elemNameSet` rec_clss
                 -- Tuples never contribute to recursion, and can be nested
    rec_clss'  = rec_clss `extendNameSet` cls_nm

    this_ct | null tvs, null theta
            = CDictCan { cc_ev = ev, cc_class = cls, cc_tyargs = tys
                       , cc_pend_sc = loop_found }
                 -- NB: If there is a loop, we cut off, so we have not
                 --     added the superclasses, hence cc_pend_sc = True
            | otherwise
            = CQuantCan (QCI { qci_tvs = tvs, qci_pred = mkClassPred cls tys
                             , qci_ev = ev
                             , qci_pend_sc = loop_found })

592

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
{- Note [Equality superclasses in quantified constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (Trac #15359, #15593, #15625)
  f :: (forall a. theta => a ~ b) => stuff

It's a bit odd to have a local, quantified constraint for `(a~b)`,
but some people want such a thing (see the tickets). And for
Coercible it is definitely useful
  f :: forall m. (forall p q. Coercible p q => Coercible (m p) (m q)))
                 => stuff

Moreover it's not hard to arrange; we just need to look up /equality/
constraints in the quantified-constraint environment, which we do in
TcInteract.doTopReactOther.

There is a wrinkle though, in the case where 'theta' is empty, so
we have
  f :: (forall a. a~b) => stuff

Now the superclass machinery kicks in, in makeSuperClasses,
giving us a a second quantified constrait
       (forall a. a ~# b)
BUT this is an unboxed value!  And nothing has prepared us for
dictionary "functions" that are unboxed.  Actually it does just
about work, but the simplier ends up with stuff like
   case (/\a. eq_sel d) of df -> ...(df @Int)...
and fails to simplify that any further.

It seems eaiser to give such unboxed quantifed constraints a
dummmy () argument, thus
      (forall a. (% %) => a ~# b)
where (% %) is the empty constraint tuple.  That makes everything
be nicely boxed.

(One might wonder about using void# instead, but this seems more
uniform -- it's a constraint argument -- and I'm not worried about
the last drop of efficiency for this very rare case.)


Austin Seipp's avatar
Austin Seipp committed
632 633 634 635 636 637
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
638

639
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
640
-- Precondition: ty not a tuple and no other evidence form
641
canIrred ev
642 643
  = do { let pred = ctEvPred ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr pred)
644 645
       ; (xi,co) <- flatten FM_FlattenAll ev pred -- co :: xi ~ pred
       ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
646 647
    do { -- Re-classify, in case flattening has improved its shape
       ; case classifyPredType (ctEvPred new_ev) of
648 649 650
           ClassPred cls tys     -> canClassNC new_ev cls tys
           EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
           _                     -> continueWith $
651
                                    mkIrredCt new_ev } }
652

653 654
canHole :: CtEvidence -> Hole -> TcS (StopOrContinue Ct)
canHole ev hole
655 656
  = do { let pred = ctEvPred ev
       ; (xi,co) <- flatten FM_SubstOnly ev pred -- co :: xi ~ pred
657
       ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
658 659
    do { updInertIrreds (`snocCts` (CHoleCan { cc_ev = new_ev
                                             , cc_hole = hole }))
660
       ; stopWith new_ev "Emit insoluble hole" } }
661

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816

{- *********************************************************************
*                                                                      *
*                      Quantified predicates
*                                                                      *
********************************************************************* -}

{- Note [Quantified constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The -XQuantifiedConstraints extension allows type-class contexts like this:

  data Rose f x = Rose x (f (Rose f x))

  instance (Eq a, forall b. Eq b => Eq (f b))
        => Eq (Rose f a)  where
    (Rose x1 rs1) == (Rose x2 rs2) = x1==x2 && rs1 == rs2

Note the (forall b. Eq b => Eq (f b)) in the instance contexts.
This quantified constraint is needed to solve the
 [W] (Eq (f (Rose f x)))
constraint which arises form the (==) definition.

The wiki page is
  https://ghc.haskell.org/trac/ghc/wiki/QuantifiedConstraints
which in turn contains a link to the GHC Proposal where the change
is specified, and a Haskell Symposium paper about it.

We implement two main extensions to the design in the paper:

 1. We allow a variable in the instance head, e.g.
      f :: forall m a. (forall b. m b) => D (m a)
    Notice the 'm' in the head of the quantified constraint, not
    a class.

 2. We suport superclasses to quantified constraints.
    For example (contrived):
      f :: (Ord b, forall b. Ord b => Ord (m b)) => m a -> m a -> Bool
      f x y = x==y
    Here we need (Eq (m a)); but the quantifed constraint deals only
    with Ord.  But we can make it work by using its superclass.

Here are the moving parts
  * Language extension {-# LANGUAGE QuantifiedConstraints #-}
    and add it to ghc-boot-th:GHC.LanguageExtensions.Type.Extension

  * A new form of evidence, EvDFun, that is used to discharge
    such wanted constraints

  * checkValidType gets some changes to accept forall-constraints
    only in the right places.

  * Type.PredTree gets a new constructor ForAllPred, and
    and classifyPredType analyses a PredType to decompose
    the new forall-constraints

  * TcSMonad.InertCans gets an extra field, inert_insts,
    which holds all the Given forall-constraints.  In effect,
    such Given constraints are like local instance decls.

  * When trying to solve a class constraint, via
    TcInteract.matchInstEnv, use the InstEnv from inert_insts
    so that we include the local Given forall-constraints
    in the lookup.  (See TcSMonad.getInstEnvs.)

  * TcCanonical.canForAll deals with solving a
    forall-constraint.  See
       Note [Solving a Wanted forall-constraint]

  * We augment the kick-out code to kick out an inert
    forall constraint if it can be rewritten by a new
    type equality; see TcSMonad.kick_out_rewritable

Note that a quantified constraint is never /inferred/
(by TcSimplify.simplifyInfer).  A function can only have a
quantified constraint in its type if it is given an explicit
type signature.

Note that we implement
-}

canForAll :: CtEvidence -> Bool -> TcS (StopOrContinue Ct)
-- We have a constraint (forall as. blah => C tys)
canForAll ev pend_sc
  = do { -- First rewrite it to apply the current substitution
         -- Do not bother with type-family reductions; we can't
         -- do them under a forall anyway (c.f. Flatten.flatten_one
         -- on a forall type)
         let pred = ctEvPred ev
       ; (xi,co) <- flatten FM_SubstOnly ev pred -- co :: xi ~ pred
       ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->

    do { -- Now decompose into its pieces and solve it
         -- (It takes a lot less code to flatten before decomposing.)
       ; case classifyPredType (ctEvPred new_ev) of
           ForAllPred tv_bndrs theta pred
              -> solveForAll new_ev tv_bndrs theta pred pend_sc
           _  -> pprPanic "canForAll" (ppr new_ev)
    } }

solveForAll :: CtEvidence -> [TyVarBinder] -> TcThetaType -> PredType -> Bool
            -> TcS (StopOrContinue Ct)
solveForAll ev tv_bndrs theta pred pend_sc
  | CtWanted { ctev_dest = dest } <- ev
  = -- See Note [Solving a Wanted forall-constraint]
    do { let skol_info = QuantCtxtSkol
             empty_subst = mkEmptyTCvSubst $ mkInScopeSet $
                           tyCoVarsOfTypes (pred:theta) `delVarSetList` tvs
       ; (subst, skol_tvs) <- tcInstSkolTyVarsX empty_subst tvs
       ; given_ev_vars <- mapM newEvVar (substTheta subst theta)

       ; (w_id, ev_binds)
             <- checkConstraintsTcS skol_info skol_tvs given_ev_vars $
                do { wanted_ev <- newWantedEvVarNC loc $
                                  substTy subst pred
                   ; return ( ctEvEvId wanted_ev
                            , unitBag (mkNonCanonical wanted_ev)) }

      ; setWantedEvTerm dest $
        EvFun { et_tvs = skol_tvs, et_given = given_ev_vars
              , et_binds = ev_binds, et_body = w_id }

      ; stopWith ev "Wanted forall-constraint" }

  | isGiven ev   -- See Note [Solving a Given forall-constraint]
  = do { addInertForAll qci
       ; stopWith ev "Given forall-constraint" }

  | otherwise
  = stopWith ev "Derived forall-constraint"
  where
    loc = ctEvLoc ev
    tvs = binderVars tv_bndrs
    qci = QCI { qci_ev = ev, qci_tvs = tvs
              , qci_pred = pred, qci_pend_sc = pend_sc }

{- Note [Solving a Wanted forall-constraint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Solving a wanted forall (quantified) constraint
  [W] df :: forall ab. (Eq a, Ord b) => C x a b
is delightfully easy.   Just build an implication constraint
    forall ab. (g1::Eq a, g2::Ord b) => [W] d :: C x a
and discharge df thus:
    df = /\ab. \g1 g2. let <binds> in d
where <binds> is filled in by solving the implication constraint.
All the machinery is to hand; there is little to do.

Note [Solving a Given forall-constraint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For a Given constraint
  [G] df :: forall ab. (Eq a, Ord b) => C x a b
we just add it to TcS's local InstEnv of known instances,
via addInertForall.  Then, if we look up (C x Int Bool), say,
we'll find a match in the InstEnv.


Austin Seipp's avatar
Austin Seipp committed
817 818 819 820 821
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
822 823 824 825 826 827 828 829 830 831 832 833 834

Note [Canonicalising equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to canonicalise an equality, we look at the structure of the
two types at hand, looking for similarities. A difficulty is that the
types may look dissimilar before flattening but similar after flattening.
However, we don't just want to jump in and flatten right away, because
this might be wasted effort. So, after looking for similarities and failing,
we flatten and then try again. Of course, we don't want to loop, so we
track whether or not we've already flattened.

It is conceivable to do a better job at tracking whether or not a type
is flattened, but this is left as future work. (Mar '15)
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853


Note [FunTy and decomposing tycon applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When can_eq_nc' attempts to decompose a tycon application we haven't yet zonked.
This means that we may very well have a FunTy containing a type of some unknown
kind. For instance, we may have,

    FunTy (a :: k) Int

Where k is a unification variable. tcRepSplitTyConApp_maybe panics in the event
that it sees such a type as it cannot determine the RuntimeReps which the (->)
is applied to. Consequently, it is vital that we instead use
tcRepSplitTyConApp_maybe', which simply returns Nothing in such a case.

When this happens can_eq_nc' will fail to decompose, zonk, and try again.
Zonking should fill the variable k, meaning that decomposition will succeed the
second time around.
Austin Seipp's avatar
Austin Seipp committed
854
-}
855

856 857
canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
canEqNC ev eq_rel ty1 ty2
858 859 860 861
  = do { result <- zonk_eq_types ty1 ty2
       ; case result of
           Left (Pair ty1' ty2') -> can_eq_nc False ev eq_rel ty1' ty1 ty2' ty2
           Right ty              -> canEqReflexive ev eq_rel ty }
862

863
can_eq_nc
864 865
   :: Bool            -- True => both types are flat
   -> CtEvidence
866
   -> EqRel
Austin Seipp's avatar
Austin Seipp committed
867 868
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
869
   -> TcS (StopOrContinue Ct)
870
can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
Austin Seipp's avatar
Austin Seipp committed
871
  = do { traceTcS "can_eq_nc" $
872
         vcat [ ppr flat, ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
873 874
       ; rdr_env <- getGlobalRdrEnvTcS
       ; fam_insts <- getFamInstEnvs
875
       ; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
876 877

can_eq_nc'
878 879
   :: Bool           -- True => both input types are flattened
   -> GlobalRdrEnv   -- needed to see which newtypes are in scope
880 881 882 883 884 885
   -> FamInstEnvs    -- needed to unwrap data instances
   -> CtEvidence
   -> EqRel
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
   -> TcS (StopOrContinue Ct)
886 887

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
888
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
Ben Gamari's avatar
Ben Gamari committed
889 890
  | Just ty1' <- tcView ty1 = can_eq_nc flat ev eq_rel ty1' ps_ty1 ty2  ps_ty2
  | Just ty2' <- tcView ty2 = can_eq_nc flat ev eq_rel ty1  ps_ty1 ty2' ps_ty2
891 892

-- need to check for reflexivity in the ReprEq case.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
893
-- See Note [Eager reflexivity check]
894 895 896
-- Check only when flat because the zonk_eq_types check in canEqNC takes
-- care of the non-flat case.
can_eq_nc' True _rdr_env _envs ev ReprEq ty1 _ ty2 _
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
897
  | ty1 `tcEqType` ty2
898 899 900
  = canEqReflexive ev ReprEq ty1

-- When working with ReprEq, unwrap newtypes.
901 902 903 904
-- See Note [Unwrap newtypes first]
can_eq_nc' _flat rdr_env envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
  | ReprEq <- eq_rel
  , Just stuff1 <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
905
  = can_eq_newtype_nc ev NotSwapped ty1 stuff1 ty2 ps_ty2
906 907 908

  | ReprEq <- eq_rel
  , Just stuff2 <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
909
  = can_eq_newtype_nc ev IsSwapped  ty2 stuff2 ty1 ps_ty1
910

911 912 913 914 915 916
-- Then, get rid of casts
can_eq_nc' flat _rdr_env _envs ev eq_rel (CastTy ty1 co1) _ ty2 ps_ty2
  = canEqCast flat ev eq_rel NotSwapped ty1 co1 ty2 ps_ty2
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 (CastTy ty2 co2) _
  = canEqCast flat ev eq_rel IsSwapped ty2 co2 ty1 ps_ty1

917 918 919 920 921 922 923
-- NB: pattern match on True: we want only flat types sent to canEqTyVar.
-- See also Note [No top-level newtypes on RHS of representational equalities]
can_eq_nc' True _rdr_env _envs ev eq_rel (TyVarTy tv1) ps_ty1 ty2 ps_ty2
  = canEqTyVar ev eq_rel NotSwapped tv1 ps_ty1 ty2 ps_ty2
can_eq_nc' True _rdr_env _envs ev eq_rel ty1 ps_ty1 (TyVarTy tv2) ps_ty2
  = canEqTyVar ev eq_rel IsSwapped tv2 ps_ty2 ty1 ps_ty1

924 925 926 927 928
----------------------
-- Otherwise try to decompose
----------------------

-- Literals
929
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
930
 | l1 == l2
931
  = do { setEvBindIfWanted ev (evCoercion $ mkReflCo (eqRelRole eq_rel) ty1)
932
       ; stopWith ev "Equal LitTy" }
933

Simon Peyton Jones's avatar
Simon Peyton Jones committed
934 935
-- Try to decompose type constructor applications
-- Including FunTy (s -> t)
936
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1 _ ty2 _
937 938 939
    --- See Note [FunTy and decomposing type constructor applications].
  | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe' ty1
  , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe' ty2
940 941
  , not (isTypeFamilyTyCon tc1)
  , not (isTypeFamilyTyCon tc2)
942
  = canTyConApp ev eq_rel tc1 tys1 tc2 tys2
943

944
can_eq_nc' _flat _rdr_env _envs ev eq_rel
945
           s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
946
  = can_eq_nc_forall ev eq_rel s1 s2
947

948
-- See Note [Canonicalising type applications] about why we require flat types
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
949
can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
950 951 952
  | NomEq <- eq_rel
  , Just (t2, s2) <- tcSplitAppTy_maybe ty2
  = can_eq_app ev t1 s1 t2 s2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
953
can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
954 955 956
  | NomEq <- eq_rel
  , Just (t1, s1) <- tcSplitAppTy_maybe ty1
  = can_eq_app ev t1 s1 t2 s2
957

958
-- No similarity in type structure detected. Flatten and try again.
959 960 961
can_eq_nc' False rdr_env envs ev eq_rel _ ps_ty1 _ ps_ty2
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ps_ty1
       ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2
962 963
       ; new_ev <- rewriteEqEvidence ev NotSwapped xi1 xi2 co1 co2
       ; can_eq_nc' True rdr_env envs new_ev eq_rel xi1 xi1 xi2 xi2 }
964 965

-- We've flattened and the types don't match. Give up.
966
can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 _ ps_ty2
967
  = do { traceTcS "can_eq_nc' catch-all case" (ppr ps_ty1 $$ ppr ps_ty2)
968 969 970 971 972 973 974 975 976 977 978 979 980 981
       ; case eq_rel of -- See Note [Unsolved equalities]
            ReprEq -> continueWith (mkIrredCt ev)
            NomEq  -> continueWith (mkInsolubleCt ev) }
          -- No need to call canEqFailure/canEqHardFailure because they
          -- flatten, and the types involved here are already flat

{- Note [Unsolved equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have an unsolved equality like
  (a b ~R# Int)
that is not necessarily insoluble!  Maybe 'a' will turn out to be a newtype.
So we want to make it a potentially-soluble Irred not an insoluble one.
Missing this point is what caused Trac #15431
-}
982

983 984 985 986 987 988 989 990 991 992 993 994 995 996
---------------------------------
can_eq_nc_forall :: CtEvidence -> EqRel
                 -> Type -> Type    -- LHS and RHS
                 -> TcS (StopOrContinue Ct)
-- (forall as. phi1) ~ (forall bs. phi2)
-- Check for length match of as, bs
-- Then build an implication constraint: forall as. phi1 ~ phi2[as/bs]
-- But remember also to unify the kinds of as and bs
--  (this is the 'go' loop), and actually substitute phi2[as |> cos / bs]
-- Remember also that we might have forall z (a:z). blah
--  so we must proceed one binder at a time (Trac #13879)

can_eq_nc_forall ev eq_rel s1 s2
 | CtWanted { ctev_loc = loc, ctev_dest = orig_dest } <- ev
997
 = do { let free_tvs       = tyCoVarsOfTypes [s1,s2]
Ningning Xie's avatar
Ningning Xie committed
998 999
            (bndrs1, phi1) = tcSplitForAllVarBndrs s1
            (bndrs2, phi2) = tcSplitForAllVarBndrs s2
1000 1001 1002 1003 1004 1005 1006 1007
      ; if not (equalLength bndrs1 bndrs2)
        then do { traceTcS "Forall failure" $
                     vcat [ ppr s1, ppr s2, ppr bndrs1, ppr bndrs2
                          , ppr (map binderArgFlag bndrs1)
                          , ppr (map binderArgFlag bndrs2) ]
                ; canEqHardFailure ev s1 s2 }
        else
   do { traceTcS "Creating implication for polytype equality" $ ppr ev
1008
      ; let empty_subst1 = mkEmptyTCvSubst $ mkInScopeSet free_tvs
1009 1010 1011 1012 1013 1014 1015
      ; (subst1, skol_tvs) <- tcInstSkolTyVarsX empty_subst1 $
                              binderVars bndrs1

      ; let skol_info = UnifyForAllSkol phi1
            phi1' = substTy subst1 phi1

            -- Unify the kinds, extend the substitution
1016 1017
            go :: [TcTyVar] -> TCvSubst -> [TyVarBinder]
               -> TcS (TcCoercion, Cts)
1018 1019
            go (skol_tv:skol_tvs) subst (bndr2:bndrs2)
              = do { let tv2 = binderVar bndr2
1020 1021
                   ; (kind_co, wanteds1) <- unify loc Nominal (tyVarKind skol_tv)
                                                  (substTy subst (tyVarKind tv2))
1022 1023
                   ; let subst' = extendTvSubst subst tv2
                                       (mkCastTy (mkTyVarTy skol_tv) kind_co)
1024 1025 1026
                   ; (co, wanteds2) <- go skol_tvs subst' bndrs2
                   ; return ( mkTcForAllCo skol_tv kind_co co
                            , wanteds1 `unionBags` wanteds2 ) }
1027 1028 1029 1030

            -- Done: unify phi1 ~ phi2
            go [] subst bndrs2
              = ASSERT( null bndrs2 )
1031
                unify loc (eqRelRole eq_rel) phi1' (substTy subst phi2)
1032 1033 1034

            go _ _ _ = panic "cna_eq_nc_forall"  -- case (s:ss) []

1035
            empty_subst2 = mkEmptyTCvSubst (getTCvInScope subst1)
1036

1037
      ; all_co <- checkTvConstraintsTcS skol_info skol_tvs $
1038 1039
                  go skol_tvs empty_subst2 bndrs2

1040 1041 1042 1043 1044 1045 1046 1047
      ; setWantedEq orig_dest all_co
      ; stopWith ev "Deferred polytype equality" } }

 | otherwise
 = do { traceTcS "Omitting decomposition of given polytype equality" $
        pprEq s1 s2    -- See Note [Do not decompose given polytype equalities]
      ; stopWith ev "Discard given polytype equality" }

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
 where
    unify :: CtLoc -> Role -> TcType -> TcType -> TcS (TcCoercion, Cts)
    -- This version returns the wanted constraint rather
    -- than putting it in the work list
    unify loc role ty1 ty2
      | ty1 `tcEqType` ty2
      = return (mkTcReflCo role ty1, emptyBag)
      | otherwise
      = do { (wanted, co) <- newWantedEq loc role ty1 ty2
           ; return (co, unitBag (mkNonCanonical wanted)) }

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
---------------------------------
-- | Compare types for equality, while zonking as necessary. Gives up
-- as soon as it finds that two types are not equal.
-- This is quite handy when some unification has made two
-- types in an inert wanted to be equal. We can discover the equality without
-- flattening, which is sometimes very expensive (in the case of type functions).
-- In particular, this function makes a ~20% improvement in test case
-- perf/compiler/T5030.
--
-- Returns either the (partially zonked) types in the case of
-- inequality, or the one type in the case of equality. canEqReflexive is
-- a good next step in the 'Right' case. Returning 'Left' is always safe.
--
-- NB: This does *not* look through type synonyms. In fact, it treats type
-- synonyms as rigid constructors. In the future, it might be convenient
-- to look at only those arguments of type synonyms that actually appear
-- in the synonym RHS. But we're not there yet.
zonk_eq_types :: TcType -> TcType -> TcS (Either (Pair TcType) TcType)
zonk_eq_types = go
  where
    go (TyVarTy tv1) (TyVarTy tv2) = tyvar_tyvar tv1 tv2
    go (TyVarTy tv1) ty2           = tyvar NotSwapped tv1 ty2
    go ty1 (TyVarTy tv2)           = tyvar IsSwapped  tv2 ty1

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    -- We handle FunTys explicitly here despite the fact that they could also be
    -- treated as an application. Why? Well, for one it's cheaper to just look
    -- at two types (the argument and result types) than four (the argument,
    -- result, and their RuntimeReps). Also, we haven't completely zonked yet,
    -- so we may run into an unzonked type variable while trying to compute the
    -- RuntimeReps of the argument and result types. This can be observed in
    -- testcase tc269.
    go ty1 ty2
      | Just (arg1, res1) <- split1
      , Just (arg2, res2) <- split2
      = do { res_a <- go arg1 arg2
           ; res_b <- go res1 res2
           ; return $ combine_rev mkFunTy res_b res_a
           }
      | isJust split1 || isJust split2
      = bale_out ty1 ty2
      where
        split1 = tcSplitFunTy_maybe ty1
        split2 = tcSplitFunTy_maybe ty2

1103 1104 1105
    go ty1 ty2
      | Just (tc1, tys1) <- tcRepSplitTyConApp_maybe ty1
      , Just (tc2, tys2) <- tcRepSplitTyConApp_maybe ty2
1106 1107 1108 1109 1110 1111 1112 1113 1114
      = if tc1 == tc2 && tys1 `equalLength` tys2
          -- Crucial to check for equal-length args, because
          -- we cannot assume that the two args to 'go' have
          -- the same kind.  E.g go (Proxy *      (Maybe Int))
          --                        (Proxy (*->*) Maybe)
          -- We'll call (go (Maybe Int) Maybe)
          -- See Trac #13083
        then tycon tc1 tys1 tys2
        else bale_out ty1 ty2
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

    go ty1 ty2
      | Just (ty1a, ty1b) <- tcRepSplitAppTy_maybe ty1
      , Just (ty2a, ty2b) <- tcRepSplitAppTy_maybe ty2
      = do { res_a <- go ty1a ty2a
           ; res_b <- go ty1b ty2b
           ; return $ combine_rev mkAppTy res_b res_a }

    go ty1@(LitTy lit1) (LitTy lit2)
      | lit1 == lit2
      = return (Right ty1)

1127 1128 1129 1130
    go ty1 ty2 = bale_out ty1 ty2
      -- We don't handle more complex forms here

    bale_out ty1 ty2 = return $ Left (Pair ty1 ty2)
1131 1132 1133

    tyvar :: SwapFlag -> TcTyVar -> TcType
          -> TcS (Either (Pair TcType) TcType)
1134
      -- Try to do as little as possible, as anything we do here is redundant
1135 1136 1137 1138 1139 1140 1141 1142
      -- with flattening. In particular, no need to zonk kinds. That's why
      -- we don't use the already-defined zonking functions
    tyvar swapped tv ty
      = case tcTyVarDetails tv of
          MetaTv { mtv_ref = ref }
            -> do { cts <- readTcRef ref
                  ; case cts of
                      Flexi        -> give_up
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1143 1144
                      Indirect ty' -> do { trace_indirect tv ty'
                                         ; unSwap swapped go ty' ty } }
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
          _ -> give_up
      where
        give_up = return $ Left $ unSwap swapped Pair (mkTyVarTy tv) ty

    tyvar_tyvar tv1 tv2
      | tv1 == tv2 = return (Right (mkTyVarTy tv1))
      | otherwise  = do { (ty1', progress1) <- quick_zonk tv1
                        ; (ty2', progress2) <- quick_zonk tv2
                        ; if progress1 || progress2
                          then go ty1' ty2'
                          else return $ Left (Pair (TyVarTy tv1) (TyVarTy tv2)) }

Simon Peyton Jones's avatar
Simon Peyton Jones committed
1157 1158 1159 1160
    trace_indirect tv ty
       = traceTcS "Following filled tyvar (zonk_eq_types)"
                  (ppr tv <+> equals <+> ppr ty)

1161 1162 1163 1164 1165
    quick_zonk tv = case tcTyVarDetails tv of
      MetaTv { mtv_ref = ref }
        -> do { cts <- readTcRef ref
              ; case cts of
                  Flexi        -> return (TyVarTy tv, False)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1166 1167
                  Indirect ty' -> do { trace_indirect tv ty'
                                     ; return (ty', True) } }
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
      _ -> return (TyVarTy tv, False)

      -- This happens for type families, too. But recall that failure
      -- here just means to try harder, so it's OK if the type function
      -- isn't injective.
    tycon :: TyCon -> [TcType] -> [TcType]
          -> TcS (Either (Pair TcType) TcType)
    tycon tc tys1 tys2
      = do { results <- zipWithM go tys1 tys2
           ; return $ case combine_results results of
               Left tys  -> Left (mkTyConApp tc <$> tys)
               Right tys -> Right (mkTyConApp tc tys) }

    combine_results :: [Either (Pair TcType) TcType]
                    -> Either (Pair [TcType]) [TcType]
    combine_results = bimap (fmap reverse) reverse .
                      foldl' (combine_rev (:)) (Right [])

      -- combine (in reverse) a new result onto an already-combined result
    combine_rev :: (a -> b -> c)
                -> Either (Pair b) b
                -> Either (Pair a) a
                -> Either (Pair c) c
    combine_rev f (Left list) (Left elt) = Left (f <$> elt     <*> list)
    combine_rev f (Left list) (Right ty) = Left (f <$> pure ty <*> list)
    combine_rev f (Right tys) (Left elt) = Left (f <$> elt     <*> pure tys)
    combine_rev f (Right tys) (Right ty) = Right (f ty tys)
1195

1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
{- See Note [Unwrap newtypes first]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  newtype N m a = MkN (m a)
Then N will get a conservative, Nominal role for its second paramter 'a',
because it appears as an argument to the unknown 'm'. Now consider
  [W] N Maybe a  ~R#  N Maybe b

If we decompose, we'll get
  [W] a ~N# b

But if instead we unwrap we'll get
  [W] Maybe a ~R# Maybe b
which in turn gives us
  [W] a ~R# b
which is easier to satisfy.

Bottom line: unwrap newtypes before decomposing them!
c.f. Trac #9123 comment:52,53 for a compelling example.

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
Note [Newtypes can blow the stack]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)
  newtype Y = MkY (Int -> Y)

and now wish to prove

  [W] X ~R Y

This Wanted will loop, expanding out the newtypes ever deeper looking
for a solid match or a solid discrepancy. Indeed, there is something
appropriate to this looping, because X and Y *do* have the same representation,
in the limit -- they're both (Fix ((->) Int)). However, no finitely-sized
coercion will ever witness it. This loop won't actually cause GHC to hang,
though, because we check our depth when unwrapping newtypes.

1234 1235 1236 1237 1238 1239 1240 1241 1242
Note [Eager reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)

and

  [W] X ~R X
1243

1244 1245 1246 1247 1248
Naively, we would start unwrapping X and end up in a loop. Instead,
we do this eager reflexivity check. This is necessary only for representational
equality because the flattener technology deals with the similar case
(recursive type families) for nominal equality.

1249 1250
Note that this check does not catch all cases, but it will catch the cases
we're most worried about, types like X above that are actually inhabited.
1251

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1252
Here's another place where this reflexivity check is key:
1253 1254 1255
Consider trying to prove (f a) ~R (f a). The AppTys in there can't
be decomposed, because representational equality isn't congruent with respect
to AppTy. So, when canonicalising the equality above, we get stuck and
1256
would normally produce a CIrredCan. However, we really do want to
1257 1258 1259 1260 1261 1262 1263 1264 1265
be able to solve (f a) ~R (f a). So, in the representational case only,
we do a reflexivity check.

(This would be sound in the nominal case, but unnecessary, and I [Richard
E.] am worried that it would slow down the common case.)
-}

------------------------
-- | We're able to unwrap a newtype. Update the bits accordingly.
1266
can_eq_newtype_nc :: CtEvidence           -- ^ :: ty1 ~ ty2
1267
                  -> SwapFlag
1268 1269
                  -> TcType                                    -- ^ ty1
                  -> ((Bag GlobalRdrElt, TcCoercion), TcType)  -- ^ :: ty1 ~ ty1'
1270 1271 1272
                  -> TcType               -- ^ ty2
                  -> TcType               -- ^ ty2, with type synonyms
                  -> TcS (StopOrContinue Ct)
1273
can_eq_newtype_nc ev swapped ty1 ((gres, co), ty1') ty2 ps_ty2
1274
  = do { traceTcS "can_eq_newtype_nc" $
1275
         vcat [ ppr ev, ppr swapped, ppr co, ppr gres, ppr ty1', ppr ty2 ]
1276 1277

         -- check for blowing our stack:
1278 1279
         -- See Note [Newtypes can blow the stack]
       ; checkReductionDepth (ctEvLoc ev) ty1
1280
       ; addUsedGREs (bagToList gres)
1281 1282 1283
           -- we have actually used the newtype constructor here, so
           -- make sure we don't warn about importing it!

1284 1285 1286
       ; new_ev <- rewriteEqEvidence ev swapped ty1' ps_ty2
                                     (mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
       ; can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
1287

1288
---------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1289
-- ^ Decompose a type application.
1290
-- All input types must be flat. See Note [Canonicalising type applications]
1291 1292
-- Nominal equality only!
can_eq_app :: CtEvidence       -- :: s1 t1 ~N s2 t2
1293 1294 1295
           -> Xi -> Xi         -- s1 t1
           -> Xi -> Xi         -- s2 t2
           -> TcS (StopOrContinue Ct)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1296 1297

-- AppTys only decompose for nominal equality, so this case just leads
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1298
-- to an irreducible constraint; see typecheck/should_compile/T10494
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1299
-- See Note [Decomposing equality], note {4}
1300
can_eq_app ev s1 t1 s2 t2
1301
  | CtDerived { ctev_loc = loc } <- ev
1302 1303 1304 1305
  = do { unifyDeriveds loc [Nominal, Nominal] [s1, t1] [s2, t2]
       ; stopWith ev "Decomposed [D] AppTy" }
  | CtWanted { ctev_dest = dest, ctev_loc = loc } <- ev
  = do { co_s <- unifyWanted loc Nominal s1 s2
1306 1307 1308 1309
       ; let arg_loc
               | isNextArgVisible s1 = loc
               | otherwise           = updateCtLocOrigin loc toInvisibleOrigin
       ; co_t <- unifyWanted arg_loc Nominal t1 t2
1310 1311 1312
       ; let co = mkAppCo co_s co_t
       ; setWantedEq dest co
       ; stopWith ev "Decomposed [W] AppTy" }
1313 1314 1315 1316 1317 1318 1319 1320 1321

    -- If there is a ForAll/(->) mismatch, the use of the Left coercion
    -- below is ill-typed, potentially leading to a panic in splitTyConApp
    -- Test case: typecheck/should_run/Typeable1
    -- We could also include this mismatch check above (for W and D), but it's slow
    -- and we'll get a better error message not doing it
  | s1k `mismatches` s2k
  = canEqHardFailure ev (s1 `mkAppTy` t1) (s2 `mkAppTy` t2)

1322 1323
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { let co   = mkTcCoVarCo evar
1324 1325
             co_s = mkTcLRCo CLeft  co
             co_t = mkTcLRCo CRight co
1326
       ; evar_s <- newGivenEvVar loc ( mkTcEqPredLikeEv ev s1 s2
1327
                                     , evCoercion co_s )
1328
       ; evar_t <- newGivenEvVar loc ( mkTcEqPredLikeEv ev t1 t2
1329
                                     , evCoercion co_t )
1330 1331
       ; emitWorkNC [evar_t]
       ; canEqNC evar_s NomEq s1 s2 }
1332 1333 1334 1335 1336 1337 1338 1339

  where
    s1k = typeKind s1
    s2k = typeKind s2

    k1 `mismatches` k2
      =  isForAllTy k1 && not (isForAllTy k2)
      || not (isForAllTy k1) && isForAllTy k2
1340

1341 1342
-----------------------
-- | Break apart an equality over a casted type
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1343
-- looking like   (ty1 |> co1) ~ ty2   (modulo a swap-flag)
1344 1345 1346 1347
canEqCast :: Bool         -- are both types flat?
          -> CtEvidence
          -> EqRel
          -> SwapFlag
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1348 1349
          -> TcType -> Coercion   -- LHS (res. RHS), ty1 |> co1
          -> TcType -> TcType     -- RHS (res. LHS), ty2 both normal and pretty
1350 1351 1352 1353 1354
          -> TcS (StopOrContinue Ct)
canEqCast flat ev eq_rel swapped ty1 co1 ty2 ps_ty2
  = do { traceTcS "Decomposing cast" (vcat [ ppr ev
                                           , ppr ty1 <+> text "|>" <+> ppr co1
                                           , ppr ps_ty2 ])
1355
       ; new_ev <- rewriteEqEvidence ev swapped ty1 ps_ty2
Ningning Xie's avatar
Ningning Xie committed
1356
                                     (mkTcGReflRightCo role ty1 co1)
1357 1358
                                     (mkTcReflCo role ps_ty2)
       ; can_eq_nc flat new_ev eq_rel ty1 ty1 ty2 ps_ty2 }
1359 1360 1361
  where
    role = eqRelRole eq_rel

1362
------------------------
1363 1364 1365 1366
canTyConApp :: CtEvidence -> EqRel
            -> TyCon -> [TcType]
            -> TyCon -> [TcType]
            -> TcS (StopOrContinue Ct)
1367
-- See Note [Decomposing TyConApps]
1368
canTyConApp ev eq_rel tc1 tys1 tc2 tys2
1369
  | tc1 == tc2
1370
  , tys1 `equalLength` tys2
1371
  = do { inerts <- getTcSInerts
1372 1373
       ; if can_decompose inerts
         then do { traceTcS "canTyConApp"
1374 1375 1376 1377
                       (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
                 ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
                 ; stopWith ev "Decomposed TyConApp" }
         else canEqFailure ev eq_rel ty1 ty2 }
1378

1379 1380
  -- See Note [Skolem abstract data] (at tyConSkolem)
  | tyConSkolem tc1 || tyConSkolem tc2
1381
  = do { traceTcS "canTyConApp: skolem abstract" (ppr tc1 $$ ppr tc2)
1382
       ; continueWith (mkIrredCt ev) }
1383

1384 1385
  -- Fail straight away for better error messages
  -- See Note [Use canEqFailure in canDecomposableTyConApp]
1386 1387
  | eq_rel == ReprEq && not (isGenerativeTyCon tc1 Representational &&
                             isGenerativeTyCon tc2 Representational)
1388 1389
  = canEqFailure ev eq_rel ty1 ty2
  | otherwise
1390
  = canEqHardFailure ev ty1 ty2
1391 1392 1393 1394
  where
    ty1 = mkTyConApp tc1 tys1
    ty2 = mkTyConApp tc2 tys2

1395 1396 1397
    loc  = ctEvLoc ev
    pred = ctEvPred ev

1398 1399 1400 1401 1402
     -- See Note [Decomposing equality]
    can_decompose inerts
      =  isInjectiveTyCon tc1 (eqRelRole eq_rel)
      || (ctEvFlavour ev /= Given && isEmptyBag (matchableGivens loc pred inerts))

1403 1404 1405 1406 1407
{-
Note [Use canEqFailure in canDecomposableTyConApp]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We must use canEqFailure, not canEqHardFailure here, because there is
the possibility of success if working with a representational equality.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1408
Here is one case:
1409 1410 1411 1412 1413

  type family TF a where TF Char = Bool
  data family DF a
  newtype instance DF Bool = MkDF Int

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1414
Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
1415 1416
know `a`. This is *not* a hard failure, because we might soon learn
that `a` is, in fact, Char, and then the equality succeeds.
1417

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1418 1419
Here is another case: