TcCanonical.hs 65.3 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
36
import Bag
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
37 38
import MonadUtils ( zipWith3M, zipWith3M_ )
import Data.List  ( zip4 )
39
import BasicTypes
40
import FastString
41

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

49 50
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
51

52
Canonicalization converts a simple constraint to a canonical form. It is
53 54 55
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).
56

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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
63 64 65 66
  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.
67

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
71 72 73 74 75
  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.
76

Simon Peyton Jones's avatar
Simon Peyton Jones committed
77 78
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
79 80
rewrite an inert or still interact with an inert in a further phase in the
simplifier.
dimitris's avatar
dimitris committed
81

82
Note [Caching for canonicals]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
83
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
84 85 86 87
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:
88

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
92 93 94 95 96
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
97

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

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

Simon Peyton Jones's avatar
Simon Peyton Jones committed
105 106 107
   - 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:
108
        InertSet : { [G] c : t ~ Int }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
109
        WorkList : { [W] d1 : Num t}
110

Simon Peyton Jones's avatar
Simon Peyton Jones committed
111 112
   - 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
113
             d1 := d2
114 115
     and end up in a loop!

Simon Peyton Jones's avatar
Simon Peyton Jones committed
116 117 118 119 120 121 122 123
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.
124

Simon Peyton Jones's avatar
Simon Peyton Jones committed
125 126 127 128 129 130 131
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
132
-}
133

134 135 136
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

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

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

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

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

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

-- 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

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

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

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

225 226
{- Note [Adding superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
227 228 229 230 231
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.
232 233 234
            They may be needed to prove Wanteds

  Wanteds:  Do nothing.
235

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

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

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.

263
---------- Historical note -----------
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 291
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
292

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

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

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

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

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

317
newSCWorkFromFlavored :: CtEvidence -> Class -> [Xi] -> TcS ()
318
-- Returns superclasses, see Note [Adding superclasses]
319
newSCWorkFromFlavored flavor cls xis
320
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- flavor
321 322 323 324 325 326 327 328 329 330 331
  = 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)
332
       ; emitWorkNC given_evs }
dimitris's avatar
dimitris committed
333 334

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

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


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

354
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
355
-- Precondition: ty not a tuple and no other evidence form
356
canIrred old_ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
357 358
  = do { let old_ty = ctEvPred old_ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
359
       ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
360
       ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
361 362
    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
363 364 365 366
           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 } } }
367

thomasw's avatar
thomasw committed
368 369
canHole :: CtEvidence -> OccName -> HoleSort -> TcS (StopOrContinue Ct)
canHole ev occ hole_sort
370 371
  = 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
372 373 374 375 376
       ; 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
377

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

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
397
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
398

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

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

can_eq_nc'
418 419
   :: 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
420 421 422 423 424 425
   -> 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)
426 427

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
428 429 430 431 432
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
433
-- See Note [Eager reflexivity check]
434 435 436 437 438 439
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
440 441
  | Just (co, ty1') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
  = can_eq_newtype_nc rdr_env ev NotSwapped co ty1 ty1' ty2 ps_ty2
442
can_eq_nc' _flat rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
443 444
  | Just (co, ty2') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
  = can_eq_newtype_nc rdr_env ev IsSwapped  co ty2 ty2' ty1 ps_ty1
445 446 447 448 449 450

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

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

Austin Seipp's avatar
Austin Seipp committed
457
-- Decomposable type constructor applications
458 459 460 461 462
can_eq_nc' _flat _rdr_env _envs ev eq_rel ty1 _ ty2 _
  | Just (tc1, tys1) <- tcSplitTyConApp_maybe ty1
  , Just (tc2, tys2) <- tcSplitTyConApp_maybe ty2
  , not (isTypeFamilyTyCon tc1)
  , not (isTypeFamilyTyCon tc2)
463
  = canTyConApp ev eq_rel tc1 tys1 tc2 tys2
464

465 466
can_eq_nc' _flat _rdr_env _envs ev eq_rel
           s1@(ForAllTy {}) _ s2@(ForAllTy {}) _
467
 | CtWanted { ctev_loc = loc, ctev_evar = orig_ev } <- ev
468 469
 = do { let (tvs1,body1) = tcSplitForAllTys s1
            (tvs2,body2) = tcSplitForAllTys s2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
470
      ; if not (equalLength tvs1 tvs2) then
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
471
          canEqHardFailure ev eq_rel s1 s2
472
        else
473
          do { traceTcS "Creating implication for polytype equality" $ ppr ev
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
474 475
             ; ev_term <- deferTcSForAllEq (eqRelRole eq_rel)
                                           loc (tvs1,body1) (tvs2,body2)
476
             ; setWantedEvBind orig_ev ev_term
477
             ; stopWith ev "Deferred polytype equality" } }
478
 | otherwise
Simon Peyton Jones's avatar
Simon Peyton Jones committed
479
 = do { traceTcS "Ommitting decomposition of given polytype equality" $
480
        pprEq s1 s2    -- See Note [Do not decompose given polytype equalities]
481
      ; stopWith ev "Discard given polytype equality" }
Simon Peyton Jones's avatar
Simon Peyton Jones committed
482

483
-- See Note [Canonicalising type applications] about why we require flat types
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
484
can_eq_nc' True _rdr_env _envs ev eq_rel (AppTy t1 s1) _ ty2 _
485
  | Just (t2, s2) <- tcSplitAppTy_maybe ty2
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
486 487
  = can_eq_app ev eq_rel t1 s1 t2 s2
can_eq_nc' True _rdr_env _envs ev eq_rel ty1 _ (AppTy t2 s2) _
488
  | Just (t1, s1) <- tcSplitAppTy_maybe ty1
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
489
  = can_eq_app ev eq_rel t1 s1 t2 s2
490 491 492 493 494 495

-- 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
496
         `andWhenContinue` \ new_ev ->
497 498 499 500 501 502 503 504 505 506 507 508 509
         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
510

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
511
{-
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
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
530 531 532 533 534 535 536 537 538
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
539

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
540 541 542 543 544
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.

545 546
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
547

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
548
Here's another place where this reflexivity check is key:
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
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
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:
576 577 578
         -- 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
579 580 581 582 583 584
           -- 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 ->
585
         can_eq_nc False new_ev ReprEq ty1' ty1' ty2 ps_ty2 }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
586 587 588 589 590

-- | 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
591
  [ greUsedRdrName gre
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
592
  | dc <- tyConDataCons tc
593 594
  , gre : _  <- return $ lookupGRE_Name rdr_env (dataConName dc)
  , not (isLocalGRE gre) ]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
595

596
---------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
597
-- ^ Decompose a type application.
598
-- All input types must be flat. See Note [Canonicalising type applications]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
599 600
can_eq_app :: CtEvidence       -- :: s1 t1 ~r s2 t2
           -> EqRel            -- r
601 602 603
           -> Xi -> Xi         -- s1 t1
           -> Xi -> Xi         -- s2 t2
           -> TcS (StopOrContinue Ct)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
604 605

-- AppTys only decompose for nominal equality, so this case just leads
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
606
-- to an irreducible constraint; see typecheck/should_compile/T10494
607
-- See Note [Decomposing equality]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
608 609 610
can_eq_app ev ReprEq _ _ _ _
  = do { traceTcS "failing to decompose representational AppTy equality" (ppr ev)
       ; continueWith (CIrredEvCan { cc_ev = ev }) }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
611 612
          -- no need to call canEqFailure, because that flattens, and the
          -- types involved here are already flat
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
613 614

can_eq_app ev NomEq s1 t1 s2 t2
615
  | CtDerived { ctev_loc = loc } <- ev
616
  = do { emitNewDerivedEq loc (mkTcEqPred t1 t2)
617 618 619 620 621 622 623
       ; 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 }
624 625
  | CtGiven { ctev_evar = evar, ctev_loc = loc } <- ev
  = do { let co   = mkTcCoVarCo evar
626 627 628 629 630 631 632 633
             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"
634

Simon Peyton Jones's avatar
Simon Peyton Jones committed
635
------------------------
636 637 638 639
canTyConApp :: CtEvidence -> EqRel
            -> TyCon -> [TcType]
            -> TyCon -> [TcType]
            -> TcS (StopOrContinue Ct)
640
-- See Note [Decomposing TyConApps]
641
canTyConApp ev eq_rel tc1 tys1 tc2 tys2
642
  | tc1 == tc2
643
  , length tys1 == length tys2
644
  = do { inerts <- getTcSInerts
645 646
       ; if can_decompose inerts
         then do { traceTcS "canTyConApp"
647 648 649 650
                       (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 }
651

652 653
  -- Fail straight away for better error messages
  -- See Note [Use canEqFailure in canDecomposableTyConApp]
654 655
  | eq_rel == ReprEq && not (isGenerativeTyCon tc1 Representational &&
                             isGenerativeTyCon tc2 Representational)
656 657 658 659 660 661 662
  = canEqFailure ev eq_rel ty1 ty2
  | otherwise
  = canEqHardFailure ev eq_rel ty1 ty2
  where
    ty1 = mkTyConApp tc1 tys1
    ty2 = mkTyConApp tc2 tys2

663 664 665
    loc  = ctEvLoc ev
    pred = ctEvPred ev

666 667 668 669 670
     -- See Note [Decomposing equality]
    can_decompose inerts
      =  isInjectiveTyCon tc1 (eqRelRole eq_rel)
      || (ctEvFlavour ev /= Given && isEmptyBag (matchableGivens loc pred inerts))

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
671 672 673 674 675
{-
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
676
Here is one case:
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
677 678 679 680 681

  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
682
Suppose we are canonicalising (Int ~R DF (TF a)), where we don't yet
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
683 684
know `a`. This is *not* a hard failure, because we might soon learn
that `a` is, in fact, Char, and then the equality succeeds.
685

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
686 687
Here is another case:

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
688
  [G] Age ~R Int
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
689 690 691 692

where Age's constructor is not in scope. We don't want to report
an "inaccessible code" error in the context of this Given!

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
693 694 695 696 697 698 699 700 701 702
For example, see typecheck/should_compile/T10493, repeated here:

  import Data.Ord (Down)  -- no constructor

  foo :: Coercible (Down Int) Int => Down Int -> Int
  foo = coerce

That should compile, but only because we use canEqFailure and not
canEqHardFailure.

703 704
Note [Decomposing newtypes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
Decomposing newtypes is a dangerous business. Here is a representative example
of why:

  newtype Nt a = Mk Bool         -- NB: a is not used in the RHS,
  type role Nt representational  -- but the user gives it an R role anyway

If we have [W] Nt alpha ~R Nt beta, we *don't* want to decompose to
[W] alpha ~R beta, because it's possible that alpha and beta aren't
representationally equal. So we really want to unwrap newtypes first,
which is what is done in can_eq_nc'.
It all comes from the fact that newtypes aren't necessarily injective w.r.t.
representational equality.

Furthermore, as explained in Note [NthCo and newtypes] in Coercion, we can't use
NthCo on representational coercions over newtypes. NthCo comes into play
only when decomposing givens. So we avoid decomposing representational given
equalities over newtypes.
722

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
723
But is it ever sensible to decompose *Wanted* constraints over newtypes? Yes, as
724 725 726 727 728 729 730 731
long as there are no Givens that might (later) influence Coercible solving.
(See Note [Instance and Given overlap] in TcInteract.) 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
732 733 734 735 736 737 738 739 740 741 742 743 744 745

Example of how a given might influence this decision-making:

  [G] alpha ~R beta
  [W] Nt Int ~R Nt gamma

where Nt is a newtype whose constructor is not in scope, and its parameter
is representational. Decomposing to [W] Int ~R gamma seems sensible, but it's
just possible that the given above will become informative and that we shouldn't
decompose. If we have `newtype Nt a = Mk Bool`, then there might be well-formed
evidence that (Nt Int ~R Nt Char), even if we can't form that evidence in this
module (because Mk is not in scope). Creating this scenario in source Haskell
is challenging; there is no test case.

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 817 818 819 820 821 822 823 824 825 826 827 828

Note [Decomposing equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have a constraint (of any flavour and role) that looks like
T tys1 ~ T tys2, what can we conclude about tys1 and tys2? The answer,
of course, is "it depends". This Note spells it all out.

In this Note, "decomposition" refers to taking the constraint
  [fl] (T tys1 ~X T tys2)
(for some flavour fl and some role X) and replacing it with
  [fls'] (tys1 ~Xs' tys2)
where that notation indicates a list of new constraints, where the
new constraints may have different flavours and different roles.

The key property to consider is injectivity. When decomposing a Given the
decomposition is sound if and only if T is injective in all of its type
arguments. When decomposing a Wanted, the decomposition is sound (assuming the
correct roles in the produced equality constraints), but it may be a guess --
that is, an unforced decision by the constraint solver. Decomposing Wanteds
over injective TyCons does not entail guessing. But sometimes we want to
decompose a Wanted even when the TyCon involved is not injective! (See below.)

So, in broad strokes, we want this rule:

(*) Decompose a constraint (T tys1 ~X T tys2) if and only if T is injective
at role X.

Pursuing the details requires exploring three axes:
* Flavour: Given vs. Derived vs. Wanted
* Role: Nominal vs. Representational
* TyCon species: datatype vs. newtype vs. data family vs. type family vs. type variable

(So a type variable isn't a TyCon, but it's convenient to put the AppTy case
in the same table.)

Right away, we can say that Derived behaves just as Wanted for the purposes
of decomposition. The difference between Derived and Wanted is the handling of
evidence. Since decomposition in these cases isn't a matter of soundness but of
guessing, we want the same behavior regardless of evidence.

Here is a table (discussion following) detailing where decomposition is allowed:

NOMINAL               GIVEN                       WANTED

Datatype               YES                         YES
Newtype                YES                         YES
Data family            YES                         YES
Type family            YES, in injective args{1}   YES, in injective args{1}
Type variable          YES                         YES

REPRESENTATIONAL      GIVEN                       WANTED

Datatype               YES                         YES
Newtype                NO{2}                      MAYBE{2}
Data family            NO{3}                      MAYBE{3}
Type family             NO                          NO
Type variable          NO{4}                       NO{4}

{1}: Type families can be injective in some, but not all, of their arguments,
so we want to do partial decomposition. This is quite different than the way
other decomposition is done, where the decomposed equalities replace the original
one. We thus proceed much like we do with superclasses: emitting new Givens
when "decomposing" a partially-injective type family Given and new Deriveds
when "decomposing" a partially-injective type family Wanted. (As of the time of
writing, 13 June 2015, the implementation of injective type families has not
been merged, but it should be soon. Please delete this parenthetical if the
implementation is indeed merged.)

{2}: See Note [Decomposing newtypes]

{3}: Because of the possibility of newtype instances, we must treat data families
like newtypes. See also Note [Decomposing newtypes].

{4}: Because type variables can stand in for newtypes, we conservatively do not
decompose AppTys over representational equality.

In the implementation of can_eq_nc and friends, we don't directly pattern
match using lines like in the tables above, as those tables don't cover
all cases (what about PrimTyCon? tuples?). Instead we just ask about injectivity,
boiling the tables above down to rule (*). The exceptions to rule (*) are for
injective type families, which are handled separately from other decompositions,
and the MAYBE entries above.

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
829 830 831
-}

canDecomposableTyConAppOK :: CtEvidence -> EqRel
832
                          -> TyCon -> [TcType] -> [TcType]
833 834
                          -> TcS ()
-- Precondition: tys1 and tys2 are the same length, hence "OK"
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
835
canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
836 837
  = case ev of
     CtDerived { ctev_loc = loc }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
838
        -> unifyDeriveds loc tc_roles tys1 tys2
839 840

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

844 845
     CtGiven { ctev_evar = evar, ctev_loc = loc }
        -> do { let ev_co = mkTcCoVarCo evar
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
846 847 848 849 850
              ; 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 ]
851 852
              ; emitWorkNC given_evs }
  where
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
853 854 855 856 857
    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.
858
-- Examples in Note [Use canEqFailure in canDecomposableTyConApp]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
859 860 861
canEqFailure :: CtEvidence -> EqRel
             -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure ev ReprEq ty1 ty2
862
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
863 864 865
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
       ; traceTcS "canEqFailure with ReprEq" $
         vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
866 867 868
       ; rewriteEqEvidence ev ReprEq NotSwapped xi1 xi2 co1 co2
         `andWhenContinue` \ new_ev ->
         continueWith (CIrredEvCan { cc_ev = new_ev }) }
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
869 870 871 872 873
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)
874
-- See Note [Make sure that insolubles are fully rewritten]
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
875
canEqHardFailure ev eq_rel ty1 ty2
876 877
  = 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
878 879 880 881
       ; rewriteEqEvidence ev eq_rel NotSwapped s1 s2 co1 co2
         `andWhenContinue` \ new_ev ->
    do { emitInsoluble (mkNonCanonical new_ev)
       ; stopWith new_ev "Definitely not equal" }}
882

Austin Seipp's avatar
Austin Seipp committed
883
{-
884 885 886 887 888 889 890 891 892 893 894 895 896
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.

897 898 899
Note [Canonicalising type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (s1 t1) ~ ty2, how should we proceed?
Austin Seipp's avatar
Austin Seipp committed
900
The simple things is to see if ty2 is of form (s2 t2), and
901
decompose.  By this time s1 and s2 can't be saturated type
Austin Seipp's avatar
Austin Seipp committed
902 903
function applications, because those have been dealt with
by an earlier equation in can_eq_nc, so it is always sound to
904 905
decompose.

Austin Seipp's avatar
Austin Seipp committed
906
However, over-eager decomposition gives bad error messages
907 908 909 910 911 912 913
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
914
we get an error        "Can't match Array ~ Maybe",
915 916
but we'd prefer to get "Can't match Array b ~ Maybe c".

917 918 919
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.
920

921 922
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
923 924
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
925 926 927
 (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
928
And if we don't do this there is a bad danger that
929 930 931
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.

932
Note [Do not decompose Given polytype equalities]
933 934
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
935
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
936
this given evidence.
937 938


939 940 941 942 943 944 945 946 947 948 949 950 951
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
952 953 954 955 956 957 958 959 960 961 962

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

963 964 965 966
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
967

Austin Seipp's avatar
Austin Seipp committed
968
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
969

Austin Seipp's avatar
Austin Seipp committed
970
canCFunEqCan :: CtEvidence
971
             -> TyCon -> [TcType]   -- LHS
972 973
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
974 975
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
976 977 978
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
979
  = do { (tys', cos) <- flattenManyNom ev tys
980 981 982 983 984
                        -- 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
985 986 987 988
       ; 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')
989
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
990
                                 , cc_tyargs = tys', cc_fsk = fsk }) } }
991 992

---------------------
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
993
canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
994 995
           -> TcTyVar             -- already flat
           -> TcType              -- already flat
996
           -> TcS (StopOrContinue Ct)
997
-- A TyVar on LHS, but so far un-zonked
998 999 1000
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
1001 1002 1003 1004
         -- 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
1005
       ; canEqTyVar2 dflags ev eq_rel swapped tv1 ps_ty2 }
1006 1007

canEqTyVar2 :: DynFlags
1008
            -> CtEvidence   -- lhs ~ rhs (or, if swapped, orhs ~ olhs)
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
1009
            -> EqRel
1010
            -> SwapFlag
1011 1012
            -> TcTyVar      -- lhs, flat
            -> TcType       -- rhs, flat
1013
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
1014
-- LHS is an inert type variable,
1015
-- and RHS is fully rewritten, but with type synonyms
1016
-- preserved as much as possible
1017

1018
canEqTyVar2 dflags ev eq_rel swapped tv1 xi2
1019
  | Just tv2 <- getTyVar_maybe xi2
1020
  = canEqTyVarTyVar ev eq_rel swapped tv1 tv2
1021

1022
  | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2  -- No occurs check
1023