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

3 4 5 6 7 8
module TcCanonical( 
     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
22 23 24
import Coercion
import FamInstEnv ( FamInstEnvs )
import FamInst ( tcTopNormaliseNewTypeTF_maybe )
25
import Var
26 27
import DataCon ( dataConName )
import Name( isSystemName, nameOccName )
28
import OccName( OccName )
29
import Outputable
30
import Control.Monad
31
import DynFlags( DynFlags )
32
import VarSet
33
import RdrName
34

35
import Pair
36
import Util
37 38
import MonadUtils ( zipWith3M, zipWith3M_ )
import Data.List  ( zip4 )
39
import BasicTypes
40
import Data.Maybe ( isJust )
41
import FastString
42

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

50 51
Note [Canonicalization]
~~~~~~~~~~~~~~~~~~~~~~~
52

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

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

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

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

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

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

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

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

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

93 94 95 96 97
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
98

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

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

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

112 113
   - 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
114
             d1 := d2
115 116
     and end up in a loop!

117 118 119 120 121 122 123 124
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.
125

126 127 128 129 130 131 132
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
133
-}
134

135 136 137
-- Top-level canonicalization
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

144
canonicalize (CDictCan { cc_ev = ev
145 146
                       , cc_class  = cls
                       , cc_tyargs = xis })
147
  = {-# SCC "canClass" #-}
148 149
    canClass ev cls xis -- Do not add any superclasses
canonicalize (CTyEqCan { cc_ev = ev
150
                       , cc_tyvar  = tv
151 152
                       , cc_rhs    = xi
                       , cc_eq_rel = eq_rel })
153
  = {-# SCC "canEqLeafTyVarEq" #-}
154
    canEqTyVar ev eq_rel NotSwapped tv xi xi
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
172 173 174 175 176 177 178 179
      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
      TuplePred tys         -> do traceTcS "canEvNC:tup" (ppr tys)
                                  canTuple   ev tys
      IrredPred {}          -> do traceTcS "canEvNC:irred" (ppr (ctEvPred ev))
                                  canIrred   ev
Austin Seipp's avatar
Austin Seipp committed
180 181 182 183 184 185 186
{-
************************************************************************
*                                                                      *
*                      Tuple Canonicalization
*                                                                      *
************************************************************************
-}
187

188
canTuple :: CtEvidence -> [PredType] -> TcS (StopOrContinue Ct)
189
canTuple ev tys
dimitris's avatar
dimitris committed
190 191
  = do { traceTcS "can_pred" (text "TuplePred!")
       ; let xcomp = EvTupleMk
Simon Peyton Jones's avatar
Simon Peyton Jones committed
192
             xdecomp x = zipWith (\_ i -> EvTupleSel x i) tys [0..]
193 194
       ; xCtEvidence ev (XEvTerm tys xcomp xdecomp)
       ; stopWith ev "Decomposed tuple constraint" }
195

Austin Seipp's avatar
Austin Seipp committed
196 197 198 199 200 201 202
{-
************************************************************************
*                                                                      *
*                      Class Canonicalization
*                                                                      *
************************************************************************
-}
203

Simon Peyton Jones's avatar
Simon Peyton Jones committed
204
canClass, canClassNC
205
   :: CtEvidence
206
   -> Class -> [Type] -> TcS (StopOrContinue Ct)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
207
-- Precondition: EvVar is class evidence
208 209 210 211 212 213

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

214 215
canClassNC ev cls tys
  = canClass ev cls tys
216 217
    `andWhenContinue` emitSuperclasses

218
canClass ev cls tys
219 220 221
  =   -- all classes do *nominal* matching
    ASSERT2( ctEvRole ev == Nominal, ppr ev $$ ppr cls $$ ppr tys )
    do { (xis, cos) <- flattenMany FM_FlattenAll ev (repeat Nominal) tys
Joachim Breitner's avatar
Joachim Breitner committed
222
       ; let co = mkTcTyConAppCo Nominal (classTyCon cls) cos
223
             xi = mkClassPred cls xis
224 225
             mk_ct new_ev = CDictCan { cc_ev = new_ev
                                     , cc_tyargs = xis, cc_class = cls }
226
       ; mb <- rewriteEvidence ev xi co
Simon Peyton Jones's avatar
Simon Peyton Jones committed
227
       ; traceTcS "canClass" (vcat [ ppr ev <+> ppr cls <+> ppr tys
Simon Peyton Jones's avatar
Simon Peyton Jones committed
228
                                   , ppr xi, ppr mb ])
229
       ; return (fmap mk_ct mb) }
dimitris's avatar
dimitris committed
230

231
emitSuperclasses :: Ct -> TcS (StopOrContinue Ct)
232
emitSuperclasses ct@(CDictCan { cc_ev = ev , cc_tyargs = xis_new, cc_class = cls })
Simon Peyton Jones's avatar
Simon Peyton Jones committed
233 234
            -- Add superclasses of this one here, See Note [Adding superclasses].
            -- But only if we are not simplifying the LHS of a rule.
235
 = do { newSCWorkFromFlavored ev cls xis_new
Simon Peyton Jones's avatar
Simon Peyton Jones committed
236
      -- Arguably we should "seq" the coercions if they are derived,
237
      -- as we do below for emit_kind_constraint, to allow errors in
Simon Peyton Jones's avatar
Simon Peyton Jones committed
238
      -- superclasses to be executed if deferred to runtime!
239 240
      ; continueWith ct }
emitSuperclasses _ = panic "emit_superclasses of non-class!"
241

Austin Seipp's avatar
Austin Seipp committed
242
{-
243
Note [Adding superclasses]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
244
~~~~~~~~~~~~~~~~~~~~~~~~~~
245 246 247 248 249 250
Since dictionaries are canonicalized only once in their lifetime, the
place to add their superclasses is canonicalisation (The alternative
would be to do it during constraint solving, but we'd have to be
extremely careful to not repeatedly introduced the same superclass in
our worklist). Here is what we do:

Simon Peyton Jones's avatar
Simon Peyton Jones committed
251 252
For Givens:
       We add all their superclasses as Givens.
253

Simon Peyton Jones's avatar
Simon Peyton Jones committed
254 255
For Wanteds:
       Generally speaking we want to be able to add superclasses of
256
       wanteds for two reasons:
257

Simon Peyton Jones's avatar
Simon Peyton Jones committed
258 259 260 261 262 263 264 265 266
       (1) Oportunities for improvement. Example:
                  class (a ~ b) => C a b
           Wanted constraint is: C alpha beta
           We'd like to simply have C alpha alpha. Similar
           situations arise in relation to functional dependencies.

       (2) To have minimal constraints to quantify over:
           For instance, if our wanted constraint is (Eq a, Ord a)
           we'd only like to quantify over Ord a.
267

268
       To deal with (1) above we only add the superclasses of wanteds
Simon Peyton Jones's avatar
Simon Peyton Jones committed
269 270
       which may lead to improvement, that is: equality superclasses or
       superclasses with functional dependencies.
271

Simon Peyton Jones's avatar
Simon Peyton Jones committed
272 273
       We deal with (2) completely independently in TcSimplify. See
       Note [Minimize by SuperClasses] in TcSimplify.
274 275


Simon Peyton Jones's avatar
Simon Peyton Jones committed
276 277 278 279
       Moreover, in all cases the extra improvement constraints are
       Derived. Derived constraints have an identity (for now), but
       we don't do anything with their evidence. For instance they
       are never used to rewrite other constraints.
280

Simon Peyton Jones's avatar
Simon Peyton Jones committed
281
       See also [New Wanted Superclass Work] in TcInteract.
282

283

Simon Peyton Jones's avatar
Simon Peyton Jones committed
284
For Deriveds:
285
       We do nothing.
286 287 288

Here's an example that demonstrates why we chose to NOT add
superclasses during simplification: [Comes from ticket #4497]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
289

290 291 292
   class Num (RealOf t) => Normed t
   type family RealOf x

Simon Peyton Jones's avatar
Simon Peyton Jones committed
293 294 295 296 297 298 299 300 301 302 303
Assume the generated wanted constraint is:
   RealOf e ~ e, Normed e
If we were to be adding the superclasses during simplification we'd get:
   Num uf, Normed e, RealOf e ~ e, RealOf e ~ uf
==>
   e ~ uf, Num uf, Normed e, RealOf e ~ e
==> [Spontaneous solve]
   Num uf, Normed uf, RealOf uf ~ uf

While looks exactly like our original constraint. If we add the superclass again we'd loop.
By adding superclasses definitely only once, during canonicalisation, this situation can't
304
happen.
Austin Seipp's avatar
Austin Seipp committed
305
-}
306

307
newSCWorkFromFlavored :: CtEvidence -> Class -> [Xi] -> TcS ()
308
-- Returns superclasses, see Note [Adding superclasses]
309
newSCWorkFromFlavored flavor cls xis
Simon Peyton Jones's avatar
Simon Peyton Jones committed
310
  | isDerived flavor
311
  = return ()  -- Deriveds don't yield more superclasses because we will
Simon Peyton Jones's avatar
Simon Peyton Jones committed
312 313 314 315 316
               -- add them transitively in the case of wanteds.

  | isGiven flavor
  = do { let sc_theta = immSuperClasses cls xis
             xev_decomp x = zipWith (\_ i -> EvSuperClass x i) sc_theta [0..]
317 318
             xev = XEvTerm { ev_preds  =  sc_theta
                           , ev_comp   = panic "Can't compose for given!"
319
                           , ev_decomp = xev_decomp }
320
       ; xCtEvidence flavor xev }
dimitris's avatar
dimitris committed
321 322

  | isEmptyVarSet (tyVarsOfTypes xis)
323
  = return () -- Wanteds with no variables yield no deriveds.
324
              -- See Note [Improvement from Ground Wanteds]
325

Simon Peyton Jones's avatar
Simon Peyton Jones committed
326 327
  | otherwise -- Wanted case, just add those SC that can lead to improvement.
  = do { let sc_rec_theta = transSuperClasses cls xis
328
             impr_theta   = filter is_improvement_pty sc_rec_theta
329
             loc          = ctEvLoc flavor
330
       ; traceTcS "newSCWork/Derived" $ text "impr_theta =" <+> ppr impr_theta
331
       ; mapM_ (emitNewDerived loc) impr_theta }
332

Simon Peyton Jones's avatar
Simon Peyton Jones committed
333
is_improvement_pty :: PredType -> Bool
334
-- Either it's an equality, or has some functional dependency
335
is_improvement_pty ty = go (classifyPredType ty)
batterseapower's avatar
batterseapower committed
336
  where
337 338
    go (EqPred NomEq t1 t2) = not (t1 `tcEqType` t2)
    go (EqPred ReprEq _ _)  = False
339
    go (ClassPred cls _tys) = not $ null fundeps
340 341 342
                            where (_,fundeps) = classTvsFds cls
    go (TuplePred ts)       = any is_improvement_pty ts
    go (IrredPred {})       = True -- Might have equalities after reduction?
343

Austin Seipp's avatar
Austin Seipp committed
344 345 346 347 348 349 350
{-
************************************************************************
*                                                                      *
*                      Irreducibles canonicalization
*                                                                      *
************************************************************************
-}
351

352
canIrred :: CtEvidence -> TcS (StopOrContinue Ct)
353
-- Precondition: ty not a tuple and no other evidence form
354
canIrred old_ev
Simon Peyton Jones's avatar
Simon Peyton Jones committed
355 356
  = do { let old_ty = ctEvPred old_ev
       ; traceTcS "can_pred" (text "IrredPred = " <+> ppr old_ty)
357
       ; (xi,co) <- flatten FM_FlattenAll old_ev old_ty -- co :: xi ~ old_ty
358
       ; rewriteEvidence old_ev xi co `andWhenContinue` \ new_ev ->
359 360
    do { -- Re-classify, in case flattening has improved its shape
       ; case classifyPredType (ctEvPred new_ev) of
361 362 363 364 365
           ClassPred cls tys     -> canClassNC new_ev cls tys
           TuplePred tys         -> canTuple   new_ev 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
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" } }
376

Austin Seipp's avatar
Austin Seipp committed
377 378 379 380 381 382 383
{-
************************************************************************
*                                                                      *
*        Equalities
*                                                                      *
************************************************************************
-}
384

385 386 387
canEqNC :: CtEvidence -> EqRel -> Type -> Type -> TcS (StopOrContinue Ct)
canEqNC ev eq_rel ty1 ty2
  = can_eq_nc ev eq_rel ty1 ty1 ty2 ty2
388

389
can_eq_nc
Austin Seipp's avatar
Austin Seipp committed
390
   :: CtEvidence
391
   -> EqRel
Austin Seipp's avatar
Austin Seipp committed
392 393
   -> Type -> Type    -- LHS, after and before type-synonym expansion, resp
   -> Type -> Type    -- RHS, after and before type-synonym expansion, resp
394
   -> TcS (StopOrContinue Ct)
395
can_eq_nc ev eq_rel ty1 ps_ty1 ty2 ps_ty2
Austin Seipp's avatar
Austin Seipp committed
396
  = do { traceTcS "can_eq_nc" $
397 398 399 400 401 402 403 404 405 406 407 408 409
         vcat [ ppr ev, ppr eq_rel, ppr ty1, ppr ps_ty1, ppr ty2, ppr ps_ty2 ]
       ; rdr_env <- getGlobalRdrEnvTcS
       ; fam_insts <- getFamInstEnvs
       ; can_eq_nc' rdr_env fam_insts ev eq_rel ty1 ps_ty1 ty2 ps_ty2 }

can_eq_nc'
   :: GlobalRdrEnv   -- needed to see which newtypes are in scope
   -> 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)
410 411

-- Expand synonyms first; see Note [Type synonyms and canonicalization]
412 413 414
can_eq_nc' _rdr_env _envs ev eq_rel ty1 ps_ty1 ty2 ps_ty2
  | Just ty1' <- tcView ty1 = can_eq_nc ev eq_rel ty1' ps_ty1 ty2  ps_ty2
  | Just ty2' <- tcView ty2 = can_eq_nc ev eq_rel ty1  ps_ty1 ty2' ps_ty2
415

416 417 418
-- Type family on LHS or RHS take priority over tyvars,
-- so that  tv ~ F ty gets flattened
-- Otherwise  F a ~ F a  might not get solved!
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
can_eq_nc' _rdr_env _envs ev eq_rel (TyConApp fn1 tys1) _ ty2 ps_ty2
  | isTypeFamilyTyCon fn1
  = can_eq_fam_nc ev eq_rel NotSwapped fn1 tys1 ty2 ps_ty2
can_eq_nc' _rdr_env _envs ev eq_rel ty1 ps_ty1 (TyConApp fn2 tys2) _
  | isTypeFamilyTyCon fn2
  = can_eq_fam_nc ev eq_rel IsSwapped fn2 tys2 ty1 ps_ty1

-- When working with ReprEq, unwrap newtypes next.
-- Otherwise, a ~ Id a wouldn't get solved
can_eq_nc' rdr_env envs ev ReprEq ty1 _ ty2 ps_ty2
  | Just (co, ty1') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty1
  = can_eq_newtype_nc rdr_env ev NotSwapped co ty1 ty1' ty2 ps_ty2
can_eq_nc' rdr_env envs ev ReprEq ty1 ps_ty1 ty2 _
  | Just (co, ty2') <- tcTopNormaliseNewTypeTF_maybe envs rdr_env ty2
  = can_eq_newtype_nc rdr_env ev IsSwapped  co ty2 ty2' ty1 ps_ty1
434 435

-- Type variable on LHS or RHS are next
436 437 438 439
can_eq_nc' _rdr_env _envs ev eq_rel (TyVarTy tv1) _ ty2 ps_ty2
  = canEqTyVar ev eq_rel NotSwapped tv1 ty2 ps_ty2
can_eq_nc' _rdr_env _envs ev eq_rel ty1 ps_ty1 (TyVarTy tv2) _
  = canEqTyVar ev eq_rel IsSwapped tv2 ty1 ps_ty1
440 441 442 443 444 445

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

-- Literals
446
can_eq_nc' _rdr_env _envs ev eq_rel ty1@(LitTy l1) _ (LitTy l2) _
447 448
 | l1 == l2
  = do { when (isWanted ev) $
449 450
         setEvBind (ctev_evar ev) (EvCoercion $
                                   mkTcReflCo (eqRelRole eq_rel) ty1)
451
       ; stopWith ev "Equal LitTy" }
452

Austin Seipp's avatar
Austin Seipp committed
453
-- Decomposable type constructor applications
454
-- Synonyms and type functions (which are not decomposable)
Austin Seipp's avatar
Austin Seipp committed
455
-- have already been dealt with
456
can_eq_nc' _rdr_env _envs ev eq_rel (TyConApp tc1 tys1) _ (TyConApp tc2 tys2) _
457 458
  | isDecomposableTyCon tc1
  , isDecomposableTyCon tc2
459
  = canDecomposableTyConApp ev eq_rel tc1 tys1 tc2 tys2
460

461
can_eq_nc' _rdr_env _envs ev eq_rel (TyConApp tc1 _) ps_ty1 (FunTy {}) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
462
  | isDecomposableTyCon tc1
463 464 465
      -- 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
466
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
467

468 469
can_eq_nc' _rdr_env _envs ev eq_rel (FunTy s1 t1) _ (FunTy s2 t2) _
  = do { canDecomposableTyConAppOK ev eq_rel funTyCon [s1,t1] [s2,t2]
470 471
       ; stopWith ev "Decomposed FunTyCon" }

472
can_eq_nc' _rdr_env _envs ev eq_rel (FunTy {}) ps_ty1 (TyConApp tc2 _) ps_ty2
Austin Seipp's avatar
Austin Seipp committed
473
  | isDecomposableTyCon tc2
474
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
475

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

493 494 495 496 497 498
can_eq_nc' _rdr_env _envs ev eq_rel (AppTy {}) ps_ty1 _ ps_ty2
  | isGiven ev = try_decompose_app ev eq_rel ps_ty1 ps_ty2
  | otherwise  = can_eq_wanted_app ev eq_rel ps_ty1 ps_ty2
can_eq_nc' _rdr_env _envs ev eq_rel _ ps_ty1 (AppTy {}) ps_ty2
  | isGiven ev = try_decompose_app ev eq_rel ps_ty1 ps_ty2
  | otherwise  = can_eq_wanted_app ev eq_rel ps_ty1 ps_ty2
499 500

-- Everything else is a definite type error, eg LitTy ~ TyConApp
501 502
can_eq_nc' _rdr_env _envs ev eq_rel _ ps_ty1 _ ps_ty2
  = canEqHardFailure ev eq_rel ps_ty1 ps_ty2
503

504
------------
505
can_eq_fam_nc :: CtEvidence -> EqRel -> SwapFlag
506 507 508 509 510 511
              -> TyCon -> [TcType]
              -> TcType -> TcType
              -> TcS (StopOrContinue Ct)
-- Canonicalise a non-canonical equality of form (F tys ~ ty)
--   or the swapped version thereof
-- Flatten both sides and go round again
512
can_eq_fam_nc ev eq_rel swapped fn tys rhs ps_rhs
513
  = do { (xi_lhs, co_lhs) <- flattenFamApp FM_FlattenAll ev fn tys
514 515 516 517
       ; rewriteEqEvidence ev eq_rel swapped xi_lhs rhs co_lhs
                           (mkTcReflCo (eqRelRole eq_rel) rhs)
         `andWhenContinue` \ new_ev ->
         can_eq_nc new_ev eq_rel xi_lhs xi_lhs rhs ps_rhs }
518

519 520 521 522 523 524 525 526 527 528
{-
Note [Eager reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have

  newtype X = MkX (Int -> X)

and

  [W] X ~R X
529

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
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.

As an alternative, suppose we also have

  newtype Y = MkY (Int -> Y)

and now wish to prove

  [W] X ~R Y

This new 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 of the stack-blowing check in can_eq_newtype_nc, along
with the fact that rewriteEqEvidence bumps the stack depth.

Note [AppTy reflexivity check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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:
         -- See Note [Eager reflexivity check] for an example of
         -- when this is necessary
       ; dflags <- getDynFlags
       ; if isJust $ subGoalDepthExceeded (maxSubGoalDepth dflags)
                                          (ctLocDepth (ctEvLoc ev))
         then do { emitInsoluble (mkNonCanonical ev)
                 ; stopWith ev "unwrapping newtypes blew stack" }
         else do
       { if ty1 `eqType` ty2   -- See Note [Eager reflexivity check]
         then canEqReflexive ev ReprEq ty1
         else do
       { markDataConsAsUsed rdr_env (tyConAppTyCon ty1)
           -- 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 ->
         can_eq_nc new_ev ReprEq ty1' ty1' ty2 ps_ty2 }}}

-- | 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
  [ mkRdrQual (is_as (is_decl imp_spec)) occ
  | dc <- tyConDataCons tc
  , let dc_name = dataConName dc
        occ  = nameOccName dc_name
  , gre : _               <- return $ lookupGRE_Name rdr_env dc_name
  , Imported (imp_spec:_) <- return $ gre_prov gre ]

-------------------------------------------------
can_eq_wanted_app :: CtEvidence -> EqRel -> TcType -> TcType
613 614 615
                  -> TcS (StopOrContinue Ct)
-- One or the other is an App; neither is a type variable
-- See Note [Canonicalising type applications]
616
can_eq_wanted_app ev eq_rel ty1 ty2
617 618
  = do { (xi1, co1) <- flatten FM_FlattenAll ev ty1
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
619 620 621
        ; rewriteEqEvidence ev eq_rel NotSwapped xi1 xi2 co1 co2
          `andWhenContinue` \ new_ev ->
          try_decompose_app new_ev eq_rel xi1 xi2 }
622

623 624
try_decompose_app :: CtEvidence -> EqRel
                  -> TcType -> TcType -> TcS (StopOrContinue Ct)
625 626 627 628
-- Preconditions: neither is a type variable
--                so can't turn it into an application if it
--                   doesn't look like one already
-- See Note [Canonicalising type applications]
629 630 631
try_decompose_app ev NomEq  ty1 ty2
  = try_decompose_nom_app ev ty1 ty2

632 633 634 635 636 637 638 639 640 641 642 643 644
try_decompose_app ev ReprEq ty1 ty2
  | ty1 `eqType` ty2   -- See Note [AppTy reflexivity check]
  = canEqReflexive ev ReprEq ty1

  | otherwise
  = canEqFailure ev ReprEq ty1 ty2

try_decompose_nom_app :: CtEvidence
                      -> TcType -> TcType -> TcS (StopOrContinue Ct)
-- Preconditions: like try_decompose_app, but also
--                ev has a nominal role
-- See Note [Canonicalising type applications]
try_decompose_nom_app ev ty1 ty2
645 646
   | AppTy s1 t1  <- ty1
   = case tcSplitAppTy_maybe ty2 of
647
       Nothing      -> canEqHardFailure ev NomEq ty1 ty2
648 649 650 651
       Just (s2,t2) -> do_decompose s1 t1 s2 t2

   | AppTy s2 t2 <- ty2
   = case tcSplitAppTy_maybe ty1 of
652
       Nothing      -> canEqHardFailure ev NomEq ty1 ty2
653 654 655
       Just (s1,t1) -> do_decompose s1 t1 s2 t2

   | otherwise  -- Neither is an AppTy
656
   = canEqNC ev NomEq ty1 ty2
657 658
   where
     -- do_decompose is like xCtEvidence, but recurses
659
     -- to try_decompose_nom_app to decompose a chain of AppTys
660 661 662
     do_decompose s1 t1 s2 t2
       | CtDerived { ctev_loc = loc } <- ev
       = do { emitNewDerived loc (mkTcEqPred t1 t2)
663
            ; canEqNC ev NomEq s1 s2 }
664
       | CtWanted { ctev_evar = evar, ctev_loc = loc } <- ev
665
       = do { ev_s <- newWantedEvVarNC loc (mkTcEqPred s1 s2)
666
            ; co_t <- unifyWanted loc Nominal t1 t2
667
            ; let co = mkTcAppCo (ctEvCoercion ev_s) co_t
668
            ; setEvBind evar (EvCoercion co)
669
            ; canEqNC ev_s NomEq s1 s2 }
670 671 672 673 674 675 676
       | CtGiven { ctev_evtm = ev_tm, ctev_loc = loc } <- ev
       = do { let co   = evTermCoercion ev_tm
                  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]
677
            ; canEqNC evar_s NomEq s1 s2 }
678 679
       | otherwise  -- Can't happen
       = error "try_decompose_app"
680

681
------------------------
682
canDecomposableTyConApp :: CtEvidence -> EqRel
Simon Peyton Jones's avatar
Simon Peyton Jones committed
683 684
                        -> TyCon -> [TcType]
                        -> TyCon -> [TcType]
685
                        -> TcS (StopOrContinue Ct)
686
-- See Note [Decomposing TyConApps]
687
canDecomposableTyConApp ev eq_rel tc1 tys1 tc2 tys2
688 689
  | tc1 /= tc2 || length tys1 /= length tys2
    -- Fail straight away for better error messages
690 691 692 693 694 695 696 697
  = let eq_failure
          | isDataFamilyTyCon tc1 || isDataFamilyTyCon tc2
                -- See Note [Use canEqFailure in canDecomposableTyConApp]
          = canEqFailure
          | otherwise
          = canEqHardFailure in
    eq_failure ev eq_rel (mkTyConApp tc1 tys1) (mkTyConApp tc2 tys2)

698
  | otherwise
699 700 701
  = do { traceTcS "canDecomposableTyConApp"
                  (ppr ev $$ ppr eq_rel $$ ppr tc1 $$ ppr tys1 $$ ppr tys2)
       ; canDecomposableTyConAppOK ev eq_rel tc1 tys1 tys2
702
       ; stopWith ev "Decomposed TyConApp" }
703

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
{-
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.
-}

canDecomposableTyConAppOK :: CtEvidence -> EqRel
721
                          -> TyCon -> [TcType] -> [TcType]
722 723
                          -> TcS ()
-- Precondition: tys1 and tys2 are the same length, hence "OK"
724
canDecomposableTyConAppOK ev eq_rel tc tys1 tys2
725 726
  = case ev of
     CtDerived { ctev_loc = loc }
727
        -> unifyDeriveds loc tc_roles tys1 tys2
728 729

     CtWanted { ctev_evar = evar, ctev_loc = loc }
730 731
        -> do { cos <- zipWith3M (unifyWanted loc) tc_roles tys1 tys2
              ; setEvBind evar (EvCoercion (mkTcTyConAppCo role tc cos)) }
732 733

     CtGiven { ctev_evtm = ev_tm, ctev_loc = loc }
734 735 736 737 738 739
        -> do { let ev_co = evTermCoercion ev_tm
              ; 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 ]
740 741
              ; emitWorkNC given_evs }
  where
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    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.
-- Examples in Note [Flatten irreducible representational equalities]
canEqFailure :: CtEvidence -> EqRel
             -> TcType -> TcType -> TcS (StopOrContinue Ct)
canEqFailure ev ReprEq ty1 ty2
  = do { -- See Note [Flatten irreducible representational equalities]
         (xi1, co1) <- flatten FM_FlattenAll ev ty1
       ; (xi2, co2) <- flatten FM_FlattenAll ev ty2
       ; traceTcS "canEqFailure with ReprEq" $
         vcat [ ppr ev, ppr ty1, ppr ty2, ppr xi1, ppr xi2 ]
       ; if xi1 `eqType` ty1 && xi2 `eqType` ty2
         then continueWith (CIrredEvCan { cc_ev = ev })  -- co1/2 must be refl
         else rewriteEqEvidence ev ReprEq NotSwapped xi1 xi2 co1 co2
              `andWhenContinue` \ new_ev ->
              can_eq_nc new_ev ReprEq xi1 xi1 xi2 xi2 }
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)
766
-- See Note [Make sure that insolubles are fully rewritten]
767
canEqHardFailure ev eq_rel ty1 ty2
768 769
  = do { (s1, co1) <- flatten FM_SubstOnly ev ty1
       ; (s2, co2) <- flatten FM_SubstOnly ev ty2
770 771 772 773
       ; rewriteEqEvidence ev eq_rel NotSwapped s1 s2 co1 co2
         `andWhenContinue` \ new_ev ->
    do { emitInsoluble (mkNonCanonical new_ev)
       ; stopWith new_ev "Definitely not equal" }}
774

Austin Seipp's avatar
Austin Seipp committed
775
{-
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
Note [Flatten irreducible representational equalities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we can't make any progress with a representational equality, but
we haven't given up all hope, we must flatten before producing the
CIrredEvCan. There are two reasons to do this:

  * See case in Note [Use canEqFailure in canDecomposableTyConApp].
    Flattening here can expose that we know enough information to unwrap
    a newtype.

  * This case, which was encountered in the testsuite (T9117_3):

      work item: [W] c1: f a ~R g a
      inert set: [G] c2: g ~R f

    In can_eq_app, we try to flatten the LHS of c1. This causes no effect,
    because `f` cannot be rewritten. So, we go to can_eq_flat_app. Without
    flattening the RHS, the reflexivity check fails, and we give up. However,
    flattening the RHS rewrites `g` to `f`, the reflexivity check succeeds,
    and we go on to glory.

797 798 799 800 801 802 803 804 805 806 807 808 809
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.

810 811 812
Note [Canonicalising type applications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given (s1 t1) ~ ty2, how should we proceed?
Austin Seipp's avatar
Austin Seipp committed
813
The simple things is to see if ty2 is of form (s2 t2), and
814
decompose.  By this time s1 and s2 can't be saturated type
Austin Seipp's avatar
Austin Seipp committed
815 816
function applications, because those have been dealt with
by an earlier equation in can_eq_nc, so it is always sound to
817 818
decompose.

Austin Seipp's avatar
Austin Seipp committed
819
However, over-eager decomposition gives bad error messages
820 821 822 823 824 825 826
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
827
we get an error        "Can't match Array ~ Maybe",
828 829
but we'd prefer to get "Can't match Array b ~ Maybe c".

830 831
So instead can_eq_wanted_app flattens the LHS and RHS before using
try_decompose_app to decompose it.
832

833 834
Note [Make sure that insolubles are fully rewritten]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Simon Peyton Jones's avatar
Simon Peyton Jones committed
835 836
When an equality fails, we still want to rewrite the equality
all the way down, so that it accurately reflects
837 838 839
 (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
840
And if we don't do this there is a bad danger that
841 842 843
TcSimplify.applyTyVarDefaulting will find a variable
that has in fact been substituted.

844
Note [Do not decompose Given polytype equalities]
845 846
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider [G] (forall a. t1 ~ forall a. t2).  Can we decompose this?
847
No -- what would the evidence look like?  So instead we simply discard
Simon Peyton Jones's avatar
Simon Peyton Jones committed
848
this given evidence.
849 850


851 852 853 854 855 856 857 858 859 860 861 862 863
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.
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885

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

Further, suppose flattening `a` doesn't do anything. Then, we'll flatten the
RHS of c1 and have a new [W] c3 : a ~R Id a. If we just blindly proceed, we'll
fail in canEqTyVar2 with an occurs-check. What we really need to do is to
unwrap the `Id a` in the RHS. This is exactly analogous to the requirement for
no top-level type families on the RHS of a nominal equality. The only
annoyance is that the flattener doesn't do this work for us when flattening
the RHS, so we have to catch this case here and then go back to the beginning
of can_eq_nc. We know that this can't loop forever because we require that
flattening the RHS actually made progress. (If it didn't, then we really
*should* fail with an occurs-check!)

Austin Seipp's avatar
Austin Seipp committed
886
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
887

Austin Seipp's avatar
Austin Seipp committed
888
canCFunEqCan :: CtEvidence
889
             -> TyCon -> [TcType]   -- LHS
890 891
             -> TcTyVar             -- RHS
             -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
892 893
-- ^ Canonicalise a CFunEqCan.  We know that
--     the arg types are already flat,
894 895 896
-- and the RHS is a fsk, which we must *not* substitute.
-- So just substitute in the LHS
canCFunEqCan ev fn tys fsk
897
  = do { (tys', cos) <- flattenMany FM_FlattenAll ev (repeat Nominal) tys
898 899 900 901 902
                        -- cos :: tys' ~ tys
       ; let lhs_co  = mkTcTyConAppCo Nominal fn cos
                        -- :: F tys' ~ F tys
             new_lhs = mkTyConApp fn tys'
             fsk_ty  = mkTyVarTy fsk
903 904 905 906
       ; 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')
907
       ; continueWith (CFunEqCan { cc_ev = ev', cc_fun = fn
908
                                 , cc_tyargs = tys', cc_fsk = fsk }) } }
909 910

---------------------
911
canEqTyVar :: CtEvidence -> EqRel -> SwapFlag
912
           -> TcTyVar
913
           -> TcType -> TcType
914
           -> TcS (StopOrContinue Ct)
915
-- A TyVar on LHS, but so far un-zonked
916
canEqTyVar ev eq_rel swapped tv1 ty2 ps_ty2              -- ev :: tv ~ s2
917
  = do { traceTcS "canEqTyVar" (ppr tv1 $$ ppr ty2 $$ ppr swapped)
918 919
       ; let fmode = mkFlattenEnv FM_FlattenAll ev  -- the FM_ param is ignored
       ; mb_yes <- flattenTyVarOuter fmode tv1
920
       ; case mb_yes of
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
         { Right (ty1, co1) -> -- co1 :: ty1 ~ tv1
             do { traceTcS "canEqTyVar2"
                           (vcat [ ppr tv1, ppr ty2, ppr swapped
                                 , ppr ty1 , ppUnless (isDerived ev) (ppr co1)])
                ; rewriteEqEvidence ev eq_rel swapped ty1 ps_ty2
                                    co1 (mkTcReflCo (eqRelRole eq_rel) ps_ty2)
                  `andWhenContinue` \ new_ev ->
                  can_eq_nc new_ev eq_rel ty1 ty1 ty2 ps_ty2 }

         ; Left tv1' ->
    do { -- FM_Avoid commented out: see Note [Lazy flattening] in TcFlatten
         -- 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
       ; (xi2, co2) <- flatten FM_FlattenAll ev ps_ty2 -- co2 :: xi2 ~ ps_ty2
                      -- Use ps_ty2 to preserve type synonyms if poss
       ; traceTcS "canEqTyVar flat LHS"
           (vcat [ ppr tv1, ppr tv1', ppr ty2, ppr swapped, ppr xi2 ])
       ; dflags <- getDynFlags
       ; case eq_rel of
      -- See Note [No top-level newtypes on RHS of representational equalities]
           ReprEq
             | Just (tc2, _) <- tcSplitTyConApp_maybe xi2
             , isNewTyCon tc2
             , not (ps_ty2 `eqType` xi2)
             -> do { let xi1  = mkTyVarTy tv1'
                         role = eqRelRole eq_rel
                   ; traceTcS "canEqTyVar exposed newtype"
                       (vcat [ ppr tv1', ppr ps_ty2, ppr xi2, ppr tc2 ])
                   ; rewriteEqEvidence ev eq_rel swapped xi1 xi2
                                       (mkTcReflCo role xi1) co2
                     `andWhenContinue` \ new_ev ->
                     can_eq_nc new_ev eq_rel xi1 xi1 xi2 xi2 }
           _ -> canEqTyVar2 dflags ev eq_rel swapped tv1' xi2 co2 } } }
955 956 957

canEqTyVar2 :: DynFlags
            -> CtEvidence   -- olhs ~ orhs (or, if swapped, orhs ~ olhs)
958
            -> EqRel
959 960 961 962
            -> SwapFlag
            -> TcTyVar      -- olhs
            -> TcType       -- nrhs
            -> TcCoercion   -- nrhs ~ orhs
963
            -> TcS (StopOrContinue Ct)
Austin Seipp's avatar
Austin Seipp committed
964
-- LHS is an inert type variable,
965
-- and RHS is fully rewritten, but with type synonyms
966
-- preserved as much as possible
967

968
canEqTyVar2 dflags ev eq_rel swapped tv1 xi2 co2
969
  | Just tv2 <- getTyVar_maybe xi2
970
  = canEqTyVarTyVar ev eq_rel swapped tv1 tv2 co2
971

972
  | OC_OK xi2' <- occurCheckExpand dflags tv1 xi2  -- No occurs check
973 974 975
  = do { let k1 = tyVarKind tv1
             k2 = typeKind xi2'
       ; rewriteEqEvidence ev eq_rel swapped xi1 xi2' co1 co2
Simon Peyton Jones's avatar
Simon Peyton Jones committed
976
                -- Ensure that the new goal has enough type synonyms
977
                -- expanded by the occurCheckExpand; hence using xi2' here
978
                -- See Note [occurCheckExpand]
979 980 981
         `andWhenContinue` \ new_ev ->
         if k2 `isSubKind` k1
         then   -- Establish CTyEqCan kind invariant
982 983
                -- Reorientation has done its best, but the kinds might
                -- simply be incompatible
984 985 986 987
               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 }
988 989

  | otherwise  -- Occurs check error
990 991 992 993
  = rewriteEqEvidence ev eq_rel swapped xi1 xi2 co1 co2
    `andWhenContinue` \ new_ev ->
    case eq_rel of
      NomEq  -> do { emitInsoluble (mkNonCanonical new_ev)
994 995 996
              -- 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
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
                   ; 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 }) }
1008 1009
  where
    xi1 = mkTyVarTy tv1
1010
    co1 = mkTcReflCo (eqRelRole eq_rel) xi1
1011 1012


1013 1014

canEqTyVarTyVar :: CtEvidence           -- tv1 ~ orhs (or orhs ~ tv1, if swapped)
1015
                -> EqRel
1016
                -> SwapFlag
1017 1018 1019
                -> TcTyVar -> TcTyVar   -- tv2, tv2
                -> TcCoercion           -- tv2 ~ orhs
                -> TcS (StopOrContinue Ct)
1020
-- Both LHS and RHS rewrote to a type variable,
1021 1022 1023 1024
-- If swapped = NotSwapped, then
--     rw_orhs = tv1, rw_olhs = orhs
--     rw_nlhs = tv2, rw_nrhs = xi1
-- See Note [Canonical orientation for tyvar/tyvar equality constraints]
1025
canEqTyVarTyVar ev eq_rel swapped tv1 tv2 co2
1026 1027
  | tv1 == tv2
  = do { when (isWanted ev) $
1028
         ASSERT( tcCoercionRole co2 == eqRelRole eq_rel )
1029
         setEvBind (ctev_evar ev) (EvCoercion (maybeSym swapped co2))
1030 1031 1032 1033 1034 1035 1036 1037
       ; stopWith ev "Equal tyvars" }

  | incompat_kind   = incompat
  | isFmvTyVar tv1  = do_fmv swapped            tv1 xi1 xi2 co1 co2
  | isFmvTyVar tv2  = do_fmv (flipSwap swapped) tv2 xi2 xi1 co2 co1
  | same_kind       = if swap_over then do_swap else no_swap
  | k1_sub_k2       = do_swap   -- Note [Kind orientation for CTyEqCan]
  | otherwise       = no_swap   -- k2_sub_k1
1038 1039
  where
    xi1 = mkTyVarTy tv1
1040 1041 1042
    xi2 = mkTyVarTy tv2
    k1  = tyVarKind tv1
    k2  = tyVarKind tv2
1043
    co1 = mkTcReflCo (eqRelRole eq_rel) xi1
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    k1_sub_k2     = k1 `isSubKind` k2
    k2_sub_k1     = k2 `isSubKind` k1
    same_kind     = k1_sub_k2 && k2_sub_k1
    incompat_kind = not (k1_sub_k2 || k2_sub_k1)

    no_swap = canon_eq swapped            tv1 xi1 xi2 co1 co2
    do_swap = canon_eq (flipSwap swapped) tv2 xi2 xi1 co2 co1

    canon_eq swapped tv1 xi1 xi2 co1 co2
        -- ev  : tv1 ~ orhs  (not swapped) or   orhs ~ tv1   (swapped)
        -- co1 : xi1 ~ tv1
        -- co2 : xi2 ~ tv2
1056 1057 1058
      = do { mb <- rewriteEqEvidence ev eq_rel swapped xi1 xi2 co1 co2
           ; let mk_ct ev' = CTyEqCan { cc_ev = ev', cc_tyvar = tv1
                                      , cc_rhs = xi2 , cc_eq_rel = eq_rel }
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
           ; return (fmap mk_ct mb) }

    -- See Note [Orient equalities with flatten-meta-vars on the left] in TcFlatten
    do_fmv swapped tv1 xi1 xi2 co1 co2
      | same_kind
      = canon_eq swapped tv1 xi1 xi2 co1 co2
      | otherwise  -- Presumably tv1 `subKind` tv2, which is the wrong way round
      = ASSERT2( k1_sub_k2, ppr tv1 $$ ppr tv2 )
        ASSERT2( isWanted ev, ppr ev )  -- Only wanteds have flatten meta-vars
        do { tv_ty <- newFlexiTcSTy (tyVarKind tv1)
1069 1070 1071
           ; new_ev <- newWantedEvVarNC (ctEvLoc ev)
                                        (mkTcEqPredRole (eqRelRole eq_rel)
                                                        tv_ty xi2)
1072 1073 1074 1075
           ; emitWorkNC [new_ev]
           ; canon_eq swapped tv1 xi1 tv_ty co1 (ctEvCoercion new_ev `mkTcTransCo` co2) }

    incompat
1076 1077 1078
      = rewriteEqEvidence ev eq_rel swapped xi1 xi2 (mkTcNomReflCo xi1) co2
        `andWhenContinue` \ ev' ->
        incompatibleKind ev' xi1 k1 xi2 k2
1079 1080 1081 1082 1083

    swap_over
      -- If tv1 is touchable, swap only if tv2 is also
      -- touchable and it's strictly better to update the latter
      -- But see Note [Avoid unnecessary swaps]
1084 1085
      | Just lvl1 <- metaTyVarTcLevel_maybe tv1
      = case metaTyVarTcLevel_maybe tv2 of
1086 1087 1088 1089 1090 1091 1092
          Nothing   -> False
          Just lvl2 | lvl2 `strictlyDeeperThan` lvl1 -> True
                    | lvl1 `strictlyDeeperThan` lvl2 -> False
                    | otherwise                      -> nicer_to_update_tv2

      -- So tv1 is not a meta tyvar
      -- If only one is a meta tyvar, put it on the left
Gabor Greif's avatar
Gabor Greif committed
1093
      -- This is not because it'll be solved; but because
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
      -- the floating step looks for meta tyvars on the left
      | isMetaTyVar tv2 = True

      -- So neither is a meta tyvar

      -- If only one is a flatten tyvar, put it on the left
      -- See Note [Eliminate flat-skols]
      | not (isFlattenTyVar tv1), isFlattenTyVar tv2 = True

      | otherwise = False

    nicer_to_update_tv2
      =  (isSigTyVar tv1                 && not (isSigTyVar tv2))
      || (isSystemName (Var.varName tv2) && not (isSystemName (Var.varName tv1)))

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
-- | Solve a reflexive equality constraint
canEqReflexive :: CtEvidence    -- ty ~ ty
               -> EqRel
               -> TcType        -- ty
               -> TcS (StopOrContinue Ct)   -- always Stop
canEqReflexive ev eq_rel ty
  = do { when (isWanted ev) $
         setEvBind (ctev_evar ev) (EvCoercion $
                                   mkTcReflCo (eqRelRole eq_rel) ty)
       ; stopWith ev "Solved by reflexivity" }

1120 1121 1122 1123
incompatibleKind :: CtEvidence         -- t1~t2
                 -> TcType -> TcKind
                 -> TcType -> TcKind   -- s1~s2, flattened and zonked
                 -> TcS (StopOrContinue Ct)