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

3
module TcCanonical(
4 5 6 7 8
     canonicalize,
     unifyDerived,

     StopOrContinue(..), stopWith, continueWith
  ) where
9 10 11 12 13

#include "HsVersions.h"

import TcRnTypes
import TcType
14
import Type
dreixel's avatar
dreixel committed
15
import Kind
16 17
import TcFlatten
import TcSMonad
18
import TcEvidence
19 20 21
import Class
import TyCon
import TypeRep
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
22 23 24
import Coercion
import FamInstEnv ( FamInstEnvs )
import FamInst ( tcTopNormaliseNewTypeTF_maybe )
25
import Var
26
import Name( isSystemName )
27
import OccName( OccName )
28
import Outputable
29
import DynFlags( DynFlags )
30
import VarSet
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
31
import RdrName
32
import DataCon ( dataConName )
33

34
import Pair
35
import Util
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
36 37
import MonadUtils ( zipWith3M, zipWith3M_ )
import Data.List  ( zip4 )
38
import BasicTypes
39
import FastString
40

Austin Seipp's avatar
Austin Seipp committed
41 42 43 44 45 46
{-
************************************************************************
*                                                                      *
*                      The Canonicaliser                               *
*                                                                      *
************************************************************************
47

48 49
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
50

51
Canonicalization converts a simple constraint to a canonical form. It is
52 53 54
unary (i.e. treats individual constraints one at a time), does not do
any zonking, but lives in TcS monad because it needs to create fresh
variables (for flattening) and consult the inerts (for efficiency).
55

56
The execution plan for canonicalization is the following:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
57 58

  1) Decomposition of equalities happens as necessary until we reach a
59
     variable or type family in one side. There is no decomposition step
Simon Peyton Jones's avatar
Simon Peyton Jones committed
60
     for other forms of constraints.
61

Simon Peyton Jones's avatar
Simon Peyton Jones committed
62 63 64 65
  2) If, when we decompose, we discover a variable on the head then we
     look at inert_eqs from the current inert for a substitution for this
     variable and contine decomposing. Hence we lazily apply the inert
     substitution if it is needed.
66

67 68
  3) If no more decomposition is possible, we deeply apply the substitution
     from the inert_eqs and continue with flattening.
69

Simon Peyton Jones's avatar
Simon Peyton Jones committed
70 71 72 73 74
  4) During flattening, we examine whether we have already flattened some
     function application by looking at all the CTyFunEqs with the same
     function in the inert set. The reason for deeply applying the inert
     substitution at step (3) is to maximise our chances of matching an
     already flattened family application in the inert.
75

Simon Peyton Jones's avatar
Simon Peyton Jones committed
76 77
The net result is that a constraint coming out of the canonicalization
phase cannot be rewritten any further from the inerts (but maybe /it/ can
78 79
rewrite an inert or still interact with an inert in a further phase in the
simplifier.
dimitris's avatar
dimitris committed
80

81
Note [Caching for canonicals]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
82
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
83 84 85 86
Our plan with pre-canonicalization is to be able to solve a constraint
really fast from existing bindings in TcEvBinds. So one may think that
the condition (isCNonCanonical) is not necessary.  However consider
the following setup:
87

Simon Peyton Jones's avatar
Simon Peyton Jones committed
88 89
InertSet = { [W] d1 : Num t }
WorkList = { [W] d2 : Num t, [W] c : t ~ Int}
90

Simon Peyton Jones's avatar
Simon Peyton Jones committed
91 92 93 94 95
Now, we prioritize equalities, but in our concrete example
(should_run/mc17.hs) the first (d2) constraint is dealt with first,
because (t ~ Int) is an equality that only later appears in the
worklist since it is pulled out from a nested implication
constraint. So, let's examine what happens:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
96

97 98
   - We encounter work item (d2 : Num t)

Simon Peyton Jones's avatar
Simon Peyton Jones committed
99
   - Nothing is yet in EvBinds, so we reach the interaction with inerts
100
     and set:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
101
              d2 := d1
102 103
    and we discard d2 from the worklist. The inert set remains unaffected.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
104 105 106
   - Now the equation ([W] c : t ~ Int) is encountered and kicks-out
     (d1 : Num t) from the inerts.  Then that equation gets
     spontaneously solved, perhaps. We end up with:
107
        InertSet : { [G] c : t ~ Int }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
108
        WorkList : { [W] d1 : Num t}
109

Simon Peyton Jones's avatar
Simon Peyton Jones committed
110 111
   - Now we examine (d1), we observe that there is a binding for (Num
     t) in the evidence binds and we set:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
112
             d1 := d2
113 114
     and end up in a loop!

Simon Peyton Jones's avatar
Simon Peyton Jones committed
115 116 117 118 119 120 121 122
Now, the constraints that get kicked out from the inert set are always
Canonical, so by restricting the use of the pre-canonicalizer to
NonCanonical constraints we eliminate this danger. Moreover, for
canonical constraints we already have good caching mechanisms
(effectively the interaction solver) and we are interested in reducing
things like superclasses of the same non-canonical constraint being
generated hence I don't expect us to lose a lot by introducing the
(isCNonCanonical) restriction.
123

Simon Peyton Jones's avatar
Simon Peyton Jones committed
124 125 126 127 128 129 130
A similar situation can arise in TcSimplify, at the end of the
solve_wanteds function, where constraints from the inert set are
returned as new work -- our substCt ensures however that if they are
not rewritten by subst, they remain canonical and hence we will not
attempt to solve them from the EvBinds. If on the other hand they did
get rewritten and are now non-canonical they will still not match the
EvBinds, so we are again good.
Austin Seipp's avatar
Austin Seipp committed
131
-}
132

133 134 135
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

136
canonicalize :: Ct -> TcS (StopOrContinue Ct)
137
canonicalize ct@(CNonCanonical { cc_ev = ev })
138
  = do { traceTcS "canonicalize (non-canonical)" (ppr ct)
139
       ; {-# SCC "canEvVar" #-}
140
         canEvNC ev }
141

142
canonicalize (CDictCan { cc_ev = ev
143 144
                       , cc_class  = cls
                       , cc_tyargs = xis })
145
  = {-# SCC "canClass" #-}
146 147
    canClass ev cls xis -- Do not add any superclasses
canonicalize (CTyEqCan { cc_ev = ev
148
                       , cc_tyvar  = tv
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
149 150
                       , cc_rhs    = xi
                       , cc_eq_rel = eq_rel })
151
  = {-# SCC "canEqLeafTyVarEq" #-}
152 153 154
    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
155

156
canonicalize (CFunEqCan { cc_ev = ev
157 158
                        , cc_fun    = fn
                        , cc_tyargs = xis1
159
                        , cc_fsk    = fsk })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
160
  = {-# SCC "canEqLeafFunEq" #-}
161
    canCFunEqCan ev fn xis1 fsk
162

163 164
canonicalize (CIrredEvCan { cc_ev = ev })
  = canIrred ev
thomasw's avatar
thomasw committed
165 166
canonicalize (CHoleCan { cc_ev = ev, cc_occ = occ, cc_hole = hole })
  = canHole ev occ hole
167

168
canEvNC :: CtEvidence -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
169
-- Called only for non-canonical EvVars
170
canEvNC ev
171
  = case classifyPredType (ctEvPred ev) of
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
172 173 174 175 176 177
      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
      IrredPred {}          -> do traceTcS "canEvNC:irred" (ppr (ctEvPred ev))
                                  canIrred   ev
Austin Seipp's avatar
Austin Seipp committed
178 179 180 181 182 183 184
{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}
185

Simon Peyton Jones's avatar
Simon Peyton Jones committed
186
canClass, canClassNC
187
   :: CtEvidence
188
   -> Class -> [Type] -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
189
-- Precondition: EvVar is class evidence
Simon Peyton Jones's avatar
Simon Peyton Jones committed
190 191 192 193 194 195

-- The canClassNC version is used on non-canonical constraints
-- and adds superclasses.  The plain canClass version is used
-- for already-canonical class constraints (but which might have
-- been subsituted or somthing), and hence do not need superclasses

196 197
canClassNC ev cls tys
  = canClass ev cls tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
198 199
    `andWhenContinue` emitSuperclasses

200
canClass ev cls tys
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
201 202
  =   -- all classes do *nominal* matching
    ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
203
    do { (xis, cos) <- flattenManyNom ev tys
Joachim Breitner's avatar
Joachim Breitner committed
204
       ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
205
             xi = mkClassPred cls xis
206 207
             mk_ct new_ev = CDictCan { cc_ev = new_ev
                                     , cc_tyargs = xis, cc_class = cls }
208
       ; mb <- rewriteEvidence ev xi co
Simon Peyton Jones's avatar
Simon Peyton Jones committed
209
       ; traceTcS "canClass" (vcat [ ppr ev <+> ppr cls <+> ppr tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
210
                                   , ppr xi, ppr mb ])
211
       ; return (fmap mk_ct mb) }
dimitris's avatar
dimitris committed
212

213
emitSuperclasses :: Ct -> TcS (StopOrContinue Ct)
214
emitSuperclasses ct@(CDictCan { cc_ev = ev , cc_tyargs = xis_new, cc_class = cls })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
215 216
            -- Add superclasses of this one here, See Note [Adding superclasses].
            -- But only if we are not simplifying the LHS of a rule.
217
 = do { newSCWorkFromFlavored ev cls xis_new
Simon Peyton Jones's avatar
Simon Peyton Jones committed
218
      -- Arguably we should "seq" the coercions if they are derived,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
219
      -- as we do below for emit_kind_constraint, to allow errors in
Simon Peyton Jones's avatar
Simon Peyton Jones committed
220
      -- superclasses to be executed if deferred to runtime!
Simon Peyton Jones's avatar
Simon Peyton Jones committed
221 222
      ; continueWith ct }
emitSuperclasses _ = panic "emit_superclasses of non-class!"
223

224 225
{- Note [Adding superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
226 227 228 229 230
Since dictionaries are canonicalized only once in their lifetime, the
place to add their superclasses is canonicalisation.  See Note [Add
superclasses only during canonicalisation].  Here is what we do:

  Givens:   Add all their superclasses as Givens.
231 232 233
            They may be needed to prove Wanteds

  Wanteds:  Do nothing.
234

235 236 237
  Deriveds: Add all their superclasses as Derived.
            The sole reason is to expose functional dependencies
            in superclasses or equality superclasses.
238

239 240 241
            We only do this in the improvement phase, if solving has
            not succeeded; see Note [The improvement story] in
            TcInteract
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

Examples of how adding superclasses as Derived is useful

    --- 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
    Now we we get [D] beta ~ b, and can solve that.

262
---------- Historical note -----------
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
Example of why adding superclass of a Wanted as a Given would
be terrible, see Note [Do not add superclasses of solved dictionaries]
in TcSMonad, which has this example:
        class Ord a => C a where
        instance Ord [a] => C [a] where ...
Suppose we are trying to solve
  [G] d1 : Ord a
  [W] d2 : C [a]
If we (bogusly) added the superclass of d2 as Gievn we'd have
  [G] d1 : Ord a
  [W] d2 : C [a]
  [G] d3 : Ord [a]   -- Superclass of d2, bogus

Then we'll use the instance decl to give
  [G] d1 : Ord a     Solved: d2 : C [a] = $dfCList d4
  [G] d3 : Ord [a]   -- Superclass of d2, bogus
  [W] d4: Ord [a]

ANd now we could bogusly solve d4 from d3.


Note [Add superclasses only during canonicalisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We add superclasses only during canonicalisation, on the passage
from CNonCanonical to CDictCan.  A class constraint can be repeatedly
rewritten, and there's no point in repeatedly adding its superclasses.

Here's a serious, but now out-dated example, from Trac #4497:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
291

292 293 294
   class Num (RealOf t) => Normed t
   type family RealOf x

Simon Peyton Jones's avatar
Simon Peyton Jones committed
295
Assume the generated wanted constraint is:
296 297 298
   [W] RealOf e ~ e
   [W] Normed e

Simon Peyton Jones's avatar
Simon Peyton Jones committed
299
If we were to be adding the superclasses during simplification we'd get:
300 301 302 303
   [W] RealOf e ~ e
   [W] Normed e
   [D] RealOf e ~ fuv
   [D] Num fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
304
==>
305
   e := fuv, Num fuv, Normed fuv, RealOf fuv ~ fuv
Simon Peyton Jones's avatar
Simon Peyton Jones committed
306

307 308 309
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
310
happen.
311 312 313 314

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

316
newSCWorkFromFlavored :: CtEvidence -> Class -> [Xi] -> TcS ()
317
-- Returns superclasses, see Note [Adding superclasses]
318
newSCWorkFromFlavored flavor cls xis
319
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- flavor
320 321 322 323 324 325 326 327 328 329 330
  = do { let size = sizePred (mkClassPred cls xis)
             loc' = case ctLocOrigin loc of
                       GivenOrigin InstSkol
                         -> loc { ctl_origin = GivenOrigin (InstSC size) }
                       GivenOrigin (InstSC n)
                         -> loc { ctl_origin = GivenOrigin (InstSC (n `max` size)) }
                       _ -> loc
                    -- See Note [Solving superclass constraints] in TcInstDcls
                    -- for explantation of loc'

       ; given_evs <- newGivenEvVars loc' (mkEvScSelectors (EvId evar) cls xis)
331
       ; emitWorkNC given_evs }
dimitris's avatar
dimitris committed
332 333

  | isEmptyVarSet (tyVarsOfTypes xis)
334
  = return () -- Wanteds with no variables yield no deriveds.
335
              -- See Note [Improvement from Ground Wanteds]
336

337
  | otherwise -- Derived case, just add those SC that can lead to improvement.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
338
  = do { let sc_rec_theta = transSuperClasses cls xis
339
             impr_theta   = filter isImprovementPred sc_rec_theta
340
             loc          = ctEvLoc flavor
341
       ; traceTcS "newSCWork/Derived" $ text "impr_theta =" <+> ppr impr_theta
342
       ; emitNewDeriveds loc impr_theta }
343 344


Austin Seipp's avatar
Austin Seipp committed
345 346 347 348 349 350 351
{-
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
352

353
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
354
-- Precondition: ty not a tuple and no other evidence form
355
canIrred old_ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
356 357
  = do { let old_ty = ctEvPred old_ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
358
       ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
359
       ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
360 361
    do { -- Re-classify, in case flattening has improved its shape
       ; case classifyPredType (ctEvPred new_ev) of
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
362 363 364 365
           ClassPred cls tys     -> canClassNC new_ev cls tys
           EqPred eq_rel ty1 ty2 -> canEqNC new_ev eq_rel ty1 ty2
           _                     -> continueWith $
                                    CIrredEvCan { cc_ev = new_ev } } }
366

thomasw's avatar
thomasw committed
367 368
canHole :: CtEvidence -> OccName -> HoleSort -> TcS (StopOrContinue Ct)
canHole ev occ hole_sort
369 370
  = do { let ty = ctEvPred ev
       ; (xi,co) <- flatten FM_SubstOnly ev ty -- co :: xi ~ ty
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
371 372 373 374 375
       ; rewriteEvidence ev xi co `andWhenContinue` \ new_ev ->
    do { emitInsoluble (CHoleCan { cc_ev = new_ev
                                 , cc_occ = occ
                                 , cc_hole = hole_sort })
       ; stopWith new_ev "Emit insoluble hole" } }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
376

Austin Seipp's avatar
Austin Seipp committed
377 378 379 380 381 382
{-
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
383 384 385 386 387 388 389 390 391 392 393 394 395

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)
Austin Seipp's avatar
Austin Seipp committed
396
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
397

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
398 399
canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
canEqNC ev eq_rel ty1 ty2
400
  = can_eq_nc False ev eq_rel ty1 ty1 ty2 ty2
401

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
402
can_eq_nc
403 404
   :: Bool            -- True => both types are flat
   -> CtEvidence
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
405
   -> EqRel
Austin Seipp's avatar
Austin Seipp committed
406 407
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
408
   -> TcS (StopOrContinue Ct)
409
can_eq_nc flat ev eq_rel ty1 ps_ty1 ty2 ps_ty2
Austin Seipp's avatar
Austin Seipp committed
410
  = do { traceTcS "can_eq_nc" $
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
411 412 413
         vcat [ ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
       ; rdr_env <- getGlobalRdrEnvTcS
       ; fam_insts <- getFamInstEnvs
414
       ; can_eq_nc' flat rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
415 416

can_eq_nc'
417 418
   :: Bool           -- True => both input types are flattened
   -> GlobalRdrEnv   -- needed to see which newtypes are in scope
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
419 420 421 422 423 424
   -> 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)
425 426

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
427 428 429 430 431
can_eq_nc' flat _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
  | 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

-- need to check for reflexivity in the ReprEq case.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
432
-- See Note [Eager reflexivity check]
433 434 435 436 437 438
can_eq_nc' _flat _rdr_env _envs ev ReprEq ty1 _ ty2 _
  | ty1 `eqType` ty2
  = canEqReflexive ev ReprEq ty1

-- When working with ReprEq, unwrap newtypes.
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 _ ty2 ps_ty2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
439 440
  | Just (co, ty1') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
  = can_eq_newtype_nc rdr_env ev NotSwapped co ty1 ty1' ty2 ps_ty2
441
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
442 443
  | Just (co, ty2') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
  = can_eq_newtype_nc rdr_env ev IsSwapped  co ty2 ty2' ty1 ps_ty1
444 445 446 447 448 449

----------------------
-- Otherwise try to decompose
----------------------

-- Literals
450
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
451
 | l1 == l2
452 453
  = do { setEvBindIfWanted ev (EvCoercion $
                               mkTcReflCo (eqRelRole eq_rel) ty1)
454
       ; stopWith ev "Equal LitTy" }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
455

Austin Seipp's avatar
Austin Seipp committed
456
-- Decomposable type constructor applications
457
-- Synonyms and type functions (which are not decomposable)
Austin Seipp's avatar
Austin Seipp committed
458
-- have already been dealt with
459 460
can_eq_nc' _flat _rdr_env _envs ev eq_rel
          (TyConApp tc1 tys1) _ (TyConApp tc2 tys2) _
461 462
  | isDecomposableTyCon tc1
  , isDecomposableTyCon tc2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
463
  = canDecomposableTyConApp ev eq_rel tc1 tys1 tc2 tys2
464

465 466
can_eq_nc' _flat _rdr_env _envs ev eq_rel
           (TyConApp tc1 _) ps_ty1 (FunTy {}) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
467
  | isDecomposableTyCon tc1
468 469 470
      -- The guard is important
      -- e.g.  (x -> y) ~ (F x y) where F has arity 1
      --       should not fail, but get the app/app case
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
471
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
472

473
can_eq_nc' _flat _rdr_env _envs ev eq_rel (FunTy s1 t1) _ (FunTy s2 t2) _
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
474
  = do { canDecomposableTyConAppOK ev eq_rel funTyCon [s1,t1] [s2,t2]
475 476
       ; stopWith ev "Decomposed FunTyCon" }

477 478
can_eq_nc' _flat _rdr_env _envs ev eq_rel
          (FunTy {}) ps_ty1 (TyConApp tc2 _) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
479
  | isDecomposableTyCon tc2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
480
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
481

482 483
can_eq_nc' _flat _rdr_env _envs ev eq_rel
           s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
484
 | CtWanted { ctev_loc = loc, ctev_evar = orig_ev } <- ev
485 486
 = do { let (tvs1,body1) = tcSplitForAllTys s1
            (tvs2,body2) = tcSplitForAllTys s2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
487
      ; if not (equalLength tvs1 tvs2) then
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
488
          canEqHardFailure ev eq_rel s1 s2
489
        else
490
          do { traceTcS "Creating implication for polytype equality" $ ppr ev
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
491 492
             ; ev_term <- deferTcSForAllEq (eqRelRole eq_rel)
                                           loc (tvs1,body1) (tvs2,body2)
493
             ; setWantedEvBind orig_ev ev_term
494
             ; stopWith ev "Deferred polytype equality" } }
495
 | otherwise
Simon Peyton Jones's avatar
Simon Peyton Jones committed
496
 = do { traceTcS "Ommitting decomposition of given polytype equality" $
497
        pprEq s1 s2    -- See Note [Do not decompose given polytype equalities]
498
      ; stopWith ev "Discard given polytype equality" }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
499

500
-- See Note [Canonicalising type applications] about why we require flat types
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
501
can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
502
  | Just (t2, s2) <- tcSplitAppTy_maybe ty2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
503 504
  = can_eq_app ev eq_rel t1 s1 t2 s2
can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
505
  | Just (t1, s1) <- tcSplitAppTy_maybe ty1
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
506
  = can_eq_app ev eq_rel t1 s1 t2 s2
507 508 509 510 511 512

-- No similarity in type structure detected. Flatten and try again!
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
       ; rewriteEqEvidence ev eq_rel NotSwapped xi1 xi2 co1 co2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
513
         `andWhenContinue` \ new_ev ->
514 515 516 517 518 519 520 521 522 523 524 525 526
         can_eq_nc' True rdr_env envs new_ev eq_rel xi1 xi1 xi2 xi2 }

-- Type variable on LHS or RHS are last. 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_ty2
  = canEqTyVar ev eq_rel NotSwapped tv1 ps_ty2
can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 (TyVarTy tv2) _
  = canEqTyVar ev eq_rel IsSwapped  tv2 ps_ty1

-- We've flattened and the types don't match. Give up.
can_eq_nc' True _rdr_env _envs ev eq_rel _ ps_ty1 _ ps_ty2
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
527

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
528
{-
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
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.

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
547 548 549 550 551 552 553 554 555
Note [Eager reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)

and

  [W] X ~R X
Simon Peyton Jones's avatar
Simon Peyton Jones committed
556

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
557 558 559 560 561
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.

562 563
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.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
564

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
565
Here's another place where this reflexivity check is key:
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
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 592
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
would normally produce a CIrredEvCan. However, we really do want to
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.
can_eq_newtype_nc :: GlobalRdrEnv
                  -> CtEvidence           -- ^ :: ty1 ~ ty2
                  -> SwapFlag
                  -> TcCoercion           -- ^ :: ty1 ~ ty1'
                  -> TcType               -- ^ ty1
                  -> TcType               -- ^ ty1'
                  -> TcType               -- ^ ty2
                  -> TcType               -- ^ ty2, with type synonyms
                  -> TcS (StopOrContinue Ct)
can_eq_newtype_nc rdr_env ev swapped co ty1 ty1' ty2 ps_ty2
  = do { traceTcS "can_eq_newtype_nc" $
         vcat [ ppr ev, ppr swapped, ppr co, ppr ty1', ppr ty2 ]

         -- check for blowing our stack:
593 594 595
         -- See Note [Newtypes can blow the stack]
       ; checkReductionDepth (ctEvLoc ev) ty1
       ; markDataConsAsUsed rdr_env (tyConAppTyCon ty1)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
596 597 598 599 600 601
           -- we have actually used the newtype constructor here, so
           -- make sure we don't warn about importing it!

       ; rewriteEqEvidence ev ReprEq swapped ty1' ps_ty2
                           (mkTcSymCo co) (mkTcReflCo Representational ps_ty2)
         `andWhenContinue` \ new_ev ->
602
         can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
603 604 605 606 607

-- | Mark all the datacons of the given 'TyCon' as used in this module,
-- avoiding "redundant import" warnings.
markDataConsAsUsed :: GlobalRdrEnv -> TyCon -> TcS ()
markDataConsAsUsed rdr_env tc = addUsedRdrNamesTcS
608
  [ greUsedRdrName gre
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
609
  | dc <- tyConDataCons tc
610 611
  , gre : _  <- return $ lookupGRE_Name rdr_env (dataConName dc)
  , not (isLocalGRE gre) ]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
612

613
---------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
614
-- ^ Decompose a type application.
615
-- All input types must be flat. See Note [Canonicalising type applications]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
616 617
can_eq_app :: CtEvidence       -- :: s1 t1 ~r s2 t2
           -> EqRel            -- r
618 619 620
           -> Xi -> Xi         -- s1 t1
           -> Xi -> Xi         -- s2 t2
           -> TcS (StopOrContinue Ct)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
621 622 623 624 625 626 627 628

-- AppTys only decompose for nominal equality, so this case just leads
-- to an irreducible constraint
can_eq_app ev ReprEq _ _ _ _
  = do { traceTcS "failing to decompose representational AppTy equality" (ppr ev)
       ; continueWith (CIrredEvCan { cc_ev = ev }) }

can_eq_app ev NomEq s1 t1 s2 t2
629
  | CtDerived { ctev_loc = loc } <- ev
630
  = do { emitNewDerivedEq loc (mkTcEqPred t1 t2)
631 632 633 634 635 636 637
       ; canEqNC ev NomEq s1 s2 }
  | CtWanted { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { ev_s <- newWantedEvVarNC loc (mkTcEqPred s1 s2)
       ; co_t <- unifyWanted loc Nominal t1 t2
       ; let co = mkTcAppCo (ctEvCoercion ev_s) co_t
       ; setWantedEvBind evar (EvCoercion co)
       ; canEqNC ev_s NomEq s1 s2 }
638 639
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { let co   = mkTcCoVarCo evar
640 641 642 643 644 645 646 647
             co_s = mkTcLRCo CLeft  co
             co_t = mkTcLRCo CRight co
       ; evar_s <- newGivenEvVar loc (mkTcEqPred s1 s2, EvCoercion co_s)
       ; evar_t <- newGivenEvVar loc (mkTcEqPred t1 t2, EvCoercion co_t)
       ; emitWorkNC [evar_t]
       ; canEqNC evar_s NomEq s1 s2 }
  | otherwise  -- Can't happen
  = error "can_eq_app"
648

Simon Peyton Jones's avatar
Simon Peyton Jones committed
649
------------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
650
canDecomposableTyConApp :: CtEvidence -> EqRel
Simon Peyton Jones's avatar
Simon Peyton Jones committed
651 652
                        -> TyCon -> [TcType]
                        -> TyCon -> [TcType]
653
                        -> TcS (StopOrContinue Ct)
654
-- See Note [Decomposing TyConApps]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
655
canDecomposableTyConApp ev eq_rel tc1 tys1 tc2 tys2
656
  | tc1 == tc2
657 658 659 660
  , length tys1 == length tys2
  = if eq_rel == NomEq || ctEvFlavour ev /= Given || isDistinctTyCon tc1
       -- See Note [Decomposing newtypes]
    then do { traceTcS "canDecomposableTyConApp"
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
661
                  (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
662 663 664
            ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
            ; stopWith ev "Decomposed TyConApp" }
    else canEqFailure ev eq_rel ty1 ty2
665

666 667 668 669 670 671 672 673 674 675
  -- Fail straight away for better error messages
  -- See Note [Use canEqFailure in canDecomposableTyConApp]
  | isDataFamilyTyCon tc1 || isDataFamilyTyCon tc2
  = canEqFailure ev eq_rel ty1 ty2
  | otherwise
  = canEqHardFailure ev eq_rel ty1 ty2
  where
    ty1 = mkTyConApp tc1 tys1
    ty2 = mkTyConApp tc2 tys2

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689
{-
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.
Here is the case:

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

Suppose we are canonicalising (Int ~R DF (T a)), where we don't yet
know `a`. This is *not* a hard failure, because we might soon learn
that `a` is, in fact, Char, and then the equality succeeds.
690 691 692 693 694 695 696 697 698 699 700 701 702 703

Note [Decomposing newtypes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
As explained in Note [NthCo and newtypes] in Coercion, we can't use
NthCo on representational coercions over newtypes. So we avoid doing
so.

But is it sensible to decompose *Wanted* constraints over newtypes?
Yes. By the time we reach canDecomposableTyConApp, we know that any
newtypes that can be unwrapped have been. So, without importing more
constructors, say, we know there is no way forward other than decomposition.
So we take the one route we have available. This *does* mean that
importing a newtype's constructor might make code that previously
compiled fail to do so. (If that newtype is perversely recursive, say.)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
704 705 706
-}

canDecomposableTyConAppOK :: CtEvidence -> EqRel
707
                          -> TyCon -> [TcType] -> [TcType]
708 709
                          -> TcS ()
-- Precondition: tys1 and tys2 are the same length, hence "OK"
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
710
canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
711 712
  = case ev of
     CtDerived { ctev_loc = loc }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
713
        -> unifyDeriveds loc tc_roles tys1 tys2
714 715

     CtWanted { ctev_evar = evar, ctev_loc = loc }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
716
        -> do { cos <- zipWith3M (unifyWanted loc) tc_roles tys1 tys2
717
              ; setWantedEvBind evar (EvCoercion (mkTcTyConAppCo role tc cos)) }
718

719 720
     CtGiven { ctev_evar = evar, ctev_loc = loc }
        -> do { let ev_co = mkTcCoVarCo evar
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
721 722 723 724 725
              ; given_evs <- newGivenEvVars loc $
                             [ ( mkTcEqPredRole r ty1 ty2
                               , EvCoercion (mkTcNthCo i ev_co) )
                             | (r, ty1, ty2, i) <- zip4 tc_roles tys1 tys2 [0..]
                             , r /= Phantom ]
726 727
              ; emitWorkNC given_evs }
  where
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
728 729 730 731 732
    role     = eqRelRole eq_rel
    tc_roles = tyConRolesX role tc

-- | Call when canonicalizing an equality fails, but if the equality is
-- representational, there is some hope for the future.
733
-- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
734 735 736
canEqFailure :: CtEvidence -> EqRel
             -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure ev ReprEq ty1 ty2
737
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
738 739 740
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
       ; traceTcS "canEqFailure with ReprEq" $
         vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
741 742
       ; if isTcReflCo co1 && isTcReflCo co2
         then continueWith (CIrredEvCan { cc_ev = ev })
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
743 744
         else rewriteEqEvidence ev ReprEq NotSwapped xi1 xi2 co1 co2
              `andWhenContinue` \ new_ev ->
745
              can_eq_nc True new_ev ReprEq xi1 xi1 xi2 xi2 }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
746 747 748 749 750
canEqFailure ev NomEq ty1 ty2 = canEqHardFailure ev NomEq ty1 ty2

-- | Call when canonicalizing an equality fails with utterly no hope.
canEqHardFailure :: CtEvidence -> EqRel
                 -> TcType -> TcType -> TcS (StopOrContinue Ct)
751
-- See Note [Make sure that insolubles are fully rewritten]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
752
canEqHardFailure ev eq_rel ty1 ty2
753 754
  = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
       ; (s2, co2) <- flatten FM_SubstOnly ev ty2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
755 756 757 758
       ; rewriteEqEvidence ev eq_rel NotSwapped s1 s2 co1 co2
         `andWhenContinue` \ new_ev ->
    do { emitInsoluble (mkNonCanonical new_ev)
       ; stopWith new_ev "Definitely not equal" }}
759

Austin Seipp's avatar
Austin Seipp committed
760
{-
761 762 763 764 765 766 767 768 769 770 771 772 773
Note [Decomposing TyConApps]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we see (T s1 t1 ~ T s2 t2), then we can just decompose to
  (s1 ~ s2, t1 ~ t2)
and push those back into the work list.  But if
  s1 = K k1    s2 = K k2
then we will jus decomopose s1~s2, and it might be better to
do so on the spot.  An important special case is where s1=s2,
and we get just Refl.

So canDecomposableTyCon is a fast-path decomposition that uses
unifyWanted etc to short-cut that work.

774 775 776
Note [Canonicalising type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (s1 t1) ~ ty2, how should we proceed?
Austin Seipp's avatar
Austin Seipp committed
777
The simple things is to see if ty2 is of form (s2 t2), and
778
decompose.  By this time s1 and s2 can't be saturated type
Austin Seipp's avatar
Austin Seipp committed
779 780
function applications, because those have been dealt with
by an earlier equation in can_eq_nc, so it is always sound to
781 782
decompose.

Austin Seipp's avatar
Austin Seipp committed
783
However, over-eager decomposition gives bad error messages
784 785 786 787 788 789 790
for things like
   a b ~ Maybe c
   e f ~ p -> q
Suppose (in the first example) we already know a~Array.  Then if we
decompose the application eagerly, yielding
   a ~ Maybe
   b ~ c
Austin Seipp's avatar
Austin Seipp committed
791
we get an error        "Can't match Array ~ Maybe",
792 793
but we'd prefer to get "Can't match Array b ~ Maybe c".

794 795 796
So instead can_eq_wanted_app flattens the LHS and RHS, in the hope of
replacing (a b) by (Array b), before using try_decompose_app to
decompose it.
797

798 799
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
800 801
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
802 803 804
 (a) the mutable reference substitution in force at start of solving
 (b) any ty-binds in force at this point in solving
See Note [Kick out insolubles] in TcInteract.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
805
And if we don't do this there is a bad danger that
806 807 808
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.

809
Note [Do not decompose Given polytype equalities]
810 811
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
812
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
813
this given evidence.
814 815


816 817 818 819 820 821 822 823 824 825 826 827 828
Note [Combining insoluble constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As this point we have an insoluble constraint, like Int~Bool.

 * If it is Wanted, delete it from the cache, so that subsequent
   Int~Bool constraints give rise to separate error messages

 * But if it is Derived, DO NOT delete from cache.  A class constraint
   may get kicked out of the inert set, and then have its functional
   dependency Derived constraints generated a second time. In that
   case we don't want to get two (or more) error messages by
   generating two (or more) insoluble fundep constraints from the same
   class constraint.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
829 830 831 832 833 834 835 836 837 838 839

Note [No top-level newtypes on RHS of representational equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we're in this situation:

 work item:  [W] c1 : a ~R b
     inert:  [G] c2 : b ~R Id a

where
  newtype Id a = Id a

840 841 842 843
We want to make sure canEqTyVar sees [W] a ~R a, after b is flattened
and the Id newtype is unwrapped. This is assured by requiring only flat
types in canEqTyVar *and* having the newtype-unwrapping check above
the tyvar check in can_eq_nc.
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
844

Austin Seipp's avatar
Austin Seipp committed
845
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
846

Austin Seipp's avatar
Austin Seipp committed
847
canCFunEqCan :: CtEvidence
848
             -> TyCon -> [TcType]   -- LHS
849 850
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
851 852
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
853 854 855
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
856
  = do { (tys', cos) <- flattenManyNom ev tys
857 858 859 860 861
                        -- cos :: tys' ~ tys
       ; let lhs_co  = mkTcTyConAppCo Nominal fn cos
                        -- :: F tys' ~ F tys
             new_lhs = mkTyConApp fn tys'
             fsk_ty  = mkTyVarTy fsk
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
862 863 864 865
       ; rewriteEqEvidence ev NomEq NotSwapped new_lhs fsk_ty
                           lhs_co (mkTcNomReflCo fsk_ty)
         `andWhenContinue` \ ev' ->
    do { extendFlatCache fn tys' (ctEvCoercion ev', fsk_ty, ctEvFlavour ev')
866
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
867
                                 , cc_tyargs = tys', cc_fsk = fsk }) } }
868 869

---------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
870
canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
871 872
           -> TcTyVar             -- already flat
           -> TcType              -- already flat
873
           -> TcS (StopOrContinue Ct)
874
-- A TyVar on LHS, but so far un-zonked
875 876 877
canEqTyVar ev eq_rel swapped tv1 ps_ty2              -- ev :: tv ~ s2
  = do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr ps_ty2 $$ ppr swapped)
         -- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
878 879 880 881
         -- let fmode = FE { fe_ev = ev, fe_mode = FM_Avoid tv1' True }
         -- Flatten the RHS less vigorously, to avoid gratuitous flattening
         -- True <=> xi2 should not itself be a type-function application
       ; dflags <- getDynFlags
882
       ; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
883 884

canEqTyVar2 :: DynFlags
885
            -> CtEvidence   -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
886
            -> EqRel
887
            -> SwapFlag
888 889
            -> TcTyVar      -- lhs, flat
            -> TcType       -- rhs, flat
890
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
891
-- LHS is an inert type variable,
892
-- and RHS is fully rewritten, but with type synonyms
893
-- preserved as much as possible
894

895
canEqTyVar2 dflags ev eq_rel swapped tv1 xi2
896
  | Just tv2 <- getTyVar_maybe xi2
897
  = canEqTyVarTyVar ev eq_rel swapped tv1 tv2
898

899
  | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2  -- No occurs check
900 901 902 903
     -- We use xi2' on the RHS of the new CTyEqCan, a ~ xi2'
     -- to establish the invariant that a does not appear in the
     -- rhs of the CTyEqCan. This is guaranteed by occurCheckExpand;
     -- see Note [Occurs check expansion] in TcType
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
904 905
  = do { let k1 = tyVarKind tv1
             k2 = typeKind xi2'
906
       ; rewriteEqEvidence ev eq_rel swapped xi1 xi2' co1 (mkTcReflCo role xi2')
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
907 908 909
         `andWhenContinue` \ new_ev ->
         if k2 `isSubKind` k1
         then   -- Establish CTyEqCan kind invariant
910 911
                -- Reorientation has done its best, but the kinds might
                -- simply be incompatible
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
912 913 914 915
               continueWith (CTyEqCan { cc_ev = new_ev
                                      , cc_tyvar  = tv1, cc_rhs = xi2'
                                      , cc_eq_rel = eq_rel })
         else incompatibleKind new_ev xi1 k1 xi2' k2 }
916 917

  | otherwise  -- Occurs check error
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
918 919 920
  = rewriteEqEvidence ev eq_rel swapped xi1 xi2 co1 co2
    `andWhenContinue` \ new_ev ->
    case eq_rel of
921
      NomEq  -> do { emitInsoluble (mkNonCanonical new_ev)
922 923 924
              -- If we have a ~ [a], it is not canonical, and in particular
              -- we don't want to rewrite existing inerts with it, otherwise
              -- we'd risk divergence in the constraint solver
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
925 926 927 928 929 930 931 932 933 934 935
                   ; stopWith new_ev "Occurs check" }

        -- A representational equality with an occurs-check problem isn't
        -- insoluble! For example:
        --   a ~R b a
        -- We might learn that b is the newtype Id.
        -- But, the occurs-check certainly prevents the equality from being
        -- canonical, and we might loop if we were to use it in rewriting.
      ReprEq -> do { traceTcS "Occurs-check in representational equality"
                              (ppr xi1 $$ ppr xi2)
                   ; continueWith (CIrredEvCan { cc_ev = new_ev }) }
936
  where
937 938 939 940
    role = eqRelRole eq_rel
    xi1  = mkTyVarTy tv1
    co1  = mkTcReflCo role xi1
    co2  = mkTcReflCo role xi2
941

942
canEqTyVarTyVar :: CtEvidence           -- tv1 ~ rhs (or rhs ~ tv1, if swapped)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
943
                -> EqRel
944
                -> SwapFlag
945
                -> TcTyVar -> TcTyVar   -- tv1, tv2
946
                -> TcS (StopOrContinue Ct)
947
-- Both LHS and RHS rewrote to a type variable
948
-- See Note [Canonical orientation for tyvar/tyvar equality constraints]