Clarify role of coercion in flattening function
[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 Pair
29 import Util
30 import Bag
31 import Control.Monad
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 Trac #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 Trac #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 Trac #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 (typeKind(T xis) ~N typeKind(T tys))
775 flattenArgsNom ev tc tys
776 = do { traceTcS "flatten_args {" (vcat (map ppr tys))
777 ; (tys', cos, kind_co)
778 <- runFlattenCtEv FM_FlattenAll ev (flatten_args_tc tc (repeat Nominal) tys)
779 ; traceTcS "flatten }" (vcat (map ppr tys'))
780 ; return (tys', cos, kind_co) }
781
782
783 {- *********************************************************************
784 * *
785 * The main flattening functions
786 * *
787 ********************************************************************* -}
788
789 {- Note [Flattening]
790 ~~~~~~~~~~~~~~~~~~~~
791 flatten ty ==> (xi, co)
792 where
793 xi has no type functions, unless they appear under ForAlls
794 has no skolems that are mapped in the inert set
795 has no filled-in metavariables
796 co :: xi ~ ty
797
798 Key invariants:
799 (F0) co :: xi ~ zonk(ty)
800 (F1) typeKind(xi) succeeds and returns a fully zonked kind
801 (F2) typeKind(xi) `eqType` zonk(typeKind(ty))
802
803 Note that it is flatten's job to flatten *every type function it sees*.
804 flatten is only called on *arguments* to type functions, by canEqGiven.
805
806 Flattening also:
807 * zonks, removing any metavariables, and
808 * applies the substitution embodied in the inert set
809
810 Because flattening zonks and the returned coercion ("co" above) is also
811 zonked, it's possible that (co :: xi ~ ty) isn't quite true. So, instead,
812 we can rely on this fact:
813
814 (F1) typeKind(xi) succeeds and returns a fully zonked kind
815
816 Note that the left-hand type of co is *always* precisely xi. The right-hand
817 type may or may not be ty, however: if ty has unzonked filled-in metavariables,
818 then the right-hand type of co will be the zonked version of ty.
819 It is for this reason that we
820 occasionally have to explicitly zonk, when (co :: xi ~ ty) is important
821 even before we zonk the whole program. For example, see the FTRNotFollowed
822 case in flattenTyVar.
823
824 Why have these invariants on flattening? Because we sometimes use typeKind
825 during canonicalisation, and we want this kind to be zonked (e.g., see
826 TcCanonical.canEqTyVar).
827
828 Flattening is always homogeneous. That is, the kind of the result of flattening is
829 always the same as the kind of the input, modulo zonking. More formally:
830
831 (F2) typeKind(xi) `eqType` zonk(typeKind(ty))
832
833 This invariant means that the kind of a flattened type might not itself be flat.
834
835 Recall that in comments we use alpha[flat = ty] to represent a
836 flattening skolem variable alpha which has been generated to stand in
837 for ty.
838
839 ----- Example of flattening a constraint: ------
840 flatten (List (F (G Int))) ==> (xi, cc)
841 where
842 xi = List alpha
843 cc = { G Int ~ beta[flat = G Int],
844 F beta ~ alpha[flat = F beta] }
845 Here
846 * alpha and beta are 'flattening skolem variables'.
847 * All the constraints in cc are 'given', and all their coercion terms
848 are the identity.
849
850 NB: Flattening Skolems only occur in canonical constraints, which
851 are never zonked, so we don't need to worry about zonking doing
852 accidental unflattening.
853
854 Note that we prefer to leave type synonyms unexpanded when possible,
855 so when the flattener encounters one, it first asks whether its
856 transitive expansion contains any type function applications. If so,
857 it expands the synonym and proceeds; if not, it simply returns the
858 unexpanded synonym.
859
860 Note [flatten_args performance]
861 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
862 In programs with lots of type-level evaluation, flatten_args becomes
863 part of a tight loop. For example, see test perf/compiler/T9872a, which
864 calls flatten_args a whopping 7,106,808 times. It is thus important
865 that flatten_args be efficient.
866
867 Performance testing showed that the current implementation is indeed
868 efficient. It's critically important that zipWithAndUnzipM be
869 specialized to TcS, and it's also quite helpful to actually `inline`
870 it. On test T9872a, here are the allocation stats (Dec 16, 2014):
871
872 * Unspecialized, uninlined: 8,472,613,440 bytes allocated in the heap
873 * Specialized, uninlined: 6,639,253,488 bytes allocated in the heap
874 * Specialized, inlined: 6,281,539,792 bytes allocated in the heap
875
876 To improve performance even further, flatten_args_nom is split off
877 from flatten_args, as nominal equality is the common case. This would
878 be natural to write using mapAndUnzipM, but even inlined, that function
879 is not as performant as a hand-written loop.
880
881 * mapAndUnzipM, inlined: 7,463,047,432 bytes allocated in the heap
882 * hand-written recursion: 5,848,602,848 bytes allocated in the heap
883
884 If you make any change here, pay close attention to the T9872{a,b,c} tests
885 and T5321Fun.
886
887 If we need to make this yet more performant, a possible way forward is to
888 duplicate the flattener code for the nominal case, and make that case
889 faster. This doesn't seem quite worth it, yet.
890
891 Note [flatten_args]
892 ~~~~~~~~~~~~~~~~~~~
893 Invariant (F2) of Note [Flattening] says that flattening is homogeneous.
894 This causes some trouble when flattening a function applied to a telescope
895 of arguments, perhaps with dependency. For example, suppose
896
897 type family F :: forall (j :: Type) (k :: Type). Maybe j -> Either j k -> Bool -> [k]
898
899 and we wish to flatten the args of (with kind applications explicit)
900
901 F a b (Just a c) (Right a b d) False
902
903 where all variables are skolems and
904
905 a :: Type
906 b :: Type
907 c :: a
908 d :: k
909
910 [G] aco :: a ~ fa
911 [G] bco :: b ~ fb
912 [G] cco :: c ~ fc
913 [G] dco :: d ~ fd
914
915 We process the args in left-to-right order. The first two args are easy:
916
917 (sym aco, fa) <- flatten a
918 (sym bco, fb) <- flatten b
919
920 But now consider flattening (Just a c :: Maybe a). Regardless of how this
921 flattens, the result will have kind (Maybe a), due to (F2). And yet, when
922 we build the application (F fa fb ...), we need this argument to have kind
923 (Maybe fa), not (Maybe a). Suppose (Just a c) flattens to f3 (the "3" is
924 because it's the 3rd argument). We know f3 :: Maybe a. In order to get f3
925 to have kind Maybe fa, we must cast it. The coercion to use is determined
926 by the kind of F: we see in F's kind that the third argument has kind
927 Maybe j. Critically, we also know that the argument corresponding to j
928 (in our example, a) flattened with a coercion (sym aco). We can thus
929 know the coercion needed for the 3rd argument is (Maybe aco).
930
931 More generally, we must use the Lifting Lemma, as implemented in
932 Coercion.liftCoSubst. As we work left-to-right, any variable that is a
933 dependent parameter (j and k, in our example) gets mapped in a lifting context
934 to the coercion that is output from flattening the corresponding argument (aco
935 and bco, in our example). Then, after flattening later arguments, we lift the
936 kind of these arguments in the lifting context that we've be building up.
937 This coercion is then used to keep the result of flattening well-kinded.
938
939 Working through our example, this is what happens:
940
941 1. Flatten a, getting (sym aco, fa). Extend the (empty) LC with [j |-> sym aco]
942
943 2. Flatten b, getting (sym bco, fb). Extend the LC with [k |-> sym bco].
944
945 3. Flatten (Just a c), getting (co3, f3). Lifting the kind (Maybe j) with our LC
946 yields lco3 :: Maybe fa ~ Maybe a. Use (f3 |> sym lco3) as the argument to
947 F.
948
949 4. Flatten (Right a b d), getting (co4, f4). Lifting the kind (Either j k) with our LC
950 yields lco4 :: Either fa fb ~ Either a b. Use (f4 |> sym lco4) as the 4th
951 argument to F.
952
953 5. Flatten False, getting (<False>, False). We lift Bool with our LC, getting <Bool>;
954 casting has no effect. (Indeed we lifted and casted with no effect for steps 1 and 2, as well.)
955
956 We're now almost done, but the new application (F fa fb (f3 |> sym lco3) (f4
957 |> sym lco4) False) has the wrong kind. Its kind is [fb], instead of the original [b].
958 So we must use our LC one last time to lift the result kind [k], getting res_co :: [fb] ~ [b], and
959 we cast our result.
960
961 Accordingly, the final result is
962
963 F fa fb (Just fa (fc |> aco) |> Maybe (sym aco) |> sym (Maybe (sym aco)))
964 (Right fa fb (fd |> bco) |> Either (sym aco) (sym bco) |> sym (Either (sym aco) (sym bco)))
965 False
966 |> [sym bco]
967
968 The res_co is returned as the third return value from flatten_args.
969
970 Note [Last case in flatten_args]
971 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
972 In writing flatten_args's `go`, we know here that tys cannot be empty,
973 because that case is first. We've run out of
974 binders. But perhaps inner_ki is a tyvar that has been instantiated with a
975 Π-type. I believe this, today, this Π-type must be an ordinary function.
976 But tomorrow, we may allow, say, visible type application in types. And
977 it's best to be prepared.
978
979 Here is an example.
980
981 a :: forall (k :: Type). k -> k
982 type family Star
983 Proxy :: forall j. j -> Type
984 axStar :: Star ~ Type
985 type family NoWay :: Bool
986 axNoWay :: NoWay ~ False
987 bo :: Type
988 [G] bc :: bo ~ Bool (in inert set)
989
990 co :: (forall j. j -> Type) ~ (forall (j :: Star). (j |> axStar) -> Star)
991 co = forall (j :: sym axStar). (<j> -> sym axStar)
992
993 We are flattening:
994 a (forall (j :: Star). (j |> axStar) -> Star) -- 1
995 (Proxy |> co) -- 2
996 (bo |> sym axStar) -- 3
997 (NoWay |> sym bc) -- 4
998 :: Star
999
1000 Flattening (1) gives us
1001 (forall j. j -> Type)
1002 co1 :: (forall j. j -> Type) ~ (forall (j :: Star). (j |> axStar) -> Star)
1003 We also extend the lifting context with
1004 k |-> co1
1005
1006 Flattening (2) gives us
1007 (Proxy |> co)
1008 But building (a (forall j. j -> Type) Proxy) would be ill-kinded. So we cast the
1009 result of flattening by sym co1, to get
1010 (Proxy |> co |> sym co1)
1011 Happily, co and co1 cancel each other out, leaving us with
1012 Proxy
1013 co2 :: Proxy ~ (Proxy |> co)
1014
1015 Now we need to flatten (3). After flattening, should we tack on a homogenizing
1016 coercion? The way we normally tell is to look at the kind of `a`. (See Note
1017 [flatten_args].) Here, the remainder of the kind of `a` that we're left with
1018 after processing two arguments is just `k`.
1019
1020 The way forward is look up k in the lifting context, getting co1. If we're at
1021 all well-typed, co1 will be a coercion between Π-types, with enough binders on
1022 both sides to accommodate any remaining arguments in flatten_args. So, let's
1023 decompose co1 with decomposePiCos. This decomposition needs arguments to use
1024 to instantiate any kind parameters. Look at the type of co1. If we just
1025 decomposed it, we would end up with coercions whose types include j, which is
1026 out of scope here. Accordingly, decomposePiCos takes a list of types whose
1027 kinds are the *right-hand* types in the decomposed coercion. (See comments on
1028 decomposePiCos, which also reverses the orientation of the coercions.)
1029 The right-hand types are the unflattened ones -- conveniently what we have to
1030 hand.
1031
1032 So we now call
1033
1034 decomposePiCos (forall j. j -> Type)
1035 [bo |> sym axStar, NoWay |> sym bc]
1036 co1
1037
1038 to get
1039
1040 co3 :: Star ~ Type
1041 co4 :: (j |> axStar) ~ (j |> co3), substituted to
1042 (bo |> sym axStar |> axStar) ~ (bo |> sym axStar |> co3)
1043 == bo ~ bo
1044 res_co :: Type ~ Star -- this one's not reversed in decomposePiCos
1045
1046 We then use these casts on (3) and (4) to get
1047
1048 (bo |> sym axStar |> co3 :: Type) -- (C3)
1049 (NoWay |> sym bc |> co4 :: bo) -- (C4)
1050
1051 We can simplify to
1052
1053 bo -- (C3)
1054 (NoWay |> sym bc :: bo) -- (C4)
1055
1056 Now, to flatten (C3) and (C4), we still need to keep track of dependency.
1057 We know the type of the function applied to (C3) and (C4) must be
1058 (forall j. j -> Type), the flattened type
1059 associated with k (the final type in the kind of `a`.) (We discard the lifting
1060 context up to this point; as we've already substituted k, the domain of the
1061 lifting context we used for (1) and (2), away.)
1062
1063 We now flatten (C3) to get
1064 Bool -- F3
1065 co5 :: Bool ~ bo
1066 and flatten (C4) to get
1067 (False |> sym bc)
1068 Like we did when flattening (2), we need to cast the result of flattening
1069 (4), by lifting the type j with a lifting context containing
1070 [j |-> co5]. This lifting yields co5.
1071 We cast the result of flattening (C4) by sym co5 (this is the normal
1072 cast-after-flattening; see Note [flatten_args]):
1073 (False |> sym bc |> sym co5)
1074 which is really just
1075 False -- F4
1076 co4 :: False ~ (NoWay |> sym bc)
1077
1078 Now, we build up the result
1079
1080 a (forall j. j -> Type)
1081 Proxy
1082 Bool
1083 False
1084 |> res_co
1085
1086 Let's check whether this is well-typed. We know
1087
1088 a :: forall (k :: Type). k -> k
1089
1090 a (forall j. j -> Type) :: (forall j. j -> Type) -> forall j. j -> Type
1091
1092 a (forall j. j -> Type)
1093 Proxy
1094 :: forall j. j -> Type
1095
1096 a (forall j. j -> Type)
1097 Proxy
1098 Bool
1099 :: Bool -> Type
1100
1101 a (forall j. j -> Type)
1102 Proxy
1103 Bool
1104 False
1105 :: Type
1106
1107 a (forall j. j -> Type)
1108 Proxy
1109 Bool
1110 False
1111 |> res_co
1112 :: Star
1113
1114 as desired. (Why do we want Star? Because we started with something of kind Star!)
1115
1116 Whew.
1117
1118 -}
1119
1120 {-# INLINE flatten_args_tc #-}
1121 flatten_args_tc :: TyCon
1122 -> [Role]
1123 -> [Type]
1124 -> FlatM ([Xi], [Coercion], CoercionN)
1125 flatten_args_tc tc = flatten_args all_bndrs any_named_bndrs inner_ki emptyVarSet
1126 -- NB: TyCon kinds are always closed
1127 where
1128 (bndrs, named)
1129 = ty_con_binders_ty_binders' (tyConBinders tc)
1130 -- it's possible that the result kind has arrows (for, e.g., a type family)
1131 -- so we must split it
1132 (inner_bndrs, inner_ki, inner_named) = split_pi_tys' (tyConResKind tc)
1133 !all_bndrs = bndrs `chkAppend` inner_bndrs
1134 !any_named_bndrs = named || inner_named
1135 -- NB: Those bangs there drop allocations in T9872{a,c,d} by 8%.
1136
1137 {-# INLINE flatten_args #-}
1138 flatten_args :: [TyBinder] -> Bool -- Binders, and True iff any of them are
1139 -- named.
1140 -> Kind -> TcTyCoVarSet -- function kind; kind's free vars
1141 -> [Role] -> [Type] -- these are in 1-to-1 correspondence
1142 -> FlatM ([Xi], [Coercion], CoercionN)
1143 -- Coercions :: Xi ~ Type, at roles given
1144 -- Third coercion :: typeKind(fun xis) ~N typeKind(fun tys)
1145 -- That is, the third coercion relates the kind of some function (whose kind is
1146 -- passed as the first parameter) instantiated at xis to the kind of that
1147 -- function instantiated at the tys. This is useful in keeping flattening
1148 -- homoegeneous. The list of roles must be at least as long as the list of
1149 -- types.
1150 -- See Note [flatten_args]
1151 flatten_args orig_binders
1152 any_named_bndrs
1153 orig_inner_ki
1154 orig_fvs
1155 orig_roles
1156 orig_tys
1157 = if any_named_bndrs
1158 then flatten_args_slow orig_binders
1159 orig_inner_ki
1160 orig_fvs
1161 orig_roles
1162 orig_tys
1163 else flatten_args_fast orig_binders orig_inner_ki orig_roles orig_tys
1164
1165 {-# INLINE flatten_args_fast #-}
1166 -- | fast path flatten_args, in which none of the binders are named and
1167 -- therefore we can avoid tracking a lifting context.
1168 -- There are many bang patterns in here. It's been observed that they
1169 -- greatly improve performance of an optimized build.
1170 -- The T9872 test cases are good witnesses of this fact.
1171 flatten_args_fast :: [TyBinder]
1172 -> Kind
1173 -> [Role]
1174 -> [Type]
1175 -> FlatM ([Xi], [Coercion], CoercionN)
1176 flatten_args_fast orig_binders orig_inner_ki orig_roles orig_tys
1177 = fmap finish (iterate orig_tys orig_roles orig_binders)
1178 where
1179
1180 iterate :: [Type]
1181 -> [Role]
1182 -> [TyBinder]
1183 -> FlatM ([Xi], [Coercion], [TyBinder])
1184 iterate (ty:tys) (role:roles) (_:binders) = do
1185 (xi, co) <- go role ty
1186 (xis, cos, binders) <- iterate tys roles binders
1187 pure (xi : xis, co : cos, binders)
1188 iterate [] _ binders = pure ([], [], binders)
1189 iterate _ _ _ = pprPanic
1190 "flatten_args wandered into deeper water than usual" (vcat [])
1191 -- This debug information is commented out because leaving it in
1192 -- causes a ~2% increase in allocations in T9872{a,c,d}.
1193 {-
1194 (vcat [ppr orig_binders,
1195 ppr orig_inner_ki,
1196 ppr (take 10 orig_roles), -- often infinite!
1197 ppr orig_tys])
1198 -}
1199
1200 {-# INLINE go #-}
1201 go :: Role
1202 -> Type
1203 -> FlatM (Xi, Coercion)
1204 go role ty
1205 = case role of
1206 -- In the slow path we bind the Xi and Coercion from the recursive
1207 -- call and then use it such
1208 --
1209 -- let kind_co = mkTcSymCo $ mkReflCo Nominal (tyBinderType binder)
1210 -- casted_xi = xi `mkCastTy` kind_co
1211 -- casted_co = co `mkTcCoherenceLeftCo` kind_co
1212 --
1213 -- but this isn't necessary:
1214 -- mkTcSymCo (Refl a b) = Refl a b,
1215 -- mkCastTy x (Refl _ _) = x
1216 -- mkTcCoherenceLeftCo x (Refl _ _) = x
1217 --
1218 -- Also, no need to check isAnonTyBinder or isNamedTyBinder, since
1219 -- we've already established that they're all anonymous.
1220 Nominal -> setEqRel NomEq $ flatten_one ty
1221 Representational -> setEqRel ReprEq $ flatten_one ty
1222 Phantom -> -- See Note [Phantoms in the flattener]
1223 do { ty <- liftTcS $ zonkTcType ty
1224 ; return (ty, mkReflCo Phantom ty) }
1225
1226
1227 {-# INLINE finish #-}
1228 finish :: ([Xi], [Coercion], [TyBinder]) -> ([Xi], [Coercion], CoercionN)
1229 finish (xis, cos, binders) = (xis, cos, kind_co)
1230 where
1231 final_kind = mkPiTys binders orig_inner_ki
1232 kind_co = mkReflCo Nominal final_kind
1233
1234 {-# INLINE flatten_args_slow #-}
1235 -- | Slow path, compared to flatten_args_fast, because this one must track
1236 -- a lifting context.
1237 flatten_args_slow :: [TyBinder] -> Kind -> TcTyCoVarSet
1238 -> [Role] -> [Type]
1239 -> FlatM ([Xi], [Coercion], CoercionN)
1240 flatten_args_slow orig_binders orig_inner_ki orig_fvs orig_roles orig_tys
1241 = go [] [] orig_lc orig_binders orig_inner_ki orig_roles orig_tys
1242 where
1243 orig_lc = emptyLiftingContext $ mkInScopeSet $ orig_fvs
1244
1245 go :: [Xi] -- Xis accumulator, in reverse order
1246 -> [Coercion] -- Coercions accumulator, in reverse order
1247 -- These are in 1-to-1 correspondence
1248 -> LiftingContext -- mapping from tyvars to flattening coercions
1249 -> [TyBinder] -- Unsubsted binders of function's kind
1250 -> Kind -- Unsubsted result kind of function (not a Pi-type)
1251 -> [Role] -- Roles at which to flatten these ...
1252 -> [Type] -- ... unflattened types
1253 -> FlatM ([Xi], [Coercion], CoercionN)
1254 go acc_xis acc_cos lc binders inner_ki _ []
1255 = return (reverse acc_xis, reverse acc_cos, kind_co)
1256 where
1257 final_kind = mkPiTys binders inner_ki
1258 kind_co = liftCoSubst Nominal lc final_kind
1259
1260 go acc_xis acc_cos lc (binder:binders) inner_ki (role:roles) (ty:tys)
1261 = do { (xi, co) <- case role of
1262 Nominal -> setEqRel NomEq $
1263 if isNamedTyBinder binder
1264 then noBogusCoercions $ flatten_one ty
1265 else flatten_one ty
1266
1267 Representational -> ASSERT( isAnonTyBinder binder )
1268 setEqRel ReprEq $ flatten_one ty
1269
1270 Phantom -> -- See Note [Phantoms in the flattener]
1271 ASSERT( isAnonTyBinder binder )
1272 do { ty <- liftTcS $ zonkTcType ty
1273 ; return (ty, mkReflCo Phantom ty) }
1274
1275 -- By Note [Flattening] invariant (F2),
1276 -- typeKind(xi) = typeKind(ty). But, it's possible that xi will be
1277 -- used as an argument to a function whose kind is different, if
1278 -- earlier arguments have been flattened to new types. We thus
1279 -- need a coercion (kind_co :: old_kind ~ new_kind).
1280 --
1281 -- The bangs here have been observed to improve performance
1282 -- significantly in optimized builds.
1283 ; let kind_co = mkTcSymCo $
1284 liftCoSubst Nominal lc (tyBinderType binder)
1285 !casted_xi = xi `mkCastTy` kind_co
1286 casted_co = co `mkTcCoherenceLeftCo` kind_co
1287
1288 -- now, extend the lifting context with the new binding
1289 !new_lc | Just tv <- tyBinderVar_maybe binder
1290 = extendLiftingContextAndInScope lc tv casted_co
1291 | otherwise
1292 = lc
1293
1294 ; go (casted_xi : acc_xis)
1295 (casted_co : acc_cos)
1296 new_lc
1297 binders
1298 inner_ki
1299 roles
1300 tys
1301 }
1302
1303 -- See Note [Last case in flatten_args]
1304 go acc_xis acc_cos lc [] inner_ki roles tys
1305 | Just k <- tcGetTyVar_maybe inner_ki
1306 , Just co1 <- liftCoSubstTyVar lc Nominal k
1307 = do { let Pair flattened_kind _ = coercionKind co1
1308 (arg_cos, res_co) = decomposePiCos flattened_kind tys co1
1309 casted_tys = zipWith mkCastTy tys arg_cos
1310 zapped_lc = zapLiftingContext lc
1311 (bndrs, new_inner) = splitPiTys flattened_kind
1312
1313 ; (xis_out, cos_out, res_co_out)
1314 <- go acc_xis acc_cos zapped_lc bndrs new_inner roles casted_tys
1315 -- cos_out :: xis_out ~ casted_tys
1316 -- we need to return cos :: xis_out ~ tys
1317 --
1318 -- zipWith has the map first because it will fuse.
1319 ; let cos = zipWith (flip mkTcCoherenceRightCo)
1320 (map mkTcSymCo arg_cos)
1321 cos_out
1322
1323 ; return (xis_out, cos, res_co_out `mkTcTransCo` res_co) }
1324
1325 go _ _ _ _ _ _ _ = pprPanic
1326 "flatten_args wandered into deeper water than usual" (vcat [])
1327 -- This debug information is commented out because leaving it in
1328 -- causes a ~2% increase in allocations in T9872d.
1329 -- That's independent of the analagous case in flatten_args_fast:
1330 -- each of these causes a 2% increase on its own, so commenting them
1331 -- both out gives a 4% decrease in T9872d.
1332 {-
1333
1334 (vcat [ppr orig_binders,
1335 ppr orig_inner_ki,
1336 ppr (take 10 orig_roles), -- often infinite!
1337 ppr orig_tys])
1338 -}
1339
1340 ------------------
1341 flatten_one :: TcType -> FlatM (Xi, Coercion)
1342 -- Flatten a type to get rid of type function applications, returning
1343 -- the new type-function-free type, and a collection of new equality
1344 -- constraints. See Note [Flattening] for more detail.
1345 --
1346 -- Postcondition: Coercion :: Xi ~ TcType
1347 -- The role on the result coercion matches the EqRel in the FlattenEnv
1348
1349 flatten_one xi@(LitTy {})
1350 = do { role <- getRole
1351 ; return (xi, mkReflCo role xi) }
1352
1353 flatten_one (TyVarTy tv)
1354 = flattenTyVar tv
1355
1356 flatten_one (AppTy ty1 ty2)
1357 = flatten_app_tys ty1 [ty2]
1358
1359 flatten_one (TyConApp tc tys)
1360 -- Expand type synonyms that mention type families
1361 -- on the RHS; see Note [Flattening synonyms]
1362 | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
1363 , let expanded_ty = mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys'
1364 = do { mode <- getMode
1365 ; case mode of
1366 FM_FlattenAll | not (isFamFreeTyCon tc)
1367 -> flatten_one expanded_ty
1368 _ -> flatten_ty_con_app tc tys }
1369
1370 -- Otherwise, it's a type function application, and we have to
1371 -- flatten it away as well, and generate a new given equality constraint
1372 -- between the application and a newly generated flattening skolem variable.
1373 | isTypeFamilyTyCon tc
1374 = flatten_fam_app tc tys
1375
1376 -- For * a normal data type application
1377 -- * data family application
1378 -- we just recursively flatten the arguments.
1379 | otherwise
1380 -- FM_Avoid stuff commented out; see Note [Lazy flattening]
1381 -- , let fmode' = case fmode of -- Switch off the flat_top bit in FM_Avoid
1382 -- FE { fe_mode = FM_Avoid tv _ }
1383 -- -> fmode { fe_mode = FM_Avoid tv False }
1384 -- _ -> fmode
1385 = flatten_ty_con_app tc tys
1386
1387 flatten_one (FunTy ty1 ty2)
1388 = do { (xi1,co1) <- flatten_one ty1
1389 ; (xi2,co2) <- flatten_one ty2
1390 ; role <- getRole
1391 ; return (mkFunTy xi1 xi2, mkFunCo role co1 co2) }
1392
1393 flatten_one ty@(ForAllTy {})
1394 -- TODO (RAE): This is inadequate, as it doesn't flatten the kind of
1395 -- the bound tyvar. Doing so will require carrying around a substitution
1396 -- and the usual substTyVarBndr-like silliness. Argh.
1397
1398 -- We allow for-alls when, but only when, no type function
1399 -- applications inside the forall involve the bound type variables.
1400 = do { let (bndrs, rho) = tcSplitForAllTyVarBndrs ty
1401 tvs = binderVars bndrs
1402 ; (rho', co) <- setMode FM_SubstOnly $ flatten_one rho
1403 -- Substitute only under a forall
1404 -- See Note [Flattening under a forall]
1405 ; return (mkForAllTys bndrs rho', mkHomoForAllCos tvs co) }
1406
1407 flatten_one (CastTy ty g)
1408 = do { (xi, co) <- flatten_one ty
1409 ; (g', _) <- flatten_co g
1410
1411 ; return (mkCastTy xi g', castCoercionKind co g' g) }
1412
1413 flatten_one (CoercionTy co) = first mkCoercionTy <$> flatten_co co
1414
1415 -- | "Flatten" a coercion. Really, just zonk it so we can uphold
1416 -- (F1) of Note [Flattening]
1417 flatten_co :: Coercion -> FlatM (Coercion, Coercion)
1418 flatten_co co
1419 = do { co <- liftTcS $ zonkCo co
1420 ; env_role <- getRole
1421 ; let co' = mkTcReflCo env_role (mkCoercionTy co)
1422 ; return (co, co') }
1423
1424 -- flatten (nested) AppTys
1425 flatten_app_tys :: Type -> [Type] -> FlatM (Xi, Coercion)
1426 -- commoning up nested applications allows us to look up the function's kind
1427 -- only once. Without commoning up like this, we would spend a quadratic amount
1428 -- of time looking up functions' types
1429 flatten_app_tys (AppTy ty1 ty2) tys = flatten_app_tys ty1 (ty2:tys)
1430 flatten_app_tys fun_ty arg_tys
1431 = do { (fun_xi, fun_co) <- flatten_one fun_ty
1432 ; flatten_app_ty_args fun_xi fun_co arg_tys }
1433
1434 -- Given a flattened function (with the coercion produced by flattening) and
1435 -- a bunch of unflattened arguments, flatten the arguments and apply.
1436 -- The coercion argument's role matches the role stored in the FlatM monad.
1437 --
1438 -- The bang patterns used here were observed to improve performance. If you
1439 -- wish to remove them, be sure to check for regeressions in allocations.
1440 flatten_app_ty_args :: Xi -> Coercion -> [Type] -> FlatM (Xi, Coercion)
1441 flatten_app_ty_args fun_xi fun_co []
1442 -- this will be a common case when called from flatten_fam_app, so shortcut
1443 = return (fun_xi, fun_co)
1444 flatten_app_ty_args fun_xi fun_co arg_tys
1445 = do { (xi, co, kind_co) <- case tcSplitTyConApp_maybe fun_xi of
1446 Just (tc, xis) ->
1447 do { let tc_roles = tyConRolesRepresentational tc
1448 arg_roles = dropList xis tc_roles
1449 ; (arg_xis, arg_cos, kind_co)
1450 <- flatten_vector (typeKind fun_xi) arg_roles arg_tys
1451
1452 -- Here, we have fun_co :: T xi1 xi2 ~ ty
1453 -- and we need to apply fun_co to the arg_cos. The problem is
1454 -- that using mkAppCo is wrong because that function expects
1455 -- its second coercion to be Nominal, and the arg_cos might
1456 -- not be. The solution is to use transitivity:
1457 -- T <xi1> <xi2> arg_cos ;; fun_co <arg_tys>
1458 ; eq_rel <- getEqRel
1459 ; let app_xi = mkTyConApp tc (xis ++ arg_xis)
1460 app_co = case eq_rel of
1461 NomEq -> mkAppCos fun_co arg_cos
1462 ReprEq -> mkTcTyConAppCo Representational tc
1463 (zipWith mkReflCo tc_roles xis ++ arg_cos)
1464 `mkTcTransCo`
1465 mkAppCos fun_co (map mkNomReflCo arg_tys)
1466 ; return (app_xi, app_co, kind_co) }
1467 Nothing ->
1468 do { (arg_xis, arg_cos, kind_co)
1469 <- flatten_vector (typeKind fun_xi) (repeat Nominal) arg_tys
1470 ; let arg_xi = mkAppTys fun_xi arg_xis
1471 arg_co = mkAppCos fun_co arg_cos
1472 ; return (arg_xi, arg_co, kind_co) }
1473
1474 ; return (homogenise_result xi co kind_co) }
1475
1476 flatten_ty_con_app :: TyCon -> [TcType] -> FlatM (Xi, Coercion)
1477 flatten_ty_con_app tc tys
1478 = do { role <- getRole
1479 ; (xis, cos, kind_co) <- flatten_args_tc tc (tyConRolesX role tc) tys
1480 ; let tyconapp_xi = mkTyConApp tc xis
1481 tyconapp_co = mkTyConAppCo role tc cos
1482 ; return (homogenise_result tyconapp_xi tyconapp_co kind_co) }
1483
1484 -- Make the result of flattening homogeneous (Note [Flattening] (F2))
1485 homogenise_result :: Xi -- a flattened type
1486 -> Coercion -- :: xi ~ original ty
1487 -> CoercionN -- kind_co :: typeKind(xi) ~N typeKind(ty)
1488 -> (Xi, Coercion) -- (xi |> kind_co, (xi |> kind_co)
1489 -- ~ original ty)
1490 homogenise_result xi co kind_co
1491 = let xi' = xi `mkCastTy` kind_co
1492 co' = co `mkTcCoherenceLeftCo` kind_co
1493 in (xi', co')
1494 {-# INLINE homogenise_result #-}
1495
1496 -- Flatten a vector (list of arguments).
1497 flatten_vector :: Kind -- of the function being applied to these arguments
1498 -> [Role] -- If we're flatten w.r.t. ReprEq, what roles do the
1499 -- args have?
1500 -> [Type] -- the args to flatten
1501 -> FlatM ([Xi], [Coercion], CoercionN)
1502 flatten_vector ki roles tys
1503 = do { eq_rel <- getEqRel
1504 ; case eq_rel of
1505 NomEq -> flatten_args bndrs
1506 any_named_bndrs
1507 inner_ki
1508 fvs
1509 (repeat Nominal)
1510 tys
1511 ReprEq -> flatten_args bndrs
1512 any_named_bndrs
1513 inner_ki
1514 fvs
1515 roles
1516 tys
1517 }
1518 where
1519 (bndrs, inner_ki, any_named_bndrs) = split_pi_tys' ki
1520 fvs = tyCoVarsOfType ki
1521 {-# INLINE flatten_vector #-}
1522
1523 {-
1524 Note [Flattening synonyms]
1525 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1526 Not expanding synonyms aggressively improves error messages, and
1527 keeps types smaller. But we need to take care.
1528
1529 Suppose
1530 type T a = a -> a
1531 and we want to flatten the type (T (F a)). Then we can safely flatten
1532 the (F a) to a skolem, and return (T fsk). We don't need to expand the
1533 synonym. This works because TcTyConAppCo can deal with synonyms
1534 (unlike TyConAppCo), see Note [TcCoercions] in TcEvidence.
1535
1536 But (Trac #8979) for
1537 type T a = (F a, a) where F is a type function
1538 we must expand the synonym in (say) T Int, to expose the type function
1539 to the flattener.
1540
1541
1542 Note [Flattening under a forall]
1543 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1544 Under a forall, we
1545 (a) MUST apply the inert substitution
1546 (b) MUST NOT flatten type family applications
1547 Hence FMSubstOnly.
1548
1549 For (a) consider c ~ a, a ~ T (forall b. (b, [c]))
1550 If we don't apply the c~a substitution to the second constraint
1551 we won't see the occurs-check error.
1552
1553 For (b) consider (a ~ forall b. F a b), we don't want to flatten
1554 to (a ~ forall b.fsk, F a b ~ fsk)
1555 because now the 'b' has escaped its scope. We'd have to flatten to
1556 (a ~ forall b. fsk b, forall b. F a b ~ fsk b)
1557 and we have not begun to think about how to make that work!
1558
1559 ************************************************************************
1560 * *
1561 Flattening a type-family application
1562 * *
1563 ************************************************************************
1564 -}
1565
1566 flatten_fam_app :: TyCon -> [TcType] -> FlatM (Xi, Coercion)
1567 -- flatten_fam_app can be over-saturated
1568 -- flatten_exact_fam_app is exactly saturated
1569 -- flatten_exact_fam_app_fully lifts out the application to top level
1570 -- Postcondition: Coercion :: Xi ~ F tys
1571 flatten_fam_app tc tys -- Can be over-saturated
1572 = ASSERT2( tys `lengthAtLeast` tyConArity tc
1573 , ppr tc $$ ppr (tyConArity tc) $$ ppr tys)
1574
1575 do { mode <- getMode
1576 ; case mode of
1577 { FM_SubstOnly -> flatten_ty_con_app tc tys
1578 ; FM_FlattenAll ->
1579
1580 -- Type functions are saturated
1581 -- The type function might be *over* saturated
1582 -- in which case the remaining arguments should
1583 -- be dealt with by AppTys
1584 do { let (tys1, tys_rest) = splitAt (tyConArity tc) tys
1585 ; (xi1, co1) <- flatten_exact_fam_app_fully tc tys1
1586 -- co1 :: xi1 ~ F tys1
1587
1588 ; flatten_app_ty_args xi1 co1 tys_rest } } }
1589
1590 -- the [TcType] exactly saturate the TyCon
1591 flatten_exact_fam_app_fully :: TyCon -> [TcType] -> FlatM (Xi, Coercion)
1592 flatten_exact_fam_app_fully tc tys
1593 -- See Note [Reduce type family applications eagerly]
1594 -- the following typeKind should never be evaluated, as it's just used in
1595 -- casting, and casts by refl are dropped
1596 = do { let reduce_co = mkNomReflCo (typeKind (mkTyConApp tc tys))
1597 ; mOut <- try_to_reduce_nocache tc tys reduce_co id
1598 ; case mOut of
1599 Just out -> pure out
1600 Nothing -> do
1601 { -- First, flatten the arguments
1602 ; (xis, cos, kind_co)
1603 <- setEqRel NomEq $ -- just do this once, instead of for
1604 -- each arg
1605 flatten_args_tc tc (repeat Nominal) tys
1606 -- kind_co :: typeKind(F xis) ~N typeKind(F tys)
1607 ; eq_rel <- getEqRel
1608 ; cur_flav <- getFlavour
1609 ; let role = eqRelRole eq_rel
1610 ret_co = mkTyConAppCo role tc cos
1611 -- ret_co :: F xis ~ F tys; might be heterogeneous
1612
1613 -- Now, look in the cache
1614 ; mb_ct <- liftTcS $ lookupFlatCache tc xis
1615 ; case mb_ct of
1616 Just (co, rhs_ty, flav) -- co :: F xis ~ fsk
1617 -- flav is [G] or [WD]
1618 -- See Note [Type family equations] in TcSMonad
1619 | (NotSwapped, _) <- flav `funEqCanDischargeF` cur_flav
1620 -> -- Usable hit in the flat-cache
1621 do { traceFlat "flatten/flat-cache hit" $
1622 (ppr tc <+> ppr xis $$ ppr rhs_ty)
1623 ; (fsk_xi, fsk_co) <- flatten_one rhs_ty
1624 -- The fsk may already have been unified, so
1625 -- flatten it
1626 -- fsk_co :: fsk_xi ~ fsk
1627 ; let xi = fsk_xi `mkCastTy` kind_co
1628 co' = (fsk_co `mkTcCoherenceLeftCo` kind_co)
1629 `mkTransCo`
1630 maybeSubCo eq_rel (mkSymCo co)
1631 `mkTransCo` ret_co
1632 ; return (xi, co')
1633 }
1634 -- :: fsk_xi ~ F xis
1635
1636 -- Try to reduce the family application right now
1637 -- See Note [Reduce type family applications eagerly]
1638 _ -> do { mOut <- try_to_reduce tc
1639 xis
1640 kind_co
1641 (`mkTransCo` ret_co)
1642 ; case mOut of
1643 Just out -> pure out
1644 Nothing -> do
1645 { loc <- getLoc
1646 ; (ev, co, fsk) <- liftTcS $
1647 newFlattenSkolem cur_flav loc tc xis
1648
1649 -- The new constraint (F xis ~ fsk) is not
1650 -- necessarily inert (e.g. the LHS may be a
1651 -- redex) so we must put it in the work list
1652 ; let ct = CFunEqCan { cc_ev = ev
1653 , cc_fun = tc
1654 , cc_tyargs = xis
1655 , cc_fsk = fsk }
1656 ; emitFlatWork ct
1657
1658 ; traceFlat "flatten/flat-cache miss" $
1659 (ppr tc <+> ppr xis $$ ppr fsk $$ ppr ev)
1660
1661 -- NB: fsk's kind is already flattend because
1662 -- the xis are flattened
1663 ; let xi = mkTyVarTy fsk `mkCastTy` kind_co
1664 co' = (maybeSubCo eq_rel (mkSymCo co)
1665 `mkTcCoherenceLeftCo` kind_co)
1666 `mkTransCo` ret_co
1667 ; return (xi, co')
1668 }
1669 }
1670 }
1671 }
1672
1673 where
1674
1675 -- try_to_reduce and try_to_reduce_nocache (below) could be unified into
1676 -- a more general definition, but it was observed that separating them
1677 -- gives better performance (lower allocation numbers in T9872x).
1678
1679 try_to_reduce :: TyCon -- F, family tycon
1680 -> [Type] -- args, not necessarily flattened
1681 -> CoercionN -- kind_co :: typeKind(F args) ~N
1682 -- typeKind(F orig_args)
1683 -- where
1684 -- orig_args is what was passed to the outer
1685 -- function
1686 -> ( Coercion -- :: (xi |> kind_co) ~ F args
1687 -> Coercion ) -- what to return from outer function
1688 -> FlatM (Maybe (Xi, Coercion))
1689 try_to_reduce tc tys kind_co update_co
1690 = do { checkStackDepth (mkTyConApp tc tys)
1691 ; mb_match <- liftTcS $ matchFam tc tys
1692 ; case mb_match of
1693 -- NB: norm_co will always be homogeneous. All type families
1694 -- are homogeneous.
1695 Just (norm_co, norm_ty)
1696 -> do { traceFlat "Eager T.F. reduction success" $
1697 vcat [ ppr tc, ppr tys, ppr norm_ty
1698 , ppr norm_co <+> dcolon
1699 <+> ppr (coercionKind norm_co)
1700 ]
1701 ; (xi, final_co) <- bumpDepth $ flatten_one norm_ty
1702 ; eq_rel <- getEqRel
1703 ; let co = maybeSubCo eq_rel norm_co
1704 `mkTransCo` mkSymCo final_co
1705 ; flavour <- getFlavour
1706 -- NB: only extend cache with nominal equalities
1707 ; when (eq_rel == NomEq) $
1708 liftTcS $
1709 extendFlatCache tc tys ( co, xi, flavour )
1710 ; let xi' = xi `mkCastTy` kind_co
1711 co' = update_co $ mkSymCo co
1712 `mkTcCoherenceLeftCo` kind_co
1713 ; return $ Just (xi', co') }
1714 Nothing -> pure Nothing }
1715
1716 try_to_reduce_nocache :: TyCon -- F, family tycon
1717 -> [Type] -- args, not necessarily flattened
1718 -> CoercionN -- kind_co :: typeKind(F args)
1719 -- ~N typeKind(F orig_args)
1720 -- where
1721 -- orig_args is what was passed to the
1722 -- outer function
1723 -> ( Coercion -- :: (xi |> kind_co) ~ F args
1724 -> Coercion ) -- what to return from outer
1725 -- function
1726 -> FlatM (Maybe (Xi, Coercion))
1727 try_to_reduce_nocache tc tys kind_co update_co
1728 = do { checkStackDepth (mkTyConApp tc tys)
1729 ; mb_match <- liftTcS $ matchFam tc tys
1730 ; case mb_match of
1731 -- NB: norm_co will always be homogeneous. All type families
1732 -- are homogeneous.
1733 Just (norm_co, norm_ty)
1734 -> do { (xi, final_co) <- bumpDepth $ flatten_one norm_ty
1735 ; eq_rel <- getEqRel
1736 ; let co = maybeSubCo eq_rel norm_co
1737 `mkTransCo` mkSymCo final_co
1738 xi' = xi `mkCastTy` kind_co
1739 co' = update_co $ mkSymCo co
1740 `mkTcCoherenceLeftCo` kind_co
1741 ; return $ Just (xi', co') }
1742 Nothing -> pure Nothing }
1743
1744 {- Note [Reduce type family applications eagerly]
1745 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1746 If we come across a type-family application like (Append (Cons x Nil) t),
1747 then, rather than flattening to a skolem etc, we may as well just reduce
1748 it on the spot to (Cons x t). This saves a lot of intermediate steps.
1749 Examples that are helped are tests T9872, and T5321Fun.
1750
1751 Performance testing indicates that it's best to try this *twice*, once
1752 before flattening arguments and once after flattening arguments.
1753 Adding the extra reduction attempt before flattening arguments cut
1754 the allocation amounts for the T9872{a,b,c} tests by half.
1755
1756 An example of where the early reduction appears helpful:
1757
1758 type family Last x where
1759 Last '[x] = x
1760 Last (h ': t) = Last t
1761
1762 workitem: (x ~ Last '[1,2,3,4,5,6])
1763
1764 Flattening the argument never gets us anywhere, but trying to flatten
1765 it at every step is quadratic in the length of the list. Reducing more
1766 eagerly makes simplifying the right-hand type linear in its length.
1767
1768 Testing also indicated that the early reduction should *not* use the
1769 flat-cache, but that the later reduction *should*. (Although the
1770 effect was not large.) Hence the Bool argument to try_to_reduce. To
1771 me (SLPJ) this seems odd; I get that eager reduction usually succeeds;
1772 and if don't use the cache for eager reduction, we will miss most of
1773 the opportunities for using it at all. More exploration would be good
1774 here.
1775
1776 At the end, once we've got a flat rhs, we extend the flatten-cache to record
1777 the result. Doing so can save lots of work when the same redex shows up more
1778 than once. Note that we record the link from the redex all the way to its
1779 *final* value, not just the single step reduction. Interestingly, using the
1780 flat-cache for the first reduction resulted in an increase in allocations
1781 of about 3% for the four T9872x tests. However, using the flat-cache in
1782 the later reduction is a similar gain. I (Richard E) don't currently (Dec '14)
1783 have any knowledge as to *why* these facts are true.
1784
1785 ************************************************************************
1786 * *
1787 Flattening a type variable
1788 * *
1789 ********************************************************************* -}
1790
1791 -- | The result of flattening a tyvar "one step".
1792 data FlattenTvResult
1793 = FTRNotFollowed
1794 -- ^ The inert set doesn't make the tyvar equal to anything else
1795
1796 | FTRFollowed TcType Coercion
1797 -- ^ The tyvar flattens to a not-necessarily flat other type.
1798 -- co :: new type ~r old type, where the role is determined by
1799 -- the FlattenEnv
1800
1801 flattenTyVar :: TyVar -> FlatM (Xi, Coercion)
1802 flattenTyVar tv
1803 = do { mb_yes <- flatten_tyvar1 tv
1804 ; case mb_yes of
1805 FTRFollowed ty1 co1 -- Recur
1806 -> do { (ty2, co2) <- flatten_one ty1
1807 -- ; traceFlat "flattenTyVar2" (ppr tv $$ ppr ty2)
1808 ; return (ty2, co2 `mkTransCo` co1) }
1809
1810 FTRNotFollowed -- Done, but make sure the kind is zonked
1811 -- Note [Flattening] invariant (F1)
1812 -> do { tv' <- liftTcS $ updateTyVarKindM zonkTcType tv
1813 ; role <- getRole
1814 ; let ty' = mkTyVarTy tv'
1815 ; return (ty', mkTcReflCo role ty') } }
1816
1817 flatten_tyvar1 :: TcTyVar -> FlatM FlattenTvResult
1818 -- "Flattening" a type variable means to apply the substitution to it
1819 -- Specifically, look up the tyvar in
1820 -- * the internal MetaTyVar box
1821 -- * the inerts
1822 -- See also the documentation for FlattenTvResult
1823
1824 flatten_tyvar1 tv
1825 = do { mb_ty <- liftTcS $ isFilledMetaTyVar_maybe tv
1826 ; case mb_ty of
1827 Just ty -> do { traceFlat "Following filled tyvar"
1828 (ppr tv <+> equals <+> ppr ty)
1829 ; role <- getRole
1830 ; return (FTRFollowed ty (mkReflCo role ty)) } ;
1831 Nothing -> do { traceFlat "Unfilled tyvar" (ppr tv)
1832 ; fr <- getFlavourRole
1833 ; flatten_tyvar2 tv fr } }
1834
1835 flatten_tyvar2 :: TcTyVar -> CtFlavourRole -> FlatM FlattenTvResult
1836 -- The tyvar is not a filled-in meta-tyvar
1837 -- Try in the inert equalities
1838 -- See Definition [Applying a generalised substitution] in TcSMonad
1839 -- See Note [Stability of flattening] in TcSMonad
1840
1841 flatten_tyvar2 tv fr@(_, eq_rel)
1842 = do { ieqs <- liftTcS $ getInertEqs
1843 ; mode <- getMode
1844 ; case lookupDVarEnv ieqs tv of
1845 Just (ct:_) -- If the first doesn't work,
1846 -- the subsequent ones won't either
1847 | CTyEqCan { cc_ev = ctev, cc_tyvar = tv
1848 , cc_rhs = rhs_ty, cc_eq_rel = ct_eq_rel } <- ct
1849 , let ct_fr = (ctEvFlavour ctev, ct_eq_rel)
1850 , ct_fr `eqCanRewriteFR` fr -- This is THE key call of eqCanRewriteFR
1851 -> do { traceFlat "Following inert tyvar"
1852 (ppr mode <+>
1853 ppr tv <+>
1854 equals <+>
1855 ppr rhs_ty $$ ppr ctev)
1856 ; let rewrite_co1 = mkSymCo (ctEvCoercion ctev)
1857 rewrite_co = case (ct_eq_rel, eq_rel) of
1858 (ReprEq, _rel) -> ASSERT( _rel == ReprEq )
1859 -- if this ASSERT fails, then
1860 -- eqCanRewriteFR answered incorrectly
1861 rewrite_co1
1862 (NomEq, NomEq) -> rewrite_co1
1863 (NomEq, ReprEq) -> mkSubCo rewrite_co1
1864
1865 ; return (FTRFollowed rhs_ty rewrite_co) }
1866 -- NB: ct is Derived then fmode must be also, hence
1867 -- we are not going to touch the returned coercion
1868 -- so ctEvCoercion is fine.
1869
1870 _other -> return FTRNotFollowed }
1871
1872 {-
1873 Note [An alternative story for the inert substitution]
1874 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1875 (This entire note is just background, left here in case we ever want
1876 to return the previous state of affairs)
1877
1878 We used (GHC 7.8) to have this story for the inert substitution inert_eqs
1879
1880 * 'a' is not in fvs(ty)
1881 * They are *inert* in the weaker sense that there is no infinite chain of
1882 (i1 `eqCanRewrite` i2), (i2 `eqCanRewrite` i3), etc
1883
1884 This means that flattening must be recursive, but it does allow
1885 [G] a ~ [b]
1886 [G] b ~ Maybe c
1887
1888 This avoids "saturating" the Givens, which can save a modest amount of work.
1889 It is easy to implement, in TcInteract.kick_out, by only kicking out an inert
1890 only if (a) the work item can rewrite the inert AND
1891 (b) the inert cannot rewrite the work item
1892
1893 This is significantly harder to think about. It can save a LOT of work
1894 in occurs-check cases, but we don't care about them much. Trac #5837
1895 is an example; all the constraints here are Givens
1896
1897 [G] a ~ TF (a,Int)
1898 -->
1899 work TF (a,Int) ~ fsk
1900 inert fsk ~ a
1901
1902 --->
1903 work fsk ~ (TF a, TF Int)
1904 inert fsk ~ a
1905
1906 --->
1907 work a ~ (TF a, TF Int)
1908 inert fsk ~ a
1909
1910 ---> (attempting to flatten (TF a) so that it does not mention a
1911 work TF a ~ fsk2
1912 inert a ~ (fsk2, TF Int)
1913 inert fsk ~ (fsk2, TF Int)
1914
1915 ---> (substitute for a)
1916 work TF (fsk2, TF Int) ~ fsk2
1917 inert a ~ (fsk2, TF Int)
1918 inert fsk ~ (fsk2, TF Int)
1919
1920 ---> (top-level reduction, re-orient)
1921 work fsk2 ~ (TF fsk2, TF Int)
1922 inert a ~ (fsk2, TF Int)
1923 inert fsk ~ (fsk2, TF Int)
1924
1925 ---> (attempt to flatten (TF fsk2) to get rid of fsk2
1926 work TF fsk2 ~ fsk3
1927 work fsk2 ~ (fsk3, TF Int)
1928 inert a ~ (fsk2, TF Int)
1929 inert fsk ~ (fsk2, TF Int)
1930
1931 --->
1932 work TF fsk2 ~ fsk3
1933 inert fsk2 ~ (fsk3, TF Int)
1934 inert a ~ ((fsk3, TF Int), TF Int)
1935 inert fsk ~ ((fsk3, TF Int), TF Int)
1936
1937 Because the incoming given rewrites all the inert givens, we get more and
1938 more duplication in the inert set. But this really only happens in pathalogical
1939 casee, so we don't care.
1940
1941
1942 ************************************************************************
1943 * *
1944 Unflattening
1945 * *
1946 ************************************************************************
1947
1948 An unflattening example:
1949 [W] F a ~ alpha
1950 flattens to
1951 [W] F a ~ fmv (CFunEqCan)
1952 [W] fmv ~ alpha (CTyEqCan)
1953 We must solve both!
1954 -}
1955
1956 unflattenWanteds :: Cts -> Cts -> TcS Cts
1957 unflattenWanteds tv_eqs funeqs
1958 = do { tclvl <- getTcLevel
1959
1960 ; traceTcS "Unflattening" $ braces $
1961 vcat [ text "Funeqs =" <+> pprCts funeqs
1962 , text "Tv eqs =" <+> pprCts tv_eqs ]
1963
1964 -- Step 1: unflatten the CFunEqCans, except if that causes an occurs check
1965 -- Occurs check: consider [W] alpha ~ [F alpha]
1966 -- ==> (flatten) [W] F alpha ~ fmv, [W] alpha ~ [fmv]
1967 -- ==> (unify) [W] F [fmv] ~ fmv
1968 -- See Note [Unflatten using funeqs first]
1969 ; funeqs <- foldrBagM unflatten_funeq emptyCts funeqs
1970 ; traceTcS "Unflattening 1" $ braces (pprCts funeqs)
1971
1972 -- Step 2: unify the tv_eqs, if possible
1973 ; tv_eqs <- foldrBagM (unflatten_eq tclvl) emptyCts tv_eqs
1974 ; traceTcS "Unflattening 2" $ braces (pprCts tv_eqs)
1975
1976 -- Step 3: fill any remaining fmvs with fresh unification variables
1977 ; funeqs <- mapBagM finalise_funeq funeqs
1978 ; traceTcS "Unflattening 3" $ braces (pprCts funeqs)
1979
1980 -- Step 4: remove any tv_eqs that look like ty ~ ty
1981 ; tv_eqs <- foldrBagM finalise_eq emptyCts tv_eqs
1982
1983 ; let all_flat = tv_eqs `andCts` funeqs
1984 ; traceTcS "Unflattening done" $ braces (pprCts all_flat)
1985
1986 ; return all_flat }
1987 where
1988 ----------------
1989 unflatten_funeq :: Ct -> Cts -> TcS Cts
1990 unflatten_funeq ct@(CFunEqCan { cc_fun = tc, cc_tyargs = xis
1991 , cc_fsk = fmv, cc_ev = ev }) rest
1992 = do { -- fmv should be an un-filled flatten meta-tv;
1993 -- we now fix its final value by filling it, being careful
1994 -- to observe the occurs check. Zonking will eliminate it
1995 -- altogether in due course
1996 rhs' <- zonkTcType (mkTyConApp tc xis)
1997 ; case occCheckExpand [fmv] rhs' of
1998 Just rhs'' -- Normal case: fill the tyvar
1999 -> do { setReflEvidence ev NomEq rhs''
2000 ; unflattenFmv fmv rhs''
2001 ; return rest }
2002
2003 Nothing -> -- Occurs check
2004 return (ct `consCts` rest) }
2005
2006 unflatten_funeq other_ct _
2007 = pprPanic "unflatten_funeq" (ppr other_ct)
2008
2009 ----------------
2010 finalise_funeq :: Ct -> TcS Ct
2011 finalise_funeq (CFunEqCan { cc_fsk = fmv, cc_ev = ev })
2012 = do { demoteUnfilledFmv fmv
2013 ; return (mkNonCanonical ev) }
2014 finalise_funeq ct = pprPanic "finalise_funeq" (ppr ct)
2015
2016 ----------------
2017 unflatten_eq :: TcLevel -> Ct -> Cts -> TcS Cts
2018 unflatten_eq tclvl ct@(CTyEqCan { cc_ev = ev, cc_tyvar = tv
2019 , cc_rhs = rhs, cc_eq_rel = eq_rel }) rest
2020
2021 | NomEq <- eq_rel -- See Note [Do not unify representational equalities]
2022 -- in TcInteract
2023 , isFmvTyVar tv -- Previously these fmvs were untouchable,
2024 -- but now they are touchable
2025 -- NB: unlike unflattenFmv, filling a fmv here /does/
2026 -- bump the unification count; it is "improvement"
2027 -- Note [Unflattening can force the solver to iterate]
2028 = ASSERT2( tyVarKind tv `eqType` typeKind rhs, ppr ct )
2029 -- CTyEqCan invariant should ensure this is true
2030 do { is_filled <- isFilledMetaTyVar tv
2031 ; elim <- case is_filled of
2032 False -> do { traceTcS "unflatten_eq 2" (ppr ct)
2033 ; tryFill ev tv rhs }
2034 True -> do { traceTcS "unflatten_eq 3" (ppr ct)
2035 ; try_fill_rhs ev tclvl tv rhs }
2036 ; if elim
2037 then do { setReflEvidence ev eq_rel (mkTyVarTy tv)
2038 ; return rest }
2039 else return (ct `consCts` rest) }
2040
2041 | otherwise
2042 = return (ct `consCts` rest)
2043
2044 unflatten_eq _ ct _ = pprPanic "unflatten_irred" (ppr ct)
2045
2046 ----------------
2047 try_fill_rhs ev tclvl lhs_tv rhs
2048 -- Constraint is lhs_tv ~ rhs_tv,
2049 -- and lhs_tv is filled, so try RHS
2050 | Just (rhs_tv, co) <- getCastedTyVar_maybe rhs
2051 -- co :: kind(rhs_tv) ~ kind(lhs_tv)
2052 , isFmvTyVar rhs_tv || (isTouchableMetaTyVar tclvl rhs_tv
2053 && not (isSigTyVar rhs_tv))
2054 -- LHS is a filled fmv, and so is a type
2055 -- family application, which a SigTv should
2056 -- not unify with
2057 = do { is_filled <- isFilledMetaTyVar rhs_tv
2058 ; if is_filled then return False
2059 else tryFill ev rhs_tv
2060 (mkTyVarTy lhs_tv `mkCastTy` mkSymCo co) }
2061
2062 | otherwise
2063 = return False
2064
2065 ----------------
2066 finalise_eq :: Ct -> Cts -> TcS Cts
2067 finalise_eq (CTyEqCan { cc_ev = ev, cc_tyvar = tv
2068 , cc_rhs = rhs, cc_eq_rel = eq_rel }) rest
2069 | isFmvTyVar tv
2070 = do { ty1 <- zonkTcTyVar tv
2071 ; rhs' <- zonkTcType rhs
2072 ; if ty1 `tcEqType` rhs'
2073 then do { setReflEvidence ev eq_rel rhs'
2074 ; return rest }
2075 else return (mkNonCanonical ev `consCts` rest) }
2076
2077 | otherwise
2078 = return (mkNonCanonical ev `consCts` rest)
2079
2080 finalise_eq ct _ = pprPanic "finalise_irred" (ppr ct)
2081
2082 tryFill :: CtEvidence -> TcTyVar -> TcType -> TcS Bool
2083 -- (tryFill tv rhs ev) assumes 'tv' is an /un-filled/ MetaTv
2084 -- If tv does not appear in 'rhs', it set tv := rhs,
2085 -- binds the evidence (which should be a CtWanted) to Refl<rhs>
2086 -- and return True. Otherwise returns False
2087 tryFill ev tv rhs
2088 = ASSERT2( not (isGiven ev), ppr ev )
2089 do { rhs' <- zonkTcType rhs
2090 ; case () of
2091 _ | Just tv' <- tcGetTyVar_maybe rhs'
2092 , tv == tv' -- tv == rhs
2093 -> return True
2094
2095 _ | Just rhs'' <- occCheckExpand [tv] rhs'
2096 -> do { -- Fill the tyvar
2097 unifyTyVar tv rhs''
2098 ; return True }
2099
2100 _ | otherwise -- Occurs check
2101 -> return False
2102 }
2103
2104 setReflEvidence :: CtEvidence -> EqRel -> TcType -> TcS ()
2105 setReflEvidence ev eq_rel rhs
2106 = setEvBindIfWanted ev (evCoercion refl_co)
2107 where
2108 refl_co = mkTcReflCo (eqRelRole eq_rel) rhs
2109
2110 {-
2111 Note [Unflatten using funeqs first]
2112 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2113 [W] G a ~ Int
2114 [W] F (G a) ~ G a
2115
2116 do not want to end up with
2117 [W] F Int ~ Int
2118 because that might actually hold! Better to end up with the two above
2119 unsolved constraints. The flat form will be
2120
2121 G a ~ fmv1 (CFunEqCan)
2122 F fmv1 ~ fmv2 (CFunEqCan)
2123 fmv1 ~ Int (CTyEqCan)
2124 fmv1 ~ fmv2 (CTyEqCan)
2125
2126 Flatten using the fun-eqs first.
2127 -}
2128
2129 -- | Like 'splitPiTys'' but comes with a 'Bool' which is 'True' iff there is at
2130 -- least one named binder.
2131 split_pi_tys' :: Type -> ([TyBinder], Type, Bool)
2132 split_pi_tys' ty = split ty ty
2133 where
2134 split orig_ty ty | Just ty' <- coreView ty = split orig_ty ty'
2135 split _ (ForAllTy b res) = let (bs, ty, _) = split res res
2136 in (Named b : bs, ty, True)
2137 split _ (FunTy arg res) = let (bs, ty, named) = split res res
2138 in (Anon arg : bs, ty, named)
2139 split orig_ty _ = ([], orig_ty, False)
2140 {-# INLINE split_pi_tys' #-}
2141
2142 -- | Like 'tyConBindersTyBinders' but you also get a 'Bool' which is true iff
2143 -- there is at least one named binder.
2144 ty_con_binders_ty_binders' :: [TyConBinder] -> ([TyBinder], Bool)
2145 ty_con_binders_ty_binders' = foldr go ([], False)
2146 where
2147 go (TvBndr tv (NamedTCB vis)) (bndrs, _)
2148 = (Named (TvBndr tv vis) : bndrs, True)
2149 go (TvBndr tv AnonTCB) (bndrs, n)
2150 = (Anon (tyVarKind tv) : bndrs, n)
2151 {-# INLINE go #-}
2152 {-# INLINE ty_con_binders_ty_binders' #-}