Update Trac ticket URLs to point to GitLab
[ghc.git] / compiler / typecheck / TcFlatten.hs
1 {-# LANGUAGE CPP, ViewPatterns, BangPatterns #-}
2
3 module TcFlatten(
4 FlattenMode(..),
5 flatten, flattenKind, flattenArgsNom,
6
7 unflattenWanteds
8 ) where
9
10 #include "HsVersions.h"
11
12 import GhcPrelude
13
14 import TcRnTypes
15 import TcType
16 import Type
17 import TcEvidence
18 import TyCon
19 import TyCoRep -- performs delicate algorithm on types
20 import Coercion
21 import Var
22 import VarSet
23 import VarEnv
24 import Outputable
25 import TcSMonad as TcS
26 import BasicTypes( SwapFlag(..) )
27
28 import Util
29 import Bag
30 import Control.Monad
31 import MonadUtils ( zipWith3M )
32
33 import Control.Arrow ( first )
34
35 {-
36 Note [The flattening story]
37 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
38 * A CFunEqCan is either of form
39 [G] <F xis> : F xis ~ fsk -- fsk is a FlatSkolTv
40 [W] x : F xis ~ fmv -- fmv is a FlatMetaTv
41 where
42 x is the witness variable
43 xis are function-free
44 fsk/fmv is a flatten skolem;
45 it is always untouchable (level 0)
46
47 * CFunEqCans can have any flavour: [G], [W], [WD] or [D]
48
49 * KEY INSIGHTS:
50
51 - A given flatten-skolem, fsk, is known a-priori to be equal to
52 F xis (the LHS), with <F xis> evidence. The fsk is still a
53 unification variable, but it is "owned" by its CFunEqCan, and
54 is filled in (unflattened) only by unflattenGivens.
55
56 - A unification flatten-skolem, fmv, stands for the as-yet-unknown
57 type to which (F xis) will eventually reduce. It is filled in
58
59
60 - All fsk/fmv variables are "untouchable". To make it simple to test,
61 we simply give them TcLevel=0. This means that in a CTyVarEq, say,
62 fmv ~ Int
63 we NEVER unify fmv.
64
65 - A unification flatten-skolem, fmv, ONLY gets unified when either
66 a) The CFunEqCan takes a step, using an axiom
67 b) By unflattenWanteds
68 They are never unified in any other form of equality.
69 For example [W] ffmv ~ Int is stuck; it does not unify with fmv.
70
71 * We *never* substitute in the RHS (i.e. the fsk/fmv) of a CFunEqCan.
72 That would destroy the invariant about the shape of a CFunEqCan,
73 and it would risk wanted/wanted interactions. The only way we
74 learn information about fsk is when the CFunEqCan takes a step.
75
76 However we *do* substitute in the LHS of a CFunEqCan (else it
77 would never get to fire!)
78
79 * Unflattening:
80 - We unflatten Givens when leaving their scope (see unflattenGivens)
81 - We unflatten Wanteds at the end of each attempt to simplify the
82 wanteds; see unflattenWanteds, called from solveSimpleWanteds.
83
84 * Ownership of fsk/fmv. Each canonical [G], [W], or [WD]
85 CFunEqCan x : F xis ~ fsk/fmv
86 "owns" a distinct evidence variable x, and flatten-skolem fsk/fmv.
87 Why? We make a fresh fsk/fmv when the constraint is born;
88 and we never rewrite the RHS of a CFunEqCan.
89
90 In contrast a [D] CFunEqCan /shares/ its fmv with its partner [W],
91 but does not "own" it. If we reduce a [D] F Int ~ fmv, where
92 say type instance F Int = ty, then we don't discharge fmv := ty.
93 Rather we simply generate [D] fmv ~ ty (in TcInteract.reduce_top_fun_eq,
94 and dischargeFmv)
95
96 * Inert set invariant: if F xis1 ~ fsk1, F xis2 ~ fsk2
97 then xis1 /= xis2
98 i.e. at most one CFunEqCan with a particular LHS
99
100 * Function applications can occur in the RHS of a CTyEqCan. No reason
101 not allow this, and it reduces the amount of flattening that must occur.
102
103 * Flattening a type (F xis):
104 - If we are flattening in a Wanted/Derived constraint
105 then create new [W] x : F xis ~ fmv
106 else create new [G] x : F xis ~ fsk
107 with fresh evidence variable x and flatten-skolem fsk/fmv
108
109 - Add it to the work list
110
111 - Replace (F xis) with fsk/fmv in the type you are flattening
112
113 - You can also add the CFunEqCan to the "flat cache", which
114 simply keeps track of all the function applications you
115 have flattened.
116
117 - If (F xis) is in the cache already, just
118 use its fsk/fmv and evidence x, and emit nothing.
119
120 - No need to substitute in the flat-cache. It's not the end
121 of the world if we start with, say (F alpha ~ fmv1) and
122 (F Int ~ fmv2) and then find alpha := Int. Athat will
123 simply give rise to fmv1 := fmv2 via [Interacting rule] below
124
125 * Canonicalising a CFunEqCan [G/W] x : F xis ~ fsk/fmv
126 - Flatten xis (to substitute any tyvars; there are already no functions)
127 cos :: xis ~ flat_xis
128 - New wanted x2 :: F flat_xis ~ fsk/fmv
129 - Add new wanted to flat cache
130 - Discharge x = F cos ; x2
131
132 * [Interacting rule]
133 (inert) [W] x1 : F tys ~ fmv1
134 (work item) [W] x2 : F tys ~ fmv2
135 Just solve one from the other:
136 x2 := x1
137 fmv2 := fmv1
138 This just unites the two fsks into one.
139 Always solve given from wanted if poss.
140
141 * For top-level reductions, see Note [Top-level reductions for type functions]
142 in TcInteract
143
144
145 Why given-fsks, alone, doesn't work
146 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
147 Could we get away with only flatten meta-tyvars, with no flatten-skolems? No.
148
149 [W] w : alpha ~ [F alpha Int]
150
151 ---> flatten
152 w = ...w'...
153 [W] w' : alpha ~ [fsk]
154 [G] <F alpha Int> : F alpha Int ~ fsk
155
156 --> unify (no occurs check)
157 alpha := [fsk]
158
159 But since fsk = F alpha Int, this is really an occurs check error. If
160 that is all we know about alpha, we will succeed in constraint
161 solving, producing a program with an infinite type.
162
163 Even if we did finally get (g : fsk ~ Bool) by solving (F alpha Int ~ fsk)
164 using axiom, zonking would not see it, so (x::alpha) sitting in the
165 tree will get zonked to an infinite type. (Zonking always only does
166 refl stuff.)
167
168 Why flatten-meta-vars, alone doesn't work
169 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170 Look at Simple13, with unification-fmvs only
171
172 [G] g : a ~ [F a]
173
174 ---> Flatten given
175 g' = g;[x]
176 [G] g' : a ~ [fmv]
177 [W] x : F a ~ fmv
178
179 --> subst a in x
180 g' = g;[x]
181 x = F g' ; x2
182 [W] x2 : F [fmv] ~ fmv
183
184 And now we have an evidence cycle between g' and x!
185
186 If we used a given instead (ie current story)
187
188 [G] g : a ~ [F a]
189
190 ---> Flatten given
191 g' = g;[x]
192 [G] g' : a ~ [fsk]
193 [G] <F a> : F a ~ fsk
194
195 ---> Substitute for a
196 [G] g' : a ~ [fsk]
197 [G] F (sym g'); <F a> : F [fsk] ~ fsk
198
199
200 Why is it right to treat fmv's differently to ordinary unification vars?
201 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
202 f :: forall a. a -> a -> Bool
203 g :: F Int -> F Int -> Bool
204
205 Consider
206 f (x:Int) (y:Bool)
207 This gives alpha~Int, alpha~Bool. There is an inconsistency,
208 but really only one error. SherLoc may tell you which location
209 is most likely, based on other occurrences of alpha.
210
211 Consider
212 g (x:Int) (y:Bool)
213 Here we get (F Int ~ Int, F Int ~ Bool), which flattens to
214 (fmv ~ Int, fmv ~ Bool)
215 But there are really TWO separate errors.
216
217 ** We must not complain about Int~Bool. **
218
219 Moreover these two errors could arise in entirely unrelated parts of
220 the code. (In the alpha case, there must be *some* connection (eg
221 v:alpha in common envt).)
222
223 Note [Unflattening can force the solver to iterate]
224 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
225 Look at #10340:
226 type family Any :: * -- No instances
227 get :: MonadState s m => m s
228 instance MonadState s (State s) where ...
229
230 foo :: State Any Any
231 foo = get
232
233 For 'foo' we instantiate 'get' at types mm ss
234 [WD] MonadState ss mm, [WD] mm ss ~ State Any Any
235 Flatten, and decompose
236 [WD] MonadState ss mm, [WD] Any ~ fmv
237 [WD] mm ~ State fmv, [WD] fmv ~ ss
238 Unify mm := State fmv:
239 [WD] MonadState ss (State fmv)
240 [WD] Any ~ fmv, [WD] fmv ~ ss
241 Now we are stuck; the instance does not match!! So unflatten:
242 fmv := Any
243 ss := Any (*)
244 [WD] MonadState Any (State Any)
245
246 The unification (*) represents progress, so we must do a second
247 round of solving; this time it succeeds. This is done by the 'go'
248 loop in solveSimpleWanteds.
249
250 This story does not feel right but it's the best I can do; and the
251 iteration only happens in pretty obscure circumstances.
252
253
254 ************************************************************************
255 * *
256 * Examples
257 Here is a long series of examples I had to work through
258 * *
259 ************************************************************************
260
261 Simple20
262 ~~~~~~~~
263 axiom F [a] = [F a]
264
265 [G] F [a] ~ a
266 -->
267 [G] fsk ~ a
268 [G] [F a] ~ fsk (nc)
269 -->
270 [G] F a ~ fsk2
271 [G] fsk ~ [fsk2]
272 [G] fsk ~ a
273 -->
274 [G] F a ~ fsk2
275 [G] a ~ [fsk2]
276 [G] fsk ~ a
277
278 ----------------------------------------
279 indexed-types/should_compile/T44984
280
281 [W] H (F Bool) ~ H alpha
282 [W] alpha ~ F Bool
283 -->
284 F Bool ~ fmv0
285 H fmv0 ~ fmv1
286 H alpha ~ fmv2
287
288 fmv1 ~ fmv2
289 fmv0 ~ alpha
290
291 flatten
292 ~~~~~~~
293 fmv0 := F Bool
294 fmv1 := H (F Bool)
295 fmv2 := H alpha
296 alpha := F Bool
297 plus
298 fmv1 ~ fmv2
299
300 But these two are equal under the above assumptions.
301 Solve by Refl.
302
303
304 --- under plan B, namely solve fmv1:=fmv2 eagerly ---
305 [W] H (F Bool) ~ H alpha
306 [W] alpha ~ F Bool
307 -->
308 F Bool ~ fmv0
309 H fmv0 ~ fmv1
310 H alpha ~ fmv2
311
312 fmv1 ~ fmv2
313 fmv0 ~ alpha
314 -->
315 F Bool ~ fmv0
316 H fmv0 ~ fmv1
317 H alpha ~ fmv2 fmv2 := fmv1
318
319 fmv0 ~ alpha
320
321 flatten
322 fmv0 := F Bool
323 fmv1 := H fmv0 = H (F Bool)
324 retain H alpha ~ fmv2
325 because fmv2 has been filled
326 alpha := F Bool
327
328
329 ----------------------------
330 indexed-types/should_failt/T4179
331
332 after solving
333 [W] fmv_1 ~ fmv_2
334 [W] A3 (FCon x) ~ fmv_1 (CFunEqCan)
335 [W] A3 (x (aoa -> fmv_2)) ~ fmv_2 (CFunEqCan)
336
337 ----------------------------------------
338 indexed-types/should_fail/T7729a
339
340 a) [W] BasePrimMonad (Rand m) ~ m1
341 b) [W] tt m1 ~ BasePrimMonad (Rand m)
342
343 ---> process (b) first
344 BasePrimMonad (Ramd m) ~ fmv_atH
345 fmv_atH ~ tt m1
346
347 ---> now process (a)
348 m1 ~ s_atH ~ tt m1 -- An obscure occurs check
349
350
351 ----------------------------------------
352 typecheck/TcTypeNatSimple
353
354 Original constraint
355 [W] x + y ~ x + alpha (non-canonical)
356 ==>
357 [W] x + y ~ fmv1 (CFunEqCan)
358 [W] x + alpha ~ fmv2 (CFuneqCan)
359 [W] fmv1 ~ fmv2 (CTyEqCan)
360
361 (sigh)
362
363 ----------------------------------------
364 indexed-types/should_fail/GADTwrong1
365
366 [G] Const a ~ ()
367 ==> flatten
368 [G] fsk ~ ()
369 work item: Const a ~ fsk
370 ==> fire top rule
371 [G] fsk ~ ()
372 work item fsk ~ ()
373
374 Surely the work item should rewrite to () ~ ()? Well, maybe not;
375 it'a very special case. More generally, our givens look like
376 F a ~ Int, where (F a) is not reducible.
377
378
379 ----------------------------------------
380 indexed_types/should_fail/T8227:
381
382 Why using a different can-rewrite rule in CFunEqCan heads
383 does not work.
384
385 Assuming NOT rewriting wanteds with wanteds
386
387 Inert: [W] fsk_aBh ~ fmv_aBk -> fmv_aBk
388 [W] fmv_aBk ~ fsk_aBh
389
390 [G] Scalar fsk_aBg ~ fsk_aBh
391 [G] V a ~ f_aBg
392
393 Worklist includes [W] Scalar fmv_aBi ~ fmv_aBk
394 fmv_aBi, fmv_aBk are flatten unification variables
395
396 Work item: [W] V fsk_aBh ~ fmv_aBi
397
398 Note that the inert wanteds are cyclic, because we do not rewrite
399 wanteds with wanteds.
400
401
402 Then we go into a loop when normalise the work-item, because we
403 use rewriteOrSame on the argument of V.
404
405 Conclusion: Don't make canRewrite context specific; instead use
406 [W] a ~ ty to rewrite a wanted iff 'a' is a unification variable.
407
408
409 ----------------------------------------
410
411 Here is a somewhat similar case:
412
413 type family G a :: *
414
415 blah :: (G a ~ Bool, Eq (G a)) => a -> a
416 blah = error "urk"
417
418 foo x = blah x
419
420 For foo we get
421 [W] Eq (G a), G a ~ Bool
422 Flattening
423 [W] G a ~ fmv, Eq fmv, fmv ~ Bool
424 We can't simplify away the Eq Bool unless we substitute for fmv.
425 Maybe that doesn't matter: we would still be left with unsolved
426 G a ~ Bool.
427
428 --------------------------
429 #9318 has a very simple program leading to
430
431 [W] F Int ~ Int
432 [W] F Int ~ Bool
433
434 We don't want to get "Error Int~Bool". But if fmv's can rewrite
435 wanteds, we will
436
437 [W] fmv ~ Int
438 [W] fmv ~ Bool
439 --->
440 [W] Int ~ Bool
441
442
443 ************************************************************************
444 * *
445 * FlattenEnv & FlatM
446 * The flattening environment & monad
447 * *
448 ************************************************************************
449
450 -}
451
452 type FlatWorkListRef = TcRef [Ct] -- See Note [The flattening work list]
453
454 data FlattenEnv
455 = FE { fe_mode :: !FlattenMode
456 , fe_loc :: !CtLoc -- See Note [Flattener CtLoc]
457 , fe_flavour :: !CtFlavour
458 , fe_eq_rel :: !EqRel -- See Note [Flattener EqRels]
459 , fe_work :: !FlatWorkListRef } -- See Note [The flattening work list]
460
461 data FlattenMode -- Postcondition for all three: inert wrt the type substitution
462 = FM_FlattenAll -- Postcondition: function-free
463 | FM_SubstOnly -- See Note [Flattening under a forall]
464
465 -- | FM_Avoid TcTyVar Bool -- See Note [Lazy flattening]
466 -- -- Postcondition:
467 -- -- * tyvar is only mentioned in result under a rigid path
468 -- -- e.g. [a] is ok, but F a won't happen
469 -- -- * If flat_top is True, top level is not a function application
470 -- -- (but under type constructors is ok e.g. [F a])
471
472 instance Outputable FlattenMode where
473 ppr FM_FlattenAll = text "FM_FlattenAll"
474 ppr FM_SubstOnly = text "FM_SubstOnly"
475
476 eqFlattenMode :: FlattenMode -> FlattenMode -> Bool
477 eqFlattenMode FM_FlattenAll FM_FlattenAll = True
478 eqFlattenMode FM_SubstOnly FM_SubstOnly = True
479 -- FM_Avoid tv1 b1 `eq` FM_Avoid tv2 b2 = tv1 == tv2 && b1 == b2
480 eqFlattenMode _ _ = False
481
482 -- | The 'FlatM' monad is a wrapper around 'TcS' with the following
483 -- extra capabilities: (1) it offers access to a 'FlattenEnv';
484 -- and (2) it maintains the flattening worklist.
485 -- See Note [The flattening work list].
486 newtype FlatM a
487 = FlatM { runFlatM :: FlattenEnv -> TcS a }
488
489 instance Monad FlatM where
490 m >>= k = FlatM $ \env ->
491 do { a <- runFlatM m env
492 ; runFlatM (k a) env }
493
494 instance Functor FlatM where
495 fmap = liftM
496
497 instance Applicative FlatM where
498 pure x = FlatM $ const (pure x)
499 (<*>) = ap
500
501 liftTcS :: TcS a -> FlatM a
502 liftTcS thing_inside
503 = FlatM $ const thing_inside
504
505 emitFlatWork :: Ct -> FlatM ()
506 -- See Note [The flattening work list]
507 emitFlatWork ct = FlatM $ \env -> updTcRef (fe_work env) (ct :)
508
509 -- convenient wrapper when you have a CtEvidence describing
510 -- the flattening operation
511 runFlattenCtEv :: FlattenMode -> CtEvidence -> FlatM a -> TcS a
512 runFlattenCtEv mode ev
513 = runFlatten mode (ctEvLoc ev) (ctEvFlavour ev) (ctEvEqRel ev)
514
515 -- Run thing_inside (which does flattening), and put all
516 -- the work it generates onto the main work list
517 -- See Note [The flattening work list]
518 runFlatten :: FlattenMode -> CtLoc -> CtFlavour -> EqRel -> FlatM a -> TcS a
519 runFlatten mode loc flav eq_rel thing_inside
520 = do { flat_ref <- newTcRef []
521 ; let fmode = FE { fe_mode = mode
522 , fe_loc = loc
523 , fe_flavour = flav
524 , fe_eq_rel = eq_rel
525 , fe_work = flat_ref }
526 ; res <- runFlatM thing_inside fmode
527 ; new_flats <- readTcRef flat_ref
528 ; updWorkListTcS (add_flats new_flats)
529 ; return res }
530 where
531 add_flats new_flats wl
532 = wl { wl_funeqs = add_funeqs new_flats (wl_funeqs wl) }
533
534 add_funeqs [] wl = wl
535 add_funeqs (f:fs) wl = add_funeqs fs (f:wl)
536 -- add_funeqs fs ws = reverse fs ++ ws
537 -- e.g. add_funeqs [f1,f2,f3] [w1,w2,w3,w4]
538 -- = [f3,f2,f1,w1,w2,w3,w4]
539
540 traceFlat :: String -> SDoc -> FlatM ()
541 traceFlat herald doc = liftTcS $ traceTcS herald doc
542
543 getFlatEnvField :: (FlattenEnv -> a) -> FlatM a
544 getFlatEnvField accessor
545 = FlatM $ \env -> return (accessor env)
546
547 getEqRel :: FlatM EqRel
548 getEqRel = getFlatEnvField fe_eq_rel
549
550 getRole :: FlatM Role
551 getRole = eqRelRole <$> getEqRel
552
553 getFlavour :: FlatM CtFlavour
554 getFlavour = getFlatEnvField fe_flavour
555
556 getFlavourRole :: FlatM CtFlavourRole
557 getFlavourRole
558 = do { flavour <- getFlavour
559 ; eq_rel <- getEqRel
560 ; return (flavour, eq_rel) }
561
562 getMode :: FlatM FlattenMode
563 getMode = getFlatEnvField fe_mode
564
565 getLoc :: FlatM CtLoc
566 getLoc = getFlatEnvField fe_loc
567
568 checkStackDepth :: Type -> FlatM ()
569 checkStackDepth ty
570 = do { loc <- getLoc
571 ; liftTcS $ checkReductionDepth loc ty }
572
573 -- | Change the 'EqRel' in a 'FlatM'.
574 setEqRel :: EqRel -> FlatM a -> FlatM a
575 setEqRel new_eq_rel thing_inside
576 = FlatM $ \env ->
577 if new_eq_rel == fe_eq_rel env
578 then runFlatM thing_inside env
579 else runFlatM thing_inside (env { fe_eq_rel = new_eq_rel })
580
581 -- | Change the 'FlattenMode' in a 'FlattenEnv'.
582 setMode :: FlattenMode -> FlatM a -> FlatM a
583 setMode new_mode thing_inside
584 = FlatM $ \env ->
585 if new_mode `eqFlattenMode` fe_mode env
586 then runFlatM thing_inside env
587 else runFlatM thing_inside (env { fe_mode = new_mode })
588
589 -- | Make sure that flattening actually produces a coercion (in other
590 -- words, make sure our flavour is not Derived)
591 -- Note [No derived kind equalities]
592 noBogusCoercions :: FlatM a -> FlatM a
593 noBogusCoercions thing_inside
594 = FlatM $ \env ->
595 -- No new thunk is made if the flavour hasn't changed (note the bang).
596 let !env' = case fe_flavour env of
597 Derived -> env { fe_flavour = Wanted WDeriv }
598 _ -> env
599 in
600 runFlatM thing_inside env'
601
602 bumpDepth :: FlatM a -> FlatM a
603 bumpDepth (FlatM thing_inside)
604 = FlatM $ \env -> do
605 -- bumpDepth can be called a lot during flattening so we force the
606 -- new env to avoid accumulating thunks.
607 { let !env' = env { fe_loc = bumpCtLocDepth (fe_loc env) }
608 ; thing_inside env' }
609
610 {-
611 Note [The flattening work list]
612 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
613 The "flattening work list", held in the fe_work field of FlattenEnv,
614 is a list of CFunEqCans generated during flattening. The key idea
615 is this. Consider flattening (Eq (F (G Int) (H Bool)):
616 * The flattener recursively calls itself on sub-terms before building
617 the main term, so it will encounter the terms in order
618 G Int
619 H Bool
620 F (G Int) (H Bool)
621 flattening to sub-goals
622 w1: G Int ~ fuv0
623 w2: H Bool ~ fuv1
624 w3: F fuv0 fuv1 ~ fuv2
625
626 * Processing w3 first is BAD, because we can't reduce i t,so it'll
627 get put into the inert set, and later kicked out when w1, w2 are
628 solved. In #9872 this led to inert sets containing hundreds
629 of suspended calls.
630
631 * So we want to process w1, w2 first.
632
633 * So you might think that we should just use a FIFO deque for the work-list,
634 so that putting adding goals in order w1,w2,w3 would mean we processed
635 w1 first.
636
637 * BUT suppose we have 'type instance G Int = H Char'. Then processing
638 w1 leads to a new goal
639 w4: H Char ~ fuv0
640 We do NOT want to put that on the far end of a deque! Instead we want
641 to put it at the *front* of the work-list so that we continue to work
642 on it.
643
644 So the work-list structure is this:
645
646 * The wl_funeqs (in TcS) is a LIFO stack; we push new goals (such as w4) on
647 top (extendWorkListFunEq), and take new work from the top
648 (selectWorkItem).
649
650 * When flattening, emitFlatWork pushes new flattening goals (like
651 w1,w2,w3) onto the flattening work list, fe_work, another
652 push-down stack.
653
654 * When we finish flattening, we *reverse* the fe_work stack
655 onto the wl_funeqs stack (which brings w1 to the top).
656
657 The function runFlatten initialises the fe_work stack, and reverses
658 it onto wl_fun_eqs at the end.
659
660 Note [Flattener EqRels]
661 ~~~~~~~~~~~~~~~~~~~~~~~
662 When flattening, we need to know which equality relation -- nominal
663 or representation -- we should be respecting. The only difference is
664 that we rewrite variables by representational equalities when fe_eq_rel
665 is ReprEq, and that we unwrap newtypes when flattening w.r.t.
666 representational equality.
667
668 Note [Flattener CtLoc]
669 ~~~~~~~~~~~~~~~~~~~~~~
670 The flattener does eager type-family reduction.
671 Type families might loop, and we
672 don't want GHC to do so. A natural solution is to have a bounded depth
673 to these processes. A central difficulty is that such a solution isn't
674 quite compositional. For example, say it takes F Int 10 steps to get to Bool.
675 How many steps does it take to get from F Int -> F Int to Bool -> Bool?
676 10? 20? What about getting from Const Char (F Int) to Char? 11? 1? Hard to
677 know and hard to track. So, we punt, essentially. We store a CtLoc in
678 the FlattenEnv and just update the environment when recurring. In the
679 TyConApp case, where there may be multiple type families to flatten,
680 we just copy the current CtLoc into each branch. If any branch hits the
681 stack limit, then the whole thing fails.
682
683 A consequence of this is that setting the stack limits appropriately
684 will be essentially impossible. So, the official recommendation if a
685 stack limit is hit is to disable the check entirely. Otherwise, there
686 will be baffling, unpredictable errors.
687
688 Note [Lazy flattening]
689 ~~~~~~~~~~~~~~~~~~~~~~
690 The idea of FM_Avoid mode is to flatten less aggressively. If we have
691 a ~ [F Int]
692 there seems to be no great merit in lifting out (F Int). But if it was
693 a ~ [G a Int]
694 then we *do* want to lift it out, in case (G a Int) reduces to Bool, say,
695 which gets rid of the occurs-check problem. (For the flat_top Bool, see
696 comments above and at call sites.)
697
698 HOWEVER, the lazy flattening actually seems to make type inference go
699 *slower*, not faster. perf/compiler/T3064 is a case in point; it gets
700 *dramatically* worse with FM_Avoid. I think it may be because
701 floating the types out means we normalise them, and that often makes
702 them smaller and perhaps allows more re-use of previously solved
703 goals. But to be honest I'm not absolutely certain, so I am leaving
704 FM_Avoid in the code base. What I'm removing is the unique place
705 where it is *used*, namely in TcCanonical.canEqTyVar.
706
707 See also Note [Conservative unification check] in TcUnify, which gives
708 other examples where lazy flattening caused problems.
709
710 Bottom line: FM_Avoid is unused for now (Nov 14).
711 Note: T5321Fun got faster when I disabled FM_Avoid
712 T5837 did too, but it's pathalogical anyway
713
714 Note [Phantoms in the flattener]
715 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
716 Suppose we have
717
718 data Proxy p = Proxy
719
720 and we're flattening (Proxy ty) w.r.t. ReprEq. Then, we know that `ty`
721 is really irrelevant -- it will be ignored when solving for representational
722 equality later on. So, we omit flattening `ty` entirely. This may
723 violate the expectation of "xi"s for a bit, but the canonicaliser will
724 soon throw out the phantoms when decomposing a TyConApp. (Or, the
725 canonicaliser will emit an insoluble, in which case the unflattened version
726 yields a better error message anyway.)
727
728 Note [No derived kind equalities]
729 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
730 A kind-level coercion can appear in types, via mkCastTy. So, whenever
731 we are generating a coercion in a dependent context (in other words,
732 in a kind) we need to make sure that our flavour is never Derived
733 (as Derived constraints have no evidence). The noBogusCoercions function
734 changes the flavour from Derived just for this purpose.
735
736 -}
737
738 {- *********************************************************************
739 * *
740 * Externally callable flattening functions *
741 * *
742 * They are all wrapped in runFlatten, so their *
743 * flattening work gets put into the work list *
744 * *
745 ********************************************************************* -}
746
747 flatten :: FlattenMode -> CtEvidence -> TcType
748 -> TcS (Xi, TcCoercion)
749 flatten mode ev ty
750 = do { traceTcS "flatten {" (ppr mode <+> ppr ty)
751 ; (ty', co) <- runFlattenCtEv mode ev (flatten_one ty)
752 ; traceTcS "flatten }" (ppr ty')
753 ; return (ty', co) }
754
755 -- specialized to flattening kinds: never Derived, always Nominal
756 -- See Note [No derived kind equalities]
757 flattenKind :: CtLoc -> CtFlavour -> TcType -> TcS (Xi, TcCoercionN)
758 flattenKind loc flav ty
759 = do { traceTcS "flattenKind {" (ppr flav <+> ppr ty)
760 ; let flav' = case flav of
761 Derived -> Wanted WDeriv -- the WDeriv/WOnly choice matters not
762 _ -> flav
763 ; (ty', co) <- runFlatten FM_FlattenAll loc flav' NomEq (flatten_one ty)
764 ; traceTcS "flattenKind }" (ppr ty' $$ ppr co) -- co is never a panic
765 ; return (ty', co) }
766
767 flattenArgsNom :: CtEvidence -> TyCon -> [TcType] -> TcS ([Xi], [TcCoercion], TcCoercionN)
768 -- Externally-callable, hence runFlatten
769 -- Flatten a vector of types all at once; in fact they are
770 -- always the arguments of type family or class, so
771 -- ctEvFlavour ev = Nominal
772 -- and we want to flatten all at nominal role
773 -- The kind passed in is the kind of the type family or class, call it T
774 -- The last coercion returned has type (tcTypeKind(T xis) ~N tcTypeKind(T tys))
775 --
776 -- For Derived constraints the returned coercion may be undefined
777 -- because flattening may use a Derived equality ([D] a ~ ty)
778 flattenArgsNom ev tc tys
779 = do { traceTcS "flatten_args {" (vcat (map ppr tys))
780 ; (tys', cos, kind_co)
781 <- runFlattenCtEv FM_FlattenAll ev (flatten_args_tc tc (repeat Nominal) tys)
782 ; traceTcS "flatten }" (vcat (map ppr tys'))
783 ; return (tys', cos, kind_co) }
784
785
786 {- *********************************************************************
787 * *
788 * The main flattening functions
789 * *
790 ********************************************************************* -}
791
792 {- Note [Flattening]
793 ~~~~~~~~~~~~~~~~~~~~
794 flatten ty ==> (xi, co)
795 where
796 xi has no type functions, unless they appear under ForAlls
797 has no skolems that are mapped in the inert set
798 has no filled-in metavariables
799 co :: xi ~ ty
800
801 Key invariants:
802 (F0) co :: xi ~ zonk(ty)
803 (F1) tcTypeKind(xi) succeeds and returns a fully zonked kind
804 (F2) tcTypeKind(xi) `eqType` zonk(tcTypeKind(ty))
805
806 Note that it is flatten's job to flatten *every type function it sees*.
807 flatten is only called on *arguments* to type functions, by canEqGiven.
808
809 Flattening also:
810 * zonks, removing any metavariables, and
811 * applies the substitution embodied in the inert set
812
813 Because flattening zonks and the returned coercion ("co" above) is also
814 zonked, it's possible that (co :: xi ~ ty) isn't quite true. So, instead,
815 we can rely on this fact:
816
817 (F1) tcTypeKind(xi) succeeds and returns a fully zonked kind
818
819 Note that the left-hand type of co is *always* precisely xi. The right-hand
820 type may or may not be ty, however: if ty has unzonked filled-in metavariables,
821 then the right-hand type of co will be the zonked version of ty.
822 It is for this reason that we
823 occasionally have to explicitly zonk, when (co :: xi ~ ty) is important
824 even before we zonk the whole program. For example, see the FTRNotFollowed
825 case in flattenTyVar.
826
827 Why have these invariants on flattening? Because we sometimes use tcTypeKind
828 during canonicalisation, and we want this kind to be zonked (e.g., see
829 TcCanonical.canEqTyVar).
830
831 Flattening is always homogeneous. That is, the kind of the result of flattening is
832 always the same as the kind of the input, modulo zonking. More formally:
833
834 (F2) tcTypeKind(xi) `eqType` zonk(tcTypeKind(ty))
835
836 This invariant means that the kind of a flattened type might not itself be flat.
837
838 Recall that in comments we use alpha[flat = ty] to represent a
839 flattening skolem variable alpha which has been generated to stand in
840 for ty.
841
842 ----- Example of flattening a constraint: ------
843 flatten (List (F (G Int))) ==> (xi, cc)
844 where
845 xi = List alpha
846 cc = { G Int ~ beta[flat = G Int],
847 F beta ~ alpha[flat = F beta] }
848 Here
849 * alpha and beta are 'flattening skolem variables'.
850 * All the constraints in cc are 'given', and all their coercion terms
851 are the identity.
852
853 NB: Flattening Skolems only occur in canonical constraints, which
854 are never zonked, so we don't need to worry about zonking doing
855 accidental unflattening.
856
857 Note that we prefer to leave type synonyms unexpanded when possible,
858 so when the flattener encounters one, it first asks whether its
859 transitive expansion contains any type function applications. If so,
860 it expands the synonym and proceeds; if not, it simply returns the
861 unexpanded synonym.
862
863 Note [flatten_args performance]
864 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
865 In programs with lots of type-level evaluation, flatten_args becomes
866 part of a tight loop. For example, see test perf/compiler/T9872a, which
867 calls flatten_args a whopping 7,106,808 times. It is thus important
868 that flatten_args be efficient.
869
870 Performance testing showed that the current implementation is indeed
871 efficient. It's critically important that zipWithAndUnzipM be
872 specialized to TcS, and it's also quite helpful to actually `inline`
873 it. On test T9872a, here are the allocation stats (Dec 16, 2014):
874
875 * Unspecialized, uninlined: 8,472,613,440 bytes allocated in the heap
876 * Specialized, uninlined: 6,639,253,488 bytes allocated in the heap
877 * Specialized, inlined: 6,281,539,792 bytes allocated in the heap
878
879 To improve performance even further, flatten_args_nom is split off
880 from flatten_args, as nominal equality is the common case. This would
881 be natural to write using mapAndUnzipM, but even inlined, that function
882 is not as performant as a hand-written loop.
883
884 * mapAndUnzipM, inlined: 7,463,047,432 bytes allocated in the heap
885 * hand-written recursion: 5,848,602,848 bytes allocated in the heap
886
887 If you make any change here, pay close attention to the T9872{a,b,c} tests
888 and T5321Fun.
889
890 If we need to make this yet more performant, a possible way forward is to
891 duplicate the flattener code for the nominal case, and make that case
892 faster. This doesn't seem quite worth it, yet.
893
894 Note [flatten_exact_fam_app_fully performance]
895 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
896
897 The refactor of GRefl seems to cause performance trouble for T9872x: the allocation of flatten_exact_fam_app_fully_performance increased. See note [Generalized reflexive coercion] in TyCoRep for more information about GRefl and #15192 for the current state.
898
899 The explicit pattern match in homogenise_result helps with T9872a, b, c.
900
901 Still, it increases the expected allocation of T9872d by ~2%.
902
903 TODO: a step-by-step replay of the refactor to analyze the performance.
904
905 -}
906
907 {-# INLINE flatten_args_tc #-}
908 flatten_args_tc
909 :: TyCon -- T
910 -> [Role] -- Role r
911 -> [Type] -- Arg types [t1,..,tn]
912 -> FlatM ( [Xi] -- List of flattened args [x1,..,xn]
913 -- 1-1 corresp with [t1,..,tn]
914 , [Coercion] -- List of arg coercions [co1,..,con]
915 -- 1-1 corresp with [t1,..,tn]
916 -- coi :: xi ~r ti
917 , CoercionN) -- Result coercion, rco
918 -- rco : (T t1..tn) ~N (T (x1 |> co1) .. (xn |> con))
919 flatten_args_tc tc = flatten_args all_bndrs any_named_bndrs inner_ki emptyVarSet
920 -- NB: TyCon kinds are always closed
921 where
922 (bndrs, named)
923 = ty_con_binders_ty_binders' (tyConBinders tc)
924 -- it's possible that the result kind has arrows (for, e.g., a type family)
925 -- so we must split it
926 (inner_bndrs, inner_ki, inner_named) = split_pi_tys' (tyConResKind tc)
927 !all_bndrs = bndrs `chkAppend` inner_bndrs
928 !any_named_bndrs = named || inner_named
929 -- NB: Those bangs there drop allocations in T9872{a,c,d} by 8%.
930
931 {-# INLINE flatten_args #-}
932 flatten_args :: [TyCoBinder] -> Bool -- Binders, and True iff any of them are
933 -- named.
934 -> Kind -> TcTyCoVarSet -- function kind; kind's free vars
935 -> [Role] -> [Type] -- these are in 1-to-1 correspondence
936 -> FlatM ([Xi], [Coercion], CoercionN)
937 -- Coercions :: Xi ~ Type, at roles given
938 -- Third coercion :: tcTypeKind(fun xis) ~N tcTypeKind(fun tys)
939 -- That is, the third coercion relates the kind of some function (whose kind is
940 -- passed as the first parameter) instantiated at xis to the kind of that
941 -- function instantiated at the tys. This is useful in keeping flattening
942 -- homoegeneous. The list of roles must be at least as long as the list of
943 -- types.
944 flatten_args orig_binders
945 any_named_bndrs
946 orig_inner_ki
947 orig_fvs
948 orig_roles
949 orig_tys
950 = if any_named_bndrs
951 then flatten_args_slow orig_binders
952 orig_inner_ki
953 orig_fvs
954 orig_roles
955 orig_tys
956 else flatten_args_fast orig_binders orig_inner_ki orig_roles orig_tys
957
958 {-# INLINE flatten_args_fast #-}
959 -- | fast path flatten_args, in which none of the binders are named and
960 -- therefore we can avoid tracking a lifting context.
961 -- There are many bang patterns in here. It's been observed that they
962 -- greatly improve performance of an optimized build.
963 -- The T9872 test cases are good witnesses of this fact.
964 flatten_args_fast :: [TyCoBinder]
965 -> Kind
966 -> [Role]
967 -> [Type]
968 -> FlatM ([Xi], [Coercion], CoercionN)
969 flatten_args_fast orig_binders orig_inner_ki orig_roles orig_tys
970 = fmap finish (iterate orig_tys orig_roles orig_binders)
971 where
972
973 iterate :: [Type]
974 -> [Role]
975 -> [TyCoBinder]
976 -> FlatM ([Xi], [Coercion], [TyCoBinder])
977 iterate (ty:tys) (role:roles) (_:binders) = do
978 (xi, co) <- go role ty
979 (xis, cos, binders) <- iterate tys roles binders
980 pure (xi : xis, co : cos, binders)
981 iterate [] _ binders = pure ([], [], binders)
982 iterate _ _ _ = pprPanic
983 "flatten_args wandered into deeper water than usual" (vcat [])
984 -- This debug information is commented out because leaving it in
985 -- causes a ~2% increase in allocations in T9872{a,c,d}.
986 {-
987 (vcat [ppr orig_binders,
988 ppr orig_inner_ki,
989 ppr (take 10 orig_roles), -- often infinite!
990 ppr orig_tys])
991 -}
992
993 {-# INLINE go #-}
994 go :: Role
995 -> Type
996 -> FlatM (Xi, Coercion)
997 go role ty
998 = case role of
999 -- In the slow path we bind the Xi and Coercion from the recursive
1000 -- call and then use it such
1001 --
1002 -- let kind_co = mkTcSymCo $ mkReflCo Nominal (tyBinderType binder)
1003 -- casted_xi = xi `mkCastTy` kind_co
1004 -- casted_co = xi |> kind_co ~r xi ; co
1005 --
1006 -- but this isn't necessary:
1007 -- mkTcSymCo (Refl a b) = Refl a b,
1008 -- mkCastTy x (Refl _ _) = x
1009 -- mkTcGReflLeftCo _ ty (Refl _ _) `mkTransCo` co = co
1010 --
1011 -- Also, no need to check isAnonTyCoBinder or isNamedBinder, since
1012 -- we've already established that they're all anonymous.
1013 Nominal -> setEqRel NomEq $ flatten_one ty
1014 Representational -> setEqRel ReprEq $ flatten_one ty
1015 Phantom -> -- See Note [Phantoms in the flattener]
1016 do { ty <- liftTcS $ zonkTcType ty
1017 ; return (ty, mkReflCo Phantom ty) }
1018
1019
1020 {-# INLINE finish #-}
1021 finish :: ([Xi], [Coercion], [TyCoBinder]) -> ([Xi], [Coercion], CoercionN)
1022 finish (xis, cos, binders) = (xis, cos, kind_co)
1023 where
1024 final_kind = mkPiTys binders orig_inner_ki
1025 kind_co = mkNomReflCo final_kind
1026
1027 {-# INLINE flatten_args_slow #-}
1028 -- | Slow path, compared to flatten_args_fast, because this one must track
1029 -- a lifting context.
1030 flatten_args_slow :: [TyCoBinder] -> Kind -> TcTyCoVarSet
1031 -> [Role] -> [Type]
1032 -> FlatM ([Xi], [Coercion], CoercionN)
1033 flatten_args_slow binders inner_ki fvs roles tys
1034 -- Arguments used dependently must be flattened with proper coercions, but
1035 -- we're not guaranteed to get a proper coercion when flattening with the
1036 -- "Derived" flavour. So we must call noBogusCoercions when flattening arguments
1037 -- corresponding to binders that are dependent. However, we might legitimately
1038 -- have *more* arguments than binders, in the case that the inner_ki is a variable
1039 -- that gets instantiated with a Π-type. We conservatively choose not to produce
1040 -- bogus coercions for these, too. Note that this might miss an opportunity for
1041 -- a Derived rewriting a Derived. The solution would be to generate evidence for
1042 -- Deriveds, thus avoiding this whole noBogusCoercions idea. See also
1043 -- Note [No derived kind equalities]
1044 = do { flattened_args <- zipWith3M fl (map isNamedBinder binders ++ repeat True)
1045 roles tys
1046 ; return (simplifyArgsWorker binders inner_ki fvs roles flattened_args) }
1047 where
1048 {-# INLINE fl #-}
1049 fl :: Bool -- must we ensure to produce a real coercion here?
1050 -- see comment at top of function
1051 -> Role -> Type -> FlatM (Xi, Coercion)
1052 fl True r ty = noBogusCoercions $ fl1 r ty
1053 fl False r ty = fl1 r ty
1054
1055 {-# INLINE fl1 #-}
1056 fl1 :: Role -> Type -> FlatM (Xi, Coercion)
1057 fl1 Nominal ty
1058 = setEqRel NomEq $
1059 flatten_one ty
1060
1061 fl1 Representational ty
1062 = setEqRel ReprEq $
1063 flatten_one ty
1064
1065 fl1 Phantom ty
1066 -- See Note [Phantoms in the flattener]
1067 = do { ty <- liftTcS $ zonkTcType ty
1068 ; return (ty, mkReflCo Phantom ty) }
1069
1070 ------------------
1071 flatten_one :: TcType -> FlatM (Xi, Coercion)
1072 -- Flatten a type to get rid of type function applications, returning
1073 -- the new type-function-free type, and a collection of new equality
1074 -- constraints. See Note [Flattening] for more detail.
1075 --
1076 -- Postcondition: Coercion :: Xi ~ TcType
1077 -- The role on the result coercion matches the EqRel in the FlattenEnv
1078
1079 flatten_one xi@(LitTy {})
1080 = do { role <- getRole
1081 ; return (xi, mkReflCo role xi) }
1082
1083 flatten_one (TyVarTy tv)
1084 = flattenTyVar tv
1085
1086 flatten_one (AppTy ty1 ty2)
1087 = flatten_app_tys ty1 [ty2]
1088
1089 flatten_one (TyConApp tc tys)
1090 -- Expand type synonyms that mention type families
1091 -- on the RHS; see Note [Flattening synonyms]
1092 | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
1093 , let expanded_ty = mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys'
1094 = do { mode <- getMode
1095 ; case mode of
1096 FM_FlattenAll | not (isFamFreeTyCon tc)
1097 -> flatten_one expanded_ty
1098 _ -> flatten_ty_con_app tc tys }
1099
1100 -- Otherwise, it's a type function application, and we have to
1101 -- flatten it away as well, and generate a new given equality constraint
1102 -- between the application and a newly generated flattening skolem variable.
1103 | isTypeFamilyTyCon tc
1104 = flatten_fam_app tc tys
1105
1106 -- For * a normal data type application
1107 -- * data family application
1108 -- we just recursively flatten the arguments.
1109 | otherwise
1110 -- FM_Avoid stuff commented out; see Note [Lazy flattening]
1111 -- , let fmode' = case fmode of -- Switch off the flat_top bit in FM_Avoid
1112 -- FE { fe_mode = FM_Avoid tv _ }
1113 -- -> fmode { fe_mode = FM_Avoid tv False }
1114 -- _ -> fmode
1115 = flatten_ty_con_app tc tys
1116
1117 flatten_one ty@(FunTy _ ty1 ty2)
1118 = do { (xi1,co1) <- flatten_one ty1
1119 ; (xi2,co2) <- flatten_one ty2
1120 ; role <- getRole
1121 ; return (ty { ft_arg = xi1, ft_res = xi2 }
1122 , mkFunCo role co1 co2) }
1123
1124 flatten_one ty@(ForAllTy {})
1125 -- TODO (RAE): This is inadequate, as it doesn't flatten the kind of
1126 -- the bound tyvar. Doing so will require carrying around a substitution
1127 -- and the usual substTyVarBndr-like silliness. Argh.
1128
1129 -- We allow for-alls when, but only when, no type function
1130 -- applications inside the forall involve the bound type variables.
1131 = do { let (bndrs, rho) = tcSplitForAllVarBndrs ty
1132 tvs = binderVars bndrs
1133 ; (rho', co) <- setMode FM_SubstOnly $ flatten_one rho
1134 -- Substitute only under a forall
1135 -- See Note [Flattening under a forall]
1136 ; return (mkForAllTys bndrs rho', mkHomoForAllCos tvs co) }
1137
1138 flatten_one (CastTy ty g)
1139 = do { (xi, co) <- flatten_one ty
1140 ; (g', _) <- flatten_co g
1141
1142 ; role <- getRole
1143 ; return (mkCastTy xi g', castCoercionKind co role xi ty g' g) }
1144
1145 flatten_one (CoercionTy co) = first mkCoercionTy <$> flatten_co co
1146
1147 -- | "Flatten" a coercion. Really, just zonk it so we can uphold
1148 -- (F1) of Note [Flattening]
1149 flatten_co :: Coercion -> FlatM (Coercion, Coercion)
1150 flatten_co co
1151 = do { co <- liftTcS $ zonkCo co
1152 ; env_role <- getRole
1153 ; let co' = mkTcReflCo env_role (mkCoercionTy co)
1154 ; return (co, co') }
1155
1156 -- flatten (nested) AppTys
1157 flatten_app_tys :: Type -> [Type] -> FlatM (Xi, Coercion)
1158 -- commoning up nested applications allows us to look up the function's kind
1159 -- only once. Without commoning up like this, we would spend a quadratic amount
1160 -- of time looking up functions' types
1161 flatten_app_tys (AppTy ty1 ty2) tys = flatten_app_tys ty1 (ty2:tys)
1162 flatten_app_tys fun_ty arg_tys
1163 = do { (fun_xi, fun_co) <- flatten_one fun_ty
1164 ; flatten_app_ty_args fun_xi fun_co arg_tys }
1165
1166 -- Given a flattened function (with the coercion produced by flattening) and
1167 -- a bunch of unflattened arguments, flatten the arguments and apply.
1168 -- The coercion argument's role matches the role stored in the FlatM monad.
1169 --
1170 -- The bang patterns used here were observed to improve performance. If you
1171 -- wish to remove them, be sure to check for regeressions in allocations.
1172 flatten_app_ty_args :: Xi -> Coercion -> [Type] -> FlatM (Xi, Coercion)
1173 flatten_app_ty_args fun_xi fun_co []
1174 -- this will be a common case when called from flatten_fam_app, so shortcut
1175 = return (fun_xi, fun_co)
1176 flatten_app_ty_args fun_xi fun_co arg_tys
1177 = do { (xi, co, kind_co) <- case tcSplitTyConApp_maybe fun_xi of
1178 Just (tc, xis) ->
1179 do { let tc_roles = tyConRolesRepresentational tc
1180 arg_roles = dropList xis tc_roles
1181 ; (arg_xis, arg_cos, kind_co)
1182 <- flatten_vector (tcTypeKind fun_xi) arg_roles arg_tys
1183
1184 -- Here, we have fun_co :: T xi1 xi2 ~ ty
1185 -- and we need to apply fun_co to the arg_cos. The problem is
1186 -- that using mkAppCo is wrong because that function expects
1187 -- its second coercion to be Nominal, and the arg_cos might
1188 -- not be. The solution is to use transitivity:
1189 -- T <xi1> <xi2> arg_cos ;; fun_co <arg_tys>
1190 ; eq_rel <- getEqRel
1191 ; let app_xi = mkTyConApp tc (xis ++ arg_xis)
1192 app_co = case eq_rel of
1193 NomEq -> mkAppCos fun_co arg_cos
1194 ReprEq -> mkTcTyConAppCo Representational tc
1195 (zipWith mkReflCo tc_roles xis ++ arg_cos)
1196 `mkTcTransCo`
1197 mkAppCos fun_co (map mkNomReflCo arg_tys)
1198 ; return (app_xi, app_co, kind_co) }
1199 Nothing ->
1200 do { (arg_xis, arg_cos, kind_co)
1201 <- flatten_vector (tcTypeKind fun_xi) (repeat Nominal) arg_tys
1202 ; let arg_xi = mkAppTys fun_xi arg_xis
1203 arg_co = mkAppCos fun_co arg_cos
1204 ; return (arg_xi, arg_co, kind_co) }
1205
1206 ; role <- getRole
1207 ; return (homogenise_result xi co role kind_co) }
1208
1209 flatten_ty_con_app :: TyCon -> [TcType] -> FlatM (Xi, Coercion)
1210 flatten_ty_con_app tc tys
1211 = do { role <- getRole
1212 ; (xis, cos, kind_co) <- flatten_args_tc tc (tyConRolesX role tc) tys
1213 ; let tyconapp_xi = mkTyConApp tc xis
1214 tyconapp_co = mkTyConAppCo role tc cos
1215 ; return (homogenise_result tyconapp_xi tyconapp_co role kind_co) }
1216
1217 -- Make the result of flattening homogeneous (Note [Flattening] (F2))
1218 homogenise_result :: Xi -- a flattened type
1219 -> Coercion -- :: xi ~r original ty
1220 -> Role -- r
1221 -> CoercionN -- kind_co :: tcTypeKind(xi) ~N tcTypeKind(ty)
1222 -> (Xi, Coercion) -- (xi |> kind_co, (xi |> kind_co)
1223 -- ~r original ty)
1224 homogenise_result xi co r kind_co
1225 -- the explicit pattern match here improves the performance of T9872a, b, c by
1226 -- ~2%
1227 | isGReflCo kind_co = (xi `mkCastTy` kind_co, co)
1228 | otherwise = (xi `mkCastTy` kind_co
1229 , (mkSymCo $ GRefl r xi (MCo kind_co)) `mkTransCo` co)
1230 {-# INLINE homogenise_result #-}
1231
1232 -- Flatten a vector (list of arguments).
1233 flatten_vector :: Kind -- of the function being applied to these arguments
1234 -> [Role] -- If we're flatten w.r.t. ReprEq, what roles do the
1235 -- args have?
1236 -> [Type] -- the args to flatten
1237 -> FlatM ([Xi], [Coercion], CoercionN)
1238 flatten_vector ki roles tys
1239 = do { eq_rel <- getEqRel
1240 ; case eq_rel of
1241 NomEq -> flatten_args bndrs
1242 any_named_bndrs
1243 inner_ki
1244 fvs
1245 (repeat Nominal)
1246 tys
1247 ReprEq -> flatten_args bndrs
1248 any_named_bndrs
1249 inner_ki
1250 fvs
1251 roles
1252 tys
1253 }
1254 where
1255 (bndrs, inner_ki, any_named_bndrs) = split_pi_tys' ki
1256 fvs = tyCoVarsOfType ki
1257 {-# INLINE flatten_vector #-}
1258
1259 {-
1260 Note [Flattening synonyms]
1261 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1262 Not expanding synonyms aggressively improves error messages, and
1263 keeps types smaller. But we need to take care.
1264
1265 Suppose
1266 type T a = a -> a
1267 and we want to flatten the type (T (F a)). Then we can safely flatten
1268 the (F a) to a skolem, and return (T fsk). We don't need to expand the
1269 synonym. This works because TcTyConAppCo can deal with synonyms
1270 (unlike TyConAppCo), see Note [TcCoercions] in TcEvidence.
1271
1272 But (#8979) for
1273 type T a = (F a, a) where F is a type function
1274 we must expand the synonym in (say) T Int, to expose the type function
1275 to the flattener.
1276
1277
1278 Note [Flattening under a forall]
1279 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1280 Under a forall, we
1281 (a) MUST apply the inert substitution
1282 (b) MUST NOT flatten type family applications
1283 Hence FMSubstOnly.
1284
1285 For (a) consider c ~ a, a ~ T (forall b. (b, [c]))
1286 If we don't apply the c~a substitution to the second constraint
1287 we won't see the occurs-check error.
1288
1289 For (b) consider (a ~ forall b. F a b), we don't want to flatten
1290 to (a ~ forall b.fsk, F a b ~ fsk)
1291 because now the 'b' has escaped its scope. We'd have to flatten to
1292 (a ~ forall b. fsk b, forall b. F a b ~ fsk b)
1293 and we have not begun to think about how to make that work!
1294
1295 ************************************************************************
1296 * *
1297 Flattening a type-family application
1298 * *
1299 ************************************************************************
1300 -}
1301
1302 flatten_fam_app :: TyCon -> [TcType] -> FlatM (Xi, Coercion)
1303 -- flatten_fam_app can be over-saturated
1304 -- flatten_exact_fam_app is exactly saturated
1305 -- flatten_exact_fam_app_fully lifts out the application to top level
1306 -- Postcondition: Coercion :: Xi ~ F tys
1307 flatten_fam_app tc tys -- Can be over-saturated
1308 = ASSERT2( tys `lengthAtLeast` tyConArity tc
1309 , ppr tc $$ ppr (tyConArity tc) $$ ppr tys)
1310
1311 do { mode <- getMode
1312 ; case mode of
1313 { FM_SubstOnly -> flatten_ty_con_app tc tys
1314 ; FM_FlattenAll ->
1315
1316 -- Type functions are saturated
1317 -- The type function might be *over* saturated
1318 -- in which case the remaining arguments should
1319 -- be dealt with by AppTys
1320 do { let (tys1, tys_rest) = splitAt (tyConArity tc) tys
1321 ; (xi1, co1) <- flatten_exact_fam_app_fully tc tys1
1322 -- co1 :: xi1 ~ F tys1
1323
1324 ; flatten_app_ty_args xi1 co1 tys_rest } } }
1325
1326 -- the [TcType] exactly saturate the TyCon
1327 -- See note [flatten_exact_fam_app_fully performance]
1328 flatten_exact_fam_app_fully :: TyCon -> [TcType] -> FlatM (Xi, Coercion)
1329 flatten_exact_fam_app_fully tc tys
1330 -- See Note [Reduce type family applications eagerly]
1331 -- the following tcTypeKind should never be evaluated, as it's just used in
1332 -- casting, and casts by refl are dropped
1333 = do { mOut <- try_to_reduce_nocache tc tys
1334 ; case mOut of
1335 Just out -> pure out
1336 Nothing -> do
1337 { -- First, flatten the arguments
1338 ; (xis, cos, kind_co)
1339 <- setEqRel NomEq $ -- just do this once, instead of for
1340 -- each arg
1341 flatten_args_tc tc (repeat Nominal) tys
1342 -- kind_co :: tcTypeKind(F xis) ~N tcTypeKind(F tys)
1343 ; eq_rel <- getEqRel
1344 ; cur_flav <- getFlavour
1345 ; let role = eqRelRole eq_rel
1346 ret_co = mkTyConAppCo role tc cos
1347 -- ret_co :: F xis ~ F tys; might be heterogeneous
1348
1349 -- Now, look in the cache
1350 ; mb_ct <- liftTcS $ lookupFlatCache tc xis
1351 ; case mb_ct of
1352 Just (co, rhs_ty, flav) -- co :: F xis ~ fsk
1353 -- flav is [G] or [WD]
1354 -- See Note [Type family equations] in TcSMonad
1355 | (NotSwapped, _) <- flav `funEqCanDischargeF` cur_flav
1356 -> -- Usable hit in the flat-cache
1357 do { traceFlat "flatten/flat-cache hit" $
1358 (ppr tc <+> ppr xis $$ ppr rhs_ty)
1359 ; (fsk_xi, fsk_co) <- flatten_one rhs_ty
1360 -- The fsk may already have been unified, so
1361 -- flatten it
1362 -- fsk_co :: fsk_xi ~ fsk
1363 ; let xi = fsk_xi `mkCastTy` kind_co
1364 co' = mkTcCoherenceLeftCo role fsk_xi kind_co fsk_co
1365 `mkTransCo`
1366 maybeSubCo eq_rel (mkSymCo co)
1367 `mkTransCo` ret_co
1368 ; return (xi, co')
1369 }
1370 -- :: fsk_xi ~ F xis
1371
1372 -- Try to reduce the family application right now
1373 -- See Note [Reduce type family applications eagerly]
1374 _ -> do { mOut <- try_to_reduce tc
1375 xis
1376 kind_co
1377 (`mkTransCo` ret_co)
1378 ; case mOut of
1379 Just out -> pure out
1380 Nothing -> do
1381 { loc <- getLoc
1382 ; (ev, co, fsk) <- liftTcS $
1383 newFlattenSkolem cur_flav loc tc xis
1384
1385 -- The new constraint (F xis ~ fsk) is not
1386 -- necessarily inert (e.g. the LHS may be a
1387 -- redex) so we must put it in the work list
1388 ; let ct = CFunEqCan { cc_ev = ev
1389 , cc_fun = tc
1390 , cc_tyargs = xis
1391 , cc_fsk = fsk }
1392 ; emitFlatWork ct
1393
1394 ; traceFlat "flatten/flat-cache miss" $
1395 (ppr tc <+> ppr xis $$ ppr fsk $$ ppr ev)
1396
1397 -- NB: fsk's kind is already flattened because
1398 -- the xis are flattened
1399 ; let fsk_ty = mkTyVarTy fsk
1400 xi = fsk_ty `mkCastTy` kind_co
1401 co' = mkTcCoherenceLeftCo role fsk_ty kind_co (maybeSubCo eq_rel (mkSymCo co))
1402 `mkTransCo` ret_co
1403 ; return (xi, co')
1404 }
1405 }
1406 }
1407 }
1408
1409 where
1410
1411 -- try_to_reduce and try_to_reduce_nocache (below) could be unified into
1412 -- a more general definition, but it was observed that separating them
1413 -- gives better performance (lower allocation numbers in T9872x).
1414
1415 try_to_reduce :: TyCon -- F, family tycon
1416 -> [Type] -- args, not necessarily flattened
1417 -> CoercionN -- kind_co :: tcTypeKind(F args) ~N
1418 -- tcTypeKind(F orig_args)
1419 -- where
1420 -- orig_args is what was passed to the outer
1421 -- function
1422 -> ( Coercion -- :: (xi |> kind_co) ~ F args
1423 -> Coercion ) -- what to return from outer function
1424 -> FlatM (Maybe (Xi, Coercion))
1425 try_to_reduce tc tys kind_co update_co
1426 = do { checkStackDepth (mkTyConApp tc tys)
1427 ; mb_match <- liftTcS $ matchFam tc tys
1428 ; case mb_match of
1429 -- NB: norm_co will always be homogeneous. All type families
1430 -- are homogeneous.
1431 Just (norm_co, norm_ty)
1432 -> do { traceFlat "Eager T.F. reduction success" $
1433 vcat [ ppr tc, ppr tys, ppr norm_ty
1434 , ppr norm_co <+> dcolon
1435 <+> ppr (coercionKind norm_co)
1436 ]
1437 ; (xi, final_co) <- bumpDepth $ flatten_one norm_ty
1438 ; eq_rel <- getEqRel
1439 ; let co = maybeSubCo eq_rel norm_co
1440 `mkTransCo` mkSymCo final_co
1441 ; flavour <- getFlavour
1442 -- NB: only extend cache with nominal equalities
1443 ; when (eq_rel == NomEq) $
1444 liftTcS $
1445 extendFlatCache tc tys ( co, xi, flavour )
1446 ; let role = eqRelRole eq_rel
1447 xi' = xi `mkCastTy` kind_co
1448 co' = update_co $
1449 mkTcCoherenceLeftCo role xi kind_co (mkSymCo co)
1450 ; return $ Just (xi', co') }
1451 Nothing -> pure Nothing }
1452
1453 try_to_reduce_nocache :: TyCon -- F, family tycon
1454 -> [Type] -- args, not necessarily flattened
1455 -> FlatM (Maybe (Xi, Coercion))
1456 try_to_reduce_nocache tc tys
1457 = do { checkStackDepth (mkTyConApp tc tys)
1458 ; mb_match <- liftTcS $ matchFam tc tys
1459 ; case mb_match of
1460 -- NB: norm_co will always be homogeneous. All type families
1461 -- are homogeneous.
1462 Just (norm_co, norm_ty)
1463 -> do { (xi, final_co) <- bumpDepth $ flatten_one norm_ty
1464 ; eq_rel <- getEqRel
1465 ; let co = mkSymCo (maybeSubCo eq_rel norm_co
1466 `mkTransCo` mkSymCo final_co)
1467 ; return $ Just (xi, co) }
1468 Nothing -> pure Nothing }
1469
1470 {- Note [Reduce type family applications eagerly]
1471 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1472 If we come across a type-family application like (Append (Cons x Nil) t),
1473 then, rather than flattening to a skolem etc, we may as well just reduce
1474 it on the spot to (Cons x t). This saves a lot of intermediate steps.
1475 Examples that are helped are tests T9872, and T5321Fun.
1476
1477 Performance testing indicates that it's best to try this *twice*, once
1478 before flattening arguments and once after flattening arguments.
1479 Adding the extra reduction attempt before flattening arguments cut
1480 the allocation amounts for the T9872{a,b,c} tests by half.
1481
1482 An example of where the early reduction appears helpful:
1483
1484 type family Last x where
1485 Last '[x] = x
1486 Last (h ': t) = Last t
1487
1488 workitem: (x ~ Last '[1,2,3,4,5,6])
1489
1490 Flattening the argument never gets us anywhere, but trying to flatten
1491 it at every step is quadratic in the length of the list. Reducing more
1492 eagerly makes simplifying the right-hand type linear in its length.
1493
1494 Testing also indicated that the early reduction should *not* use the
1495 flat-cache, but that the later reduction *should*. (Although the
1496 effect was not large.) Hence the Bool argument to try_to_reduce. To
1497 me (SLPJ) this seems odd; I get that eager reduction usually succeeds;
1498 and if don't use the cache for eager reduction, we will miss most of
1499 the opportunities for using it at all. More exploration would be good
1500 here.
1501
1502 At the end, once we've got a flat rhs, we extend the flatten-cache to record
1503 the result. Doing so can save lots of work when the same redex shows up more
1504 than once. Note that we record the link from the redex all the way to its
1505 *final* value, not just the single step reduction. Interestingly, using the
1506 flat-cache for the first reduction resulted in an increase in allocations
1507 of about 3% for the four T9872x tests. However, using the flat-cache in
1508 the later reduction is a similar gain. I (Richard E) don't currently (Dec '14)
1509 have any knowledge as to *why* these facts are true.
1510
1511 ************************************************************************
1512 * *
1513 Flattening a type variable
1514 * *
1515 ********************************************************************* -}
1516
1517 -- | The result of flattening a tyvar "one step".
1518 data FlattenTvResult
1519 = FTRNotFollowed
1520 -- ^ The inert set doesn't make the tyvar equal to anything else
1521
1522 | FTRFollowed TcType Coercion
1523 -- ^ The tyvar flattens to a not-necessarily flat other type.
1524 -- co :: new type ~r old type, where the role is determined by
1525 -- the FlattenEnv
1526
1527 flattenTyVar :: TyVar -> FlatM (Xi, Coercion)
1528 flattenTyVar tv
1529 = do { mb_yes <- flatten_tyvar1 tv
1530 ; case mb_yes of
1531 FTRFollowed ty1 co1 -- Recur
1532 -> do { (ty2, co2) <- flatten_one ty1
1533 -- ; traceFlat "flattenTyVar2" (ppr tv $$ ppr ty2)
1534 ; return (ty2, co2 `mkTransCo` co1) }
1535
1536 FTRNotFollowed -- Done, but make sure the kind is zonked
1537 -- Note [Flattening] invariant (F1)
1538 -> do { tv' <- liftTcS $ updateTyVarKindM zonkTcType tv
1539 ; role <- getRole
1540 ; let ty' = mkTyVarTy tv'
1541 ; return (ty', mkTcReflCo role ty') } }
1542
1543 flatten_tyvar1 :: TcTyVar -> FlatM FlattenTvResult
1544 -- "Flattening" a type variable means to apply the substitution to it
1545 -- Specifically, look up the tyvar in
1546 -- * the internal MetaTyVar box
1547 -- * the inerts
1548 -- See also the documentation for FlattenTvResult
1549
1550 flatten_tyvar1 tv
1551 = do { mb_ty <- liftTcS $ isFilledMetaTyVar_maybe tv
1552 ; case mb_ty of
1553 Just ty -> do { traceFlat "Following filled tyvar"
1554 (ppr tv <+> equals <+> ppr ty)
1555 ; role <- getRole
1556 ; return (FTRFollowed ty (mkReflCo role ty)) } ;
1557 Nothing -> do { traceFlat "Unfilled tyvar" (ppr tv)
1558 ; fr <- getFlavourRole
1559 ; flatten_tyvar2 tv fr } }
1560
1561 flatten_tyvar2 :: TcTyVar -> CtFlavourRole -> FlatM FlattenTvResult
1562 -- The tyvar is not a filled-in meta-tyvar
1563 -- Try in the inert equalities
1564 -- See Definition [Applying a generalised substitution] in TcSMonad
1565 -- See Note [Stability of flattening] in TcSMonad
1566
1567 flatten_tyvar2 tv fr@(_, eq_rel)
1568 = do { ieqs <- liftTcS $ getInertEqs
1569 ; mode <- getMode
1570 ; case lookupDVarEnv ieqs tv of
1571 Just (ct:_) -- If the first doesn't work,
1572 -- the subsequent ones won't either
1573 | CTyEqCan { cc_ev = ctev, cc_tyvar = tv
1574 , cc_rhs = rhs_ty, cc_eq_rel = ct_eq_rel } <- ct
1575 , let ct_fr = (ctEvFlavour ctev, ct_eq_rel)
1576 , ct_fr `eqCanRewriteFR` fr -- This is THE key call of eqCanRewriteFR
1577 -> do { traceFlat "Following inert tyvar"
1578 (ppr mode <+>
1579 ppr tv <+>
1580 equals <+>
1581 ppr rhs_ty $$ ppr ctev)
1582 ; let rewrite_co1 = mkSymCo (ctEvCoercion ctev)
1583 rewrite_co = case (ct_eq_rel, eq_rel) of
1584 (ReprEq, _rel) -> ASSERT( _rel == ReprEq )
1585 -- if this ASSERT fails, then
1586 -- eqCanRewriteFR answered incorrectly
1587 rewrite_co1
1588 (NomEq, NomEq) -> rewrite_co1
1589 (NomEq, ReprEq) -> mkSubCo rewrite_co1
1590
1591 ; return (FTRFollowed rhs_ty rewrite_co) }
1592 -- NB: ct is Derived then fmode must be also, hence
1593 -- we are not going to touch the returned coercion
1594 -- so ctEvCoercion is fine.
1595
1596 _other -> return FTRNotFollowed }
1597
1598 {-
1599 Note [An alternative story for the inert substitution]
1600 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1601 (This entire note is just background, left here in case we ever want
1602 to return the previous state of affairs)
1603
1604 We used (GHC 7.8) to have this story for the inert substitution inert_eqs
1605
1606 * 'a' is not in fvs(ty)
1607 * They are *inert* in the weaker sense that there is no infinite chain of
1608 (i1 `eqCanRewrite` i2), (i2 `eqCanRewrite` i3), etc
1609
1610 This means that flattening must be recursive, but it does allow
1611 [G] a ~ [b]
1612 [G] b ~ Maybe c
1613
1614 This avoids "saturating" the Givens, which can save a modest amount of work.
1615 It is easy to implement, in TcInteract.kick_out, by only kicking out an inert
1616 only if (a) the work item can rewrite the inert AND
1617 (b) the inert cannot rewrite the work item
1618
1619 This is significantly harder to think about. It can save a LOT of work
1620 in occurs-check cases, but we don't care about them much. #5837
1621 is an example; all the constraints here are Givens
1622
1623 [G] a ~ TF (a,Int)
1624 -->
1625 work TF (a,Int) ~ fsk
1626 inert fsk ~ a
1627
1628 --->
1629 work fsk ~ (TF a, TF Int)
1630 inert fsk ~ a
1631
1632 --->
1633 work a ~ (TF a, TF Int)
1634 inert fsk ~ a
1635
1636 ---> (attempting to flatten (TF a) so that it does not mention a
1637 work TF a ~ fsk2
1638 inert a ~ (fsk2, TF Int)
1639 inert fsk ~ (fsk2, TF Int)
1640
1641 ---> (substitute for a)
1642 work TF (fsk2, TF Int) ~ fsk2
1643 inert a ~ (fsk2, TF Int)
1644 inert fsk ~ (fsk2, TF Int)
1645
1646 ---> (top-level reduction, re-orient)
1647 work fsk2 ~ (TF fsk2, TF Int)
1648 inert a ~ (fsk2, TF Int)
1649 inert fsk ~ (fsk2, TF Int)
1650
1651 ---> (attempt to flatten (TF fsk2) to get rid of fsk2
1652 work TF fsk2 ~ fsk3
1653 work fsk2 ~ (fsk3, TF Int)
1654 inert a ~ (fsk2, TF Int)
1655 inert fsk ~ (fsk2, TF Int)
1656
1657 --->
1658 work TF fsk2 ~ fsk3
1659 inert fsk2 ~ (fsk3, TF Int)
1660 inert a ~ ((fsk3, TF Int), TF Int)
1661 inert fsk ~ ((fsk3, TF Int), TF Int)
1662
1663 Because the incoming given rewrites all the inert givens, we get more and
1664 more duplication in the inert set. But this really only happens in pathalogical
1665 casee, so we don't care.
1666
1667
1668 ************************************************************************
1669 * *
1670 Unflattening
1671 * *
1672 ************************************************************************
1673
1674 An unflattening example:
1675 [W] F a ~ alpha
1676 flattens to
1677 [W] F a ~ fmv (CFunEqCan)
1678 [W] fmv ~ alpha (CTyEqCan)
1679 We must solve both!
1680 -}
1681
1682 unflattenWanteds :: Cts -> Cts -> TcS Cts
1683 unflattenWanteds tv_eqs funeqs
1684 = do { tclvl <- getTcLevel
1685
1686 ; traceTcS "Unflattening" $ braces $
1687 vcat [ text "Funeqs =" <+> pprCts funeqs
1688 , text "Tv eqs =" <+> pprCts tv_eqs ]
1689
1690 -- Step 1: unflatten the CFunEqCans, except if that causes an occurs check
1691 -- Occurs check: consider [W] alpha ~ [F alpha]
1692 -- ==> (flatten) [W] F alpha ~ fmv, [W] alpha ~ [fmv]
1693 -- ==> (unify) [W] F [fmv] ~ fmv
1694 -- See Note [Unflatten using funeqs first]
1695 ; funeqs <- foldrBagM unflatten_funeq emptyCts funeqs
1696 ; traceTcS "Unflattening 1" $ braces (pprCts funeqs)
1697
1698 -- Step 2: unify the tv_eqs, if possible
1699 ; tv_eqs <- foldrBagM (unflatten_eq tclvl) emptyCts tv_eqs
1700 ; traceTcS "Unflattening 2" $ braces (pprCts tv_eqs)
1701
1702 -- Step 3: fill any remaining fmvs with fresh unification variables
1703 ; funeqs <- mapBagM finalise_funeq funeqs
1704 ; traceTcS "Unflattening 3" $ braces (pprCts funeqs)
1705
1706 -- Step 4: remove any tv_eqs that look like ty ~ ty
1707 ; tv_eqs <- foldrBagM finalise_eq emptyCts tv_eqs
1708
1709 ; let all_flat = tv_eqs `andCts` funeqs
1710 ; traceTcS "Unflattening done" $ braces (pprCts all_flat)
1711
1712 ; return all_flat }
1713 where
1714 ----------------
1715 unflatten_funeq :: Ct -> Cts -> TcS Cts
1716 unflatten_funeq ct@(CFunEqCan { cc_fun = tc, cc_tyargs = xis
1717 , cc_fsk = fmv, cc_ev = ev }) rest
1718 = do { -- fmv should be an un-filled flatten meta-tv;
1719 -- we now fix its final value by filling it, being careful
1720 -- to observe the occurs check. Zonking will eliminate it
1721 -- altogether in due course
1722 rhs' <- zonkTcType (mkTyConApp tc xis)
1723 ; case occCheckExpand [fmv] rhs' of
1724 Just rhs'' -- Normal case: fill the tyvar
1725 -> do { setReflEvidence ev NomEq rhs''
1726 ; unflattenFmv fmv rhs''
1727 ; return rest }
1728
1729 Nothing -> -- Occurs check
1730 return (ct `consCts` rest) }
1731
1732 unflatten_funeq other_ct _
1733 = pprPanic "unflatten_funeq" (ppr other_ct)
1734
1735 ----------------
1736 finalise_funeq :: Ct -> TcS Ct
1737 finalise_funeq (CFunEqCan { cc_fsk = fmv, cc_ev = ev })
1738 = do { demoteUnfilledFmv fmv
1739 ; return (mkNonCanonical ev) }
1740 finalise_funeq ct = pprPanic "finalise_funeq" (ppr ct)
1741
1742 ----------------
1743 unflatten_eq :: TcLevel -> Ct -> Cts -> TcS Cts
1744 unflatten_eq tclvl ct@(CTyEqCan { cc_ev = ev, cc_tyvar = tv
1745 , cc_rhs = rhs, cc_eq_rel = eq_rel }) rest
1746
1747 | NomEq <- eq_rel -- See Note [Do not unify representational equalities]
1748 -- in TcInteract
1749 , isFmvTyVar tv -- Previously these fmvs were untouchable,
1750 -- but now they are touchable
1751 -- NB: unlike unflattenFmv, filling a fmv here /does/
1752 -- bump the unification count; it is "improvement"
1753 -- Note [Unflattening can force the solver to iterate]
1754 = ASSERT2( tyVarKind tv `eqType` tcTypeKind rhs, ppr ct )
1755 -- CTyEqCan invariant should ensure this is true
1756 do { is_filled <- isFilledMetaTyVar tv
1757 ; elim <- case is_filled of
1758 False -> do { traceTcS "unflatten_eq 2" (ppr ct)
1759 ; tryFill ev tv rhs }
1760 True -> do { traceTcS "unflatten_eq 3" (ppr ct)
1761 ; try_fill_rhs ev tclvl tv rhs }
1762 ; if elim
1763 then do { setReflEvidence ev eq_rel (mkTyVarTy tv)
1764 ; return rest }
1765 else return (ct `consCts` rest) }
1766
1767 | otherwise
1768 = return (ct `consCts` rest)
1769
1770 unflatten_eq _ ct _ = pprPanic "unflatten_irred" (ppr ct)
1771
1772 ----------------
1773 try_fill_rhs ev tclvl lhs_tv rhs
1774 -- Constraint is lhs_tv ~ rhs_tv,
1775 -- and lhs_tv is filled, so try RHS
1776 | Just (rhs_tv, co) <- getCastedTyVar_maybe rhs
1777 -- co :: kind(rhs_tv) ~ kind(lhs_tv)
1778 , isFmvTyVar rhs_tv || (isTouchableMetaTyVar tclvl rhs_tv
1779 && not (isTyVarTyVar rhs_tv))
1780 -- LHS is a filled fmv, and so is a type
1781 -- family application, which a TyVarTv should
1782 -- not unify with
1783 = do { is_filled <- isFilledMetaTyVar rhs_tv
1784 ; if is_filled then return False
1785 else tryFill ev rhs_tv
1786 (mkTyVarTy lhs_tv `mkCastTy` mkSymCo co) }
1787
1788 | otherwise
1789 = return False
1790
1791 ----------------
1792 finalise_eq :: Ct -> Cts -> TcS Cts
1793 finalise_eq (CTyEqCan { cc_ev = ev, cc_tyvar = tv
1794 , cc_rhs = rhs, cc_eq_rel = eq_rel }) rest
1795 | isFmvTyVar tv
1796 = do { ty1 <- zonkTcTyVar tv
1797 ; rhs' <- zonkTcType rhs
1798 ; if ty1 `tcEqType` rhs'
1799 then do { setReflEvidence ev eq_rel rhs'
1800 ; return rest }
1801 else return (mkNonCanonical ev `consCts` rest) }
1802
1803 | otherwise
1804 = return (mkNonCanonical ev `consCts` rest)
1805
1806 finalise_eq ct _ = pprPanic "finalise_irred" (ppr ct)
1807
1808 tryFill :: CtEvidence -> TcTyVar -> TcType -> TcS Bool
1809 -- (tryFill tv rhs ev) assumes 'tv' is an /un-filled/ MetaTv
1810 -- If tv does not appear in 'rhs', it set tv := rhs,
1811 -- binds the evidence (which should be a CtWanted) to Refl<rhs>
1812 -- and return True. Otherwise returns False
1813 tryFill ev tv rhs
1814 = ASSERT2( not (isGiven ev), ppr ev )
1815 do { rhs' <- zonkTcType rhs
1816 ; case () of
1817 _ | Just tv' <- tcGetTyVar_maybe rhs'
1818 , tv == tv' -- tv == rhs
1819 -> return True
1820
1821 _ | Just rhs'' <- occCheckExpand [tv] rhs'
1822 -> do { -- Fill the tyvar
1823 unifyTyVar tv rhs''
1824 ; return True }
1825
1826 _ | otherwise -- Occurs check
1827 -> return False
1828 }
1829
1830 setReflEvidence :: CtEvidence -> EqRel -> TcType -> TcS ()
1831 setReflEvidence ev eq_rel rhs
1832 = setEvBindIfWanted ev (evCoercion refl_co)
1833 where
1834 refl_co = mkTcReflCo (eqRelRole eq_rel) rhs
1835
1836 {-
1837 Note [Unflatten using funeqs first]
1838 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1839 [W] G a ~ Int
1840 [W] F (G a) ~ G a
1841
1842 do not want to end up with
1843 [W] F Int ~ Int
1844 because that might actually hold! Better to end up with the two above
1845 unsolved constraints. The flat form will be
1846
1847 G a ~ fmv1 (CFunEqCan)
1848 F fmv1 ~ fmv2 (CFunEqCan)
1849 fmv1 ~ Int (CTyEqCan)
1850 fmv1 ~ fmv2 (CTyEqCan)
1851
1852 Flatten using the fun-eqs first.
1853 -}
1854
1855 -- | Like 'splitPiTys'' but comes with a 'Bool' which is 'True' iff there is at
1856 -- least one named binder.
1857 split_pi_tys' :: Type -> ([TyCoBinder], Type, Bool)
1858 split_pi_tys' ty = split ty ty
1859 where
1860 split orig_ty ty | Just ty' <- coreView ty = split orig_ty ty'
1861 split _ (ForAllTy b res) = let (bs, ty, _) = split res res
1862 in (Named b : bs, ty, True)
1863 split _ (FunTy { ft_af = af, ft_arg = arg, ft_res = res })
1864 = let (bs, ty, named) = split res res
1865 in (Anon af arg : bs, ty, named)
1866 split orig_ty _ = ([], orig_ty, False)
1867 {-# INLINE split_pi_tys' #-}
1868
1869 -- | Like 'tyConBindersTyCoBinders' but you also get a 'Bool' which is true iff
1870 -- there is at least one named binder.
1871 ty_con_binders_ty_binders' :: [TyConBinder] -> ([TyCoBinder], Bool)
1872 ty_con_binders_ty_binders' = foldr go ([], False)
1873 where
1874 go (Bndr tv (NamedTCB vis)) (bndrs, _)
1875 = (Named (Bndr tv vis) : bndrs, True)
1876 go (Bndr tv (AnonTCB af)) (bndrs, n)
1877 = (Anon af (tyVarKind tv) : bndrs, n)
1878 {-# INLINE go #-}
1879 {-# INLINE ty_con_binders_ty_binders' #-}