Rejig the error messages a bit; fixes a minor bug
[ghc-hetmet.git] / compiler / typecheck / TcTyFuns.lhs
1 Normalisation of type terms relative to type instances as well as
2 normalisation and entailment checking of equality constraints.
3
4 \begin{code}
5 module TcTyFuns (
6         tcNormaliseFamInst,
7
8         normaliseGivenEqs, normaliseGivenDicts, 
9         normaliseWantedEqs, normaliseWantedDicts,
10         solveWantedEqs,
11         substEqInDictInsts,
12         
13         -- errors
14         misMatchMsg, failWithMisMatch
15   ) where
16
17
18 #include "HsVersions.h"
19
20 --friends
21 import TcRnMonad
22 import TcEnv
23 import Inst
24 import TcType
25 import TcMType
26
27 -- GHC
28 import Coercion
29 import Type
30 import TypeRep  ( Type(..) )
31 import TyCon
32 import HsSyn
33 import VarEnv
34 import Var
35 import Name
36 import Bag
37 import Outputable
38 import SrcLoc   ( Located(..) )
39 import Maybes
40
41 -- standard
42 import Data.List
43 import Control.Monad (liftM)
44 \end{code}
45
46
47 %************************************************************************
48 %*                                                                      *
49                 Normalisation of types
50 %*                                                                      *
51 %************************************************************************
52
53 Unfold a single synonym family instance and yield the witnessing coercion.
54 Return 'Nothing' if the given type is either not synonym family instance
55 or is a synonym family instance that has no matching instance declaration.
56 (Applies only if the type family application is outermost.)
57
58 For example, if we have
59
60   :Co:R42T a :: T [a] ~ :R42T a
61
62 then 'T [Int]' unfolds to (:R42T Int, :Co:R42T Int).
63
64 \begin{code}
65 tcUnfoldSynFamInst :: Type -> TcM (Maybe (Type, Coercion))
66 tcUnfoldSynFamInst (TyConApp tycon tys)
67   | not (isOpenSynTyCon tycon)     -- unfold *only* _synonym_ family instances
68   = return Nothing
69   | otherwise
70   = do { -- we only use the indexing arguments for matching, 
71          -- not the additional ones
72        ; maybeFamInst <- tcLookupFamInst tycon idxTys
73        ; case maybeFamInst of
74            Nothing                -> return Nothing
75            Just (rep_tc, rep_tys) -> return $ Just (mkTyConApp rep_tc tys',
76                                                     mkTyConApp coe_tc tys')
77              where
78                tys'   = rep_tys ++ restTys
79                coe_tc = expectJust "TcTyFun.tcUnfoldSynFamInst" 
80                                    (tyConFamilyCoercion_maybe rep_tc)
81        }
82     where
83         n                = tyConArity tycon
84         (idxTys, restTys) = splitAt n tys
85 tcUnfoldSynFamInst _other = return Nothing
86 \end{code}
87
88 Normalise 'Type's and 'PredType's by unfolding type family applications where
89 possible (ie, we treat family instances as a TRS).  Also zonk meta variables.
90
91         tcNormaliseFamInst ty = (co, ty')
92         then   co : ty ~ ty'
93
94 \begin{code}
95 tcNormaliseFamInst :: TcType -> TcM (CoercionI, TcType)
96 tcNormaliseFamInst = tcGenericNormaliseFamInst tcUnfoldSynFamInst
97
98 tcNormaliseFamInstPred :: TcPredType -> TcM (CoercionI, TcPredType)
99 tcNormaliseFamInstPred = tcGenericNormaliseFamInstPred tcUnfoldSynFamInst
100 \end{code}
101
102 An elementary rewrite is a properly oriented equality with associated coercion
103 that has one of the following two forms:
104
105 (1) co :: F t1..tn ~ t
106 (2) co :: a ~ t         , where t /= F t1..tn and a is a skolem tyvar
107
108 NB: We do *not* use equalities of the form a ~ t where a is a meta tyvar as a
109 reqrite rule.  Instead, such equalities are solved by unification.  This is
110 essential; cf Note [skolemOccurs loop].
111
112 The following functions takes an equality instance and turns it into an
113 elementary rewrite if possible.
114
115 \begin{code}
116 data Rewrite = Rewrite TcType           -- lhs of rewrite rule
117                        TcType           -- rhs of rewrite rule
118                        TcType           -- coercion witnessing the rewrite rule
119
120 eqInstToRewrite :: Inst -> Maybe (Rewrite, Bool)
121                                            -- True iff rewrite swapped equality
122 eqInstToRewrite inst
123   = ASSERT( isEqInst inst )
124     go ty1 ty2 (eqInstType inst)
125   where
126     (ty1,ty2) = eqInstTys inst
127
128     -- look through synonyms
129     go ty1 ty2 co | Just ty1' <- tcView ty1 = go ty1' ty2 co
130     go ty1 ty2 co | Just ty2' <- tcView ty2 = go ty1 ty2' co
131
132     -- left-to-right rule with type family head
133     go ty1@(TyConApp con _) ty2 co 
134       | isOpenSynTyCon con
135       = Just (Rewrite ty1 ty2 co, False)                     -- not swapped
136
137     -- left-to-right rule with type variable head
138     go ty1@(TyVarTy tv) ty2 co 
139       | isSkolemTyVar tv
140       = Just (Rewrite ty1 ty2 co, False)                     -- not swapped
141
142     -- right-to-left rule with type family head, only after
143     -- having checked whether we can work left-to-right
144     go ty1 ty2@(TyConApp con _) co 
145       | isOpenSynTyCon con
146       = Just (Rewrite ty2 ty1 (mkSymCoercion co), True)      -- swapped
147
148     -- right-to-left rule with type variable head, only after 
149     -- having checked whether we can work left-to-right 
150     go ty1 ty2@(TyVarTy tv) co 
151       | isSkolemTyVar tv
152       = Just (Rewrite ty2 ty1 (mkSymCoercion co), True)      -- swapped
153
154     -- this equality is not a rewrite rule => ignore
155     go _ _ _ = Nothing
156 \end{code}
157
158 Normalise a type relative to an elementary rewrite implied by an EqInst or an
159 explicitly given elementary rewrite.
160
161 \begin{code}
162 -- Rewrite by EqInst
163 --   Precondition: the EqInst passes the occurs check
164 tcEqInstNormaliseFamInst :: Inst -> TcType -> TcM (CoercionI, TcType)
165 tcEqInstNormaliseFamInst inst ty
166   = case eqInstToRewrite inst of
167       Just (rewrite, _) -> tcEqRuleNormaliseFamInst rewrite ty
168       Nothing           -> return (IdCo, ty)
169
170 -- Rewrite by equality rewrite rule
171 tcEqRuleNormaliseFamInst :: Rewrite                     -- elementary rewrite
172                          -> TcType                      -- type to rewrite
173                          -> TcM (CoercionI,             -- witnessing coercion
174                                  TcType)                -- rewritten type
175 tcEqRuleNormaliseFamInst (Rewrite pat rhs co) ty
176   = tcGenericNormaliseFamInst matchEqRule ty
177   where
178     matchEqRule sty | pat `tcEqType` sty = return $ Just (rhs, co)
179                     | otherwise          = return $ Nothing
180 \end{code}
181
182 Generic normalisation of 'Type's and 'PredType's; ie, walk the type term and
183 apply the normalisation function gives as the first argument to every TyConApp
184 and every TyVarTy subterm.
185
186         tcGenericNormaliseFamInst fun ty = (co, ty')
187         then   co : ty ~ ty'
188
189 This function is (by way of using smart constructors) careful to ensure that
190 the returned coercion is exactly IdCo (and not some semantically equivalent,
191 but syntactically different coercion) whenever (ty' `tcEqType` ty).  This
192 makes it easy for the caller to determine whether the type changed.  BUT
193 even if we return IdCo, ty' may be *syntactically* different from ty due to
194 unfolded closed type synonyms (by way of tcCoreView).  In the interest of
195 good error messages, callers should discard ty' in favour of ty in this case.
196
197 \begin{code}
198 tcGenericNormaliseFamInst :: (TcType -> TcM (Maybe (TcType, Coercion)))         
199                              -- what to do with type functions and tyvars
200                            -> TcType                    -- old type
201                            -> TcM (CoercionI, TcType)   -- (coercion, new type)
202 tcGenericNormaliseFamInst fun ty
203   | Just ty' <- tcView ty = tcGenericNormaliseFamInst fun ty' 
204 tcGenericNormaliseFamInst fun (TyConApp tyCon tys)
205   = do  { (cois, ntys) <- mapAndUnzipM (tcGenericNormaliseFamInst fun) tys
206         ; let tycon_coi = mkTyConAppCoI tyCon ntys cois
207         ; maybe_ty_co <- fun (mkTyConApp tyCon ntys)     -- use normalised args!
208         ; case maybe_ty_co of
209             -- a matching family instance exists
210             Just (ty', co) ->
211               do { let first_coi = mkTransCoI tycon_coi (ACo co)
212                  ; (rest_coi, nty) <- tcGenericNormaliseFamInst fun ty'
213                  ; let fix_coi = mkTransCoI first_coi rest_coi
214                  ; return (fix_coi, nty)
215                  }
216             -- no matching family instance exists
217             -- we do not do anything
218             Nothing -> return (tycon_coi, mkTyConApp tyCon ntys)
219         }
220 tcGenericNormaliseFamInst fun (AppTy ty1 ty2)
221   = do  { (coi1,nty1) <- tcGenericNormaliseFamInst fun ty1
222         ; (coi2,nty2) <- tcGenericNormaliseFamInst fun ty2
223         ; return (mkAppTyCoI nty1 coi1 nty2 coi2, mkAppTy nty1 nty2)
224         }
225 tcGenericNormaliseFamInst fun (FunTy ty1 ty2)
226   = do  { (coi1,nty1) <- tcGenericNormaliseFamInst fun ty1
227         ; (coi2,nty2) <- tcGenericNormaliseFamInst fun ty2
228         ; return (mkFunTyCoI nty1 coi1 nty2 coi2, mkFunTy nty1 nty2)
229         }
230 tcGenericNormaliseFamInst fun (ForAllTy tyvar ty1)
231   = do  { (coi,nty1) <- tcGenericNormaliseFamInst fun ty1
232         ; return (mkForAllTyCoI tyvar coi, mkForAllTy tyvar nty1)
233         }
234 tcGenericNormaliseFamInst fun (NoteTy note ty1)
235   = do  { (coi,nty1) <- tcGenericNormaliseFamInst fun ty1
236         ; return (mkNoteTyCoI note coi, NoteTy note nty1)
237         }
238 tcGenericNormaliseFamInst fun ty@(TyVarTy tv)
239   | isTcTyVar tv
240   = do  { traceTc (text "tcGenericNormaliseFamInst" <+> ppr ty)
241         ; res <- lookupTcTyVar tv
242         ; case res of
243             DoneTv _ -> 
244               do { maybe_ty' <- fun ty
245                  ; case maybe_ty' of
246                      Nothing         -> return (IdCo, ty)
247                      Just (ty', co1) -> 
248                        do { (coi2, ty'') <- tcGenericNormaliseFamInst fun ty'
249                           ; return (ACo co1 `mkTransCoI` coi2, ty'') 
250                           }
251                  }
252             IndirectTv ty' -> tcGenericNormaliseFamInst fun ty' 
253         }
254   | otherwise
255   = return (IdCo, ty)
256 tcGenericNormaliseFamInst fun (PredTy predty)
257   = do  { (coi, pred') <- tcGenericNormaliseFamInstPred fun predty
258         ; return (coi, PredTy pred') }
259
260 ---------------------------------
261 tcGenericNormaliseFamInstPred :: (TcType -> TcM (Maybe (TcType,Coercion)))
262                               -> TcPredType
263                               -> TcM (CoercionI, TcPredType)
264
265 tcGenericNormaliseFamInstPred fun (ClassP cls tys) 
266   = do { (cois, tys')<- mapAndUnzipM (tcGenericNormaliseFamInst fun) tys
267        ; return (mkClassPPredCoI cls tys' cois, ClassP cls tys')
268        }
269 tcGenericNormaliseFamInstPred fun (IParam ipn ty) 
270   = do { (coi, ty') <- tcGenericNormaliseFamInst fun ty
271        ; return $ (mkIParamPredCoI ipn coi, IParam ipn ty')
272        }
273 tcGenericNormaliseFamInstPred fun (EqPred ty1 ty2) 
274   = do { (coi1, ty1') <- tcGenericNormaliseFamInst fun ty1
275        ; (coi2, ty2') <- tcGenericNormaliseFamInst fun ty2
276        ; return (mkEqPredCoI ty1' coi1 ty2' coi2, EqPred ty1' ty2') }
277 \end{code}
278
279
280 %************************************************************************
281 %*                                                                      *
282 \section{Normalisation of equality constraints}
283 %*                                                                      *
284 %************************************************************************
285
286 Note [Inconsistencies in equality constraints]
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
288 We guarantee that we raise an error if we discover any inconsistencies (i.e.,
289 equalities that if presented to the unifer in TcUnify would result in an
290 error) during normalisation of wanted constraints.  This is especially so that
291 we don't solve wanted constraints under an inconsistent given set.  In
292 particular, we don't want to permit signatures, such as
293
294   bad :: (Int ~ Bool => Int) -> a -> a
295
296 \begin{code}
297 normaliseGivenEqs :: [Inst] -> TcM ([Inst], TcM ())
298 normaliseGivenEqs givens
299  = do { traceTc (text "normaliseGivenEqs <-" <+> ppr givens)
300       ; (result, deSkolem) <- 
301           rewriteToFixedPoint (Just ("(SkolemOccurs)", skolemOccurs))
302             [ ("(ZONK)",    dontRerun $ zonkInsts)
303             , ("(TRIVIAL)", dontRerun $ trivialRule)
304             , ("(DECOMP)",  decompRule)
305             , ("(TOP)",     topRule)
306             , ("(SUBST)",   substRule)                   -- incl. occurs check
307             ] givens
308       ; traceTc (text "normaliseGivenEqs ->" <+> ppr result)
309       ; return (result, deSkolem)
310       }
311 \end{code}
312
313 \begin{code}
314 normaliseWantedEqs :: [Inst] -> TcM [Inst]
315 normaliseWantedEqs insts 
316   = do { traceTc (text "normaliseWantedEqs <-" <+> ppr insts)
317        ; result <- liftM fst $ rewriteToFixedPoint Nothing
318                      [ ("(ZONK)",    dontRerun $ zonkInsts)
319                      , ("(TRIVIAL)", dontRerun $ trivialRule)
320                      , ("(DECOMP)",  decompRule)
321                      , ("(TOP)",     topRule)
322                      , ("(UNIFY)",   unifyMetaRule)      -- incl. occurs check
323                      , ("(SUBST)",   substRule)          -- incl. occurs check
324                      ] insts
325        ; traceTc (text "normaliseWantedEqs ->" <+> ppr result)
326        ; return result
327        }
328 \end{code}
329
330
331 %************************************************************************
332 %*                                                                      *
333 \section{Solving of wanted constraints with respect to a given set}
334 %*                                                                      *
335 %************************************************************************
336
337 The set of given equalities must have been normalised already.
338
339 \begin{code}
340 solveWantedEqs :: [Inst]        -- givens
341              -> [Inst]          -- wanteds
342              -> TcM [Inst]      -- irreducible wanteds
343 solveWantedEqs givens wanteds 
344   = do { traceTc $ text "solveWantedEqs <-" <+> ppr wanteds <+> text "with" <+> 
345                    ppr givens
346        ; result <- liftM fst $ rewriteToFixedPoint Nothing
347                      [ ("(ZONK)",    dontRerun $ zonkInsts)
348                      , ("(TRIVIAL)", dontRerun $ trivialRule)
349                      , ("(DECOMP)",  decompRule)
350                      , ("(TOP)",     topRule)
351                      , ("(GIVEN)",   substGivens givens) -- incl. occurs check
352                      , ("(UNIFY)",   unifyMetaRule)      -- incl. occurs check
353                      ] wanteds
354        ; traceTc (text "solveWantedEqs ->" <+> ppr result)
355        ; return result
356        }
357   where
358     -- Use `substInst' with every given on all the wanteds.
359     substGivens :: [Inst] -> [Inst] -> TcM ([Inst], Bool)                
360     substGivens []     wanteds = return (wanteds, False)
361     substGivens (g:gs) wanteds
362       = do { (wanteds1, changed1) <- substGivens gs wanteds
363            ; (wanteds2, changed2) <- substInst g wanteds1
364            ; return (wanteds2, changed1 || changed2)
365            }
366 \end{code}
367
368
369 %************************************************************************
370 %*                                                                      *
371 \section{Normalisation of non-equality dictionaries}
372 %*                                                                      *
373 %************************************************************************
374
375 \begin{code}
376 normaliseGivenDicts, normaliseWantedDicts
377         :: [Inst]               -- given equations
378         -> [Inst]               -- dictionaries
379         -> TcM ([Inst],TcDictBinds)
380
381 normaliseGivenDicts  eqs dicts = normalise_dicts eqs dicts False
382 normaliseWantedDicts eqs dicts = normalise_dicts eqs dicts True
383
384 normalise_dicts
385         :: [Inst]       -- given equations
386         -> [Inst]       -- dictionaries
387         -> Bool         -- True <=> the dicts are wanted 
388                         -- Fals <=> they are given
389         -> TcM ([Inst],TcDictBinds)
390 normalise_dicts given_eqs dicts is_wanted
391   = do  { traceTc $ text "normalise???Dicts <-" <+> ppr dicts <+> 
392                     text "with" <+> ppr given_eqs
393         ; (dicts0, binds0)  <- normaliseInsts is_wanted dicts
394         ; (dicts1, binds1)  <- substEqInDictInsts given_eqs dicts0
395         ; let binds01 = binds0 `unionBags` binds1
396         ; if isEmptyBag binds1
397           then return (dicts1, binds01)
398           else do { (dicts2, binds2) <- normaliseGivenDicts given_eqs dicts1
399                   ; return (dicts2, binds01 `unionBags` binds2) } }
400 \end{code}
401
402
403 %************************************************************************
404 %*                                                                      *
405 \section{Normalisation rules and iterative rule application}
406 %*                                                                      *
407 %************************************************************************
408
409 We have three kinds of normalising rewrite rules:
410
411 (1) Normalisation rules that rewrite a set of insts and return a flag indicating
412     whether any changes occurred during rewriting that necessitate re-running
413     the current rule set.
414
415 (2) Precondition rules that rewrite a set of insts and return a monadic action
416     that reverts the effect of preconditioning.
417
418 (3) Idempotent normalisation rules that never require re-running the rule set. 
419
420 \begin{code}
421 type RewriteRule     = [Inst] -> TcM ([Inst], Bool)   -- rewrite, maybe re-run
422 type PrecondRule     = [Inst] -> TcM ([Inst], TcM ()) -- rewrite, revertable
423 type IdemRewriteRule = [Inst] -> TcM [Inst]           -- rewrite, don't re-run
424
425 type NamedRule       = (String, RewriteRule)          -- rule with description
426 type NamedPreRule    = (String, PrecondRule)          -- precond with desc
427 \end{code}
428
429 Template lifting idempotent rules to full rules (which can be put into a rule
430 set).
431
432 \begin{code}
433 dontRerun :: IdemRewriteRule -> RewriteRule
434 dontRerun rule insts = liftM addFalse $ rule insts
435   where
436     addFalse x = (x, False)
437 \end{code}
438
439 The following function applies a set of rewrite rules until a fixed point is
440 reached; i.e., none of the `RewriteRule's require re-running the rule set.
441 Optionally, there may be a pre-conditing rule that is applied before any other
442 rules are applied and before the rule set is re-run.
443
444 The result is the set of rewritten (i.e., normalised) insts and, in case of a
445 pre-conditing rule, a monadic action that reverts the effects of
446 pre-conditioning - specifically, this is removing introduced skolems.
447
448 \begin{code}
449 rewriteToFixedPoint :: Maybe NamedPreRule   -- optional preconditioning rule
450                     -> [NamedRule]          -- rule set
451                     -> [Inst]               -- insts to rewrite
452                     -> TcM ([Inst], TcM ())
453 rewriteToFixedPoint precondRule rules insts
454   = completeRewrite (return ()) precondRule insts
455   where
456     completeRewrite :: TcM () -> Maybe NamedPreRule -> [Inst] 
457                     -> TcM ([Inst], TcM ())
458     completeRewrite dePrecond (Just (precondName, precond)) insts
459       = do { traceTc $ text precondName <+> text " <- " <+> ppr insts
460            ; (insts', dePrecond') <- precond insts
461            ; traceTc $ text precondName <+> text " -> " <+> ppr insts'
462            ; tryRules (dePrecond >> dePrecond') rules insts'
463            }
464     completeRewrite dePrecond Nothing insts
465       = tryRules dePrecond rules insts
466
467     tryRules dePrecond _                    []    = return ([]   , dePrecond)
468     tryRules dePrecond []                   insts = return (insts, dePrecond)
469     tryRules dePrecond ((name, rule):rules) insts 
470       = do { traceTc $ text name <+> text " <- " <+> ppr insts
471            ; (insts', rerun) <- rule insts
472            ; traceTc $ text name <+> text " -> " <+> ppr insts'
473            ; if rerun then completeRewrite dePrecond precondRule insts'
474                       else tryRules dePrecond rules insts'
475            }
476 \end{code}
477
478
479 %************************************************************************
480 %*                                                                      *
481 \section{Different forms of Inst rewrite rules}
482 %*                                                                      *
483 %************************************************************************
484
485 Splitting of non-terminating given constraints: skolemOccurs
486 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
487 This is a preconditioning rule exclusively applied to given constraints.
488 Moreover, its rewriting is only temporary, as it is undone by way of
489 side-effecting mutable type variables after simplification and constraint
490 entailment has been completed.
491
492 This version is an (attempt at, yet unproven, an) *unflattened* version of
493 the SubstL-Ev completion rule.
494
495 The above rule is essential to catch non-terminating rules that cannot be
496 oriented properly, like 
497
498      F a ~ [G (F a)]
499  or even
500      a ~ [G a]          , where a is a skolem tyvar
501
502 The left-to-right orientiation is not suitable because it does not
503 terminate. The right-to-left orientation is not suitable because it 
504 does not have a type-function on the left. This is undesirable because
505 it would hide information. E.g. assume 
506
507         instance C [x]
508
509 then rewriting C [G (F a)] to C (F a) is bad because we cannot now
510 see that the C [x] instance applies.
511
512 The rule also caters for badly-oriented rules of the form:
513
514      F a ~ G (F a)
515
516 for which other solutions are possible, but this one will do too.
517
518 It's behavior is:
519
520   co : ty1 ~ ty2{F ty1}
521      >-->
522   co         : ty1 ~ ty2{b}
523   sym (F co) : F ty2{b} ~ b
524         where b is a fresh skolem variable
525
526 We also cater for the symmetric situation *if* the rule cannot be used as a
527 left-to-right rewrite rule.
528
529 We also return an action (b := ty1) which is used to eliminate b 
530 after the dust of normalisation with the completed rewrite system
531 has settled.
532
533 A subtle point of this transformation is that both coercions in the results
534 are strictly speaking incorrect.  However, they are correct again after the
535 action {B := ty1} has removed the skolem again.  This happens immediately
536 after constraint entailment has been checked; ie, code outside of the
537 simplification and entailment checking framework will never see these
538 temporarily incorrect coercions.
539
540 NB: We perform this transformation for multiple occurences of ty1 under one
541     or multiple family applications on the left-hand side at once (ie, the
542     rule doesn't need to be applied multiple times at a single inst).  As a 
543     result we can get two or more insts back.
544
545 Note [skolemOccurs loop]
546 ~~~~~~~~~~~~~~~~~~~~~~~~
547 You might think that under
548
549   type family F a 
550   type instance F [a] = [F a]
551
552 a signature such as
553
554   foo :: (F [a] ~ a) => a
555
556 will get us into a loop.  However, this is *not* the case.  Here is why:
557
558     F [a<sk>] ~ a<sk>
559
560     -->(TOP)
561
562     [F a<sk>] ~ a<sk>
563
564     -->(SkolemOccurs)
565
566     [b<tau>] ~ a<sk>
567     F [b<tau>] ~ b<tau>   , with b := F a
568
569     -->(TOP)
570
571     [b<tau>] ~ a<sk>
572     [F b<tau>] ~ b<tau>   , with b := F a
573
574 At this point (SkolemOccurs) does *not* apply anymore, as 
575
576   [F b<tau>] ~ b<tau>
577
578 is not used as a rewrite rule.  The variable b<tau> is not a skolem (cf
579 eqInstToRewrite). 
580
581 (The regression test indexed-types/should_compile/Simple20 checks that the
582 described property of the system does not change.)
583
584 \begin{code}
585 skolemOccurs :: PrecondRule
586 skolemOccurs insts
587   = do { (instss, undoSkolems) <- mapAndUnzipM oneSkolemOccurs insts
588        ; return (concat instss, sequence_ undoSkolems)
589        }
590   where
591     oneSkolemOccurs inst
592       = ASSERT( isEqInst inst )
593         case eqInstToRewrite inst of
594           Just (rewrite, swapped) -> breakRecursion rewrite swapped
595           Nothing                 -> return ([inst], return ())
596       where
597         -- inst is an elementary rewrite rule, check whether we need to break
598         -- it up
599         breakRecursion (Rewrite pat body _) swapped
600
601           -- skolemOccurs does not apply, leave as is
602           | null tysToLiftOut 
603           = do { traceTc $ text "oneSkolemOccurs: no tys to lift out"
604                ; return ([inst], return ())
605                }
606
607           -- recursive occurence of pat in body under a type family application
608           | otherwise
609           = do { traceTc $ text "oneSkolemOccurs[TLO]:" <+> ppr tysToLiftOut
610                ; skTvs <- mapM (newMetaTyVar TauTv . typeKind) tysToLiftOut
611                ; let skTvs_tysTLO   = zip skTvs tysToLiftOut
612                      insertSkolems = return . replace skTvs_tysTLO
613                ; (_, body') <- tcGenericNormaliseFamInst insertSkolems body
614                ; inst' <- if swapped then mkEqInst (EqPred body' pat) co
615                                      else mkEqInst (EqPred pat body') co
616                                      -- ensure to reconstruct the inst in the
617                                      -- original orientation
618                ; traceTc $ text "oneSkolemOccurs[inst']:" <+> ppr inst'
619                ; (insts, undoSk) <- mapAndUnzipM (mkSkolemInst inst') 
620                                                  skTvs_tysTLO
621                ; return (inst':insts, sequence_ undoSk)
622                }
623           where
624             co  = eqInstCoercion inst
625
626             -- all subtypes that are (1) type family instances and (2) contain
627             -- the lhs type as part of the type arguments of the type family
628             -- constructor 
629             tysToLiftOut = [mkTyConApp tc tys | (tc, tys) <- tyFamInsts body
630                                               , any (pat `tcPartOfType`) tys]
631
632             replace :: [(TcTyVar, Type)] -> Type -> Maybe (Type, Coercion)
633             replace []                   _  = Nothing
634             replace ((skTv, tyTLO):rest) ty 
635               | tyTLO `tcEqType` ty         = Just (mkTyVarTy skTv, undefined)
636               | otherwise                   = replace rest ty
637
638             -- create the EqInst for the equality determining the skolem and a
639             -- TcM action undoing the skolem introduction
640             mkSkolemInst inst' (skTv, tyTLO)
641               = do { (co, tyLiftedOut) <- tcEqInstNormaliseFamInst inst' tyTLO
642                    ; inst <- mkEqInst (EqPred tyLiftedOut (mkTyVarTy skTv)) 
643                                       (mkGivenCo $ mkSymCoercion (fromACo co))
644                                       -- co /= IdCo due to construction of inst'
645                    ; return (inst, writeMetaTyVar skTv tyTLO) 
646                    }
647 \end{code}
648
649
650 Removal of trivial equalities: trivialRule
651 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
652 The following rules exploits the reflexivity of equality:
653
654   (Trivial)
655     g1 : t ~ t
656       >-->
657     g1 := t
658
659 \begin{code}
660 trivialRule :: IdemRewriteRule
661 trivialRule insts 
662   = liftM catMaybes $ mappM trivial insts
663   where
664     trivial inst
665       | ASSERT( isEqInst inst )
666         ty1 `tcEqType` ty2
667       = do { eitherEqInst inst
668                (\cotv -> writeMetaTyVar cotv ty1) 
669                (\_    -> return ())
670            ; return Nothing
671            }
672       | otherwise
673       = return $ Just inst
674       where
675          (ty1,ty2) = eqInstTys inst
676 \end{code}
677
678
679 Decomposition of data type constructors: decompRule
680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681 Whenever, the same *data* constructors occurs on both sides of an equality, we
682 can decompose as in standard unification.
683
684   (Decomp)
685     g1 : T cs ~ T ds
686       >-->
687     g21 : c1 ~ d1, ..., g2n : cn ~ dn
688     g1 := T g2s
689
690 Works also for the case where T is actually an application of a type family
691 constructor to a set of types, provided the applications on both sides of the
692 ~ are identical; see also Note [OpenSynTyCon app] in TcUnify.
693
694 We guarantee to raise an error for any inconsistent equalities; 
695 cf Note [Inconsistencies in equality constraints].
696
697 \begin{code}
698 decompRule :: RewriteRule
699 decompRule insts 
700   = do { (insts, changed) <- mapAndUnzipM decomp insts
701        ; return (concat insts, or changed)
702        }
703   where
704     decomp inst
705       = ASSERT( isEqInst inst )
706         go ty1 ty2
707       where
708         (ty1,ty2) = eqInstTys inst
709         go ty1 ty2              
710           | Just ty1' <- tcView ty1 = go ty1' ty2 
711           | Just ty2' <- tcView ty2 = go ty1 ty2' 
712
713         go (TyConApp con1 tys1) (TyConApp con2 tys2)
714           | con1 == con2 && identicalHead
715           = mkArgInsts (mkTyConApp con1) tys1 tys2
716
717           | con1 /= con2 && not (isOpenSynTyCon con1 || isOpenSynTyCon con2)
718             -- not matching data constructors (of any flavour) are bad news
719           = eqInstMisMatch inst
720           where
721             n             = tyConArity con1
722             (idxTys1, _)  = splitAt n tys1
723             (idxTys2, _)  = splitAt n tys2
724             identicalHead = not (isOpenSynTyCon con1) ||
725                             idxTys1 `tcEqTypes` idxTys2
726
727         go (FunTy fun1 arg1) (FunTy fun2 arg2)
728           = mkArgInsts (\[funCo, argCo] -> mkFunTy funCo argCo) [fun1, arg1]
729                                                                 [fun2, arg2]
730
731         -- Applications need a bit of care!
732         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
733         go (AppTy s1 t1) ty2
734           | Just (s2, t2) <- tcSplitAppTy_maybe ty2
735           = mkArgInsts (\[s, t] -> mkAppTy s t) [s1, t1] [s2, t2]
736
737         -- Symmetric case
738         go ty1 (AppTy s2 t2)
739           | Just (s1, t1) <- tcSplitAppTy_maybe ty1
740           = mkArgInsts (\[s, t] -> mkAppTy s t) [s1, t1] [s2, t2]
741
742         -- We already covered all the consistent cases of rigid types on both
743         -- sides; so, if we see two rigid types here, we discovered an
744         -- inconsistency. 
745         go ty1 ty2 
746           | isRigid ty1 && isRigid ty2
747           = eqInstMisMatch inst
748
749         -- We can neither assert consistency nor inconsistency => defer
750         go _ _ = return ([inst], False)
751
752         isRigid (TyConApp con _) = not (isOpenSynTyCon con)
753         isRigid (FunTy _ _)      = True
754         isRigid (AppTy _ _)      = True
755         isRigid _                = False
756
757         -- Create insts for matching argument positions (ie, the bit after
758         -- '>-->' in the rule description above)
759         mkArgInsts con tys1 tys2
760           = do { cos <- eitherEqInst inst
761                           -- old_co := Con1 cos
762                           (\old_covar ->
763                             do { cotvs <- zipWithM newMetaCoVar tys1 tys2
764                                ; let cos = map mkTyVarTy cotvs
765                                ; writeMetaTyVar old_covar (con cos)
766                                ; return $ map mkWantedCo cotvs
767                                })
768                           -- co_i := Con_i old_co
769                           (\old_co -> 
770                             return $ map mkGivenCo $
771                                          mkRightCoercions (length tys1) old_co)
772                ; insts <- zipWithM mkEqInst (zipWith EqPred tys1 tys2) cos
773                ; traceTc (text "decomp identicalHead" <+> ppr insts) 
774                ; return (insts, not $ null insts) 
775                }
776 \end{code}
777
778
779 Rewriting with type instances: topRule
780 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
781 We use (toplevel) type instances to normalise both sides of equalities.
782
783   (Top)
784     g1 : t ~ s
785       >--> co1 :: t ~ t' / co2 :: s ~ s'
786     g2 : t' ~ s'
787     g1 := co1 * g2 * sym co2
788
789 \begin{code}
790 topRule :: RewriteRule
791 topRule insts 
792   =  do { (insts, changed) <- mapAndUnzipM top insts
793         ; return (insts, or changed)
794         }
795   where
796     top inst
797       = ASSERT( isEqInst inst )
798         do { (coi1, ty1') <- tcNormaliseFamInst ty1
799            ; (coi2, ty2') <- tcNormaliseFamInst ty2
800            ; case (coi1, coi2) of
801                (IdCo, IdCo) -> return (inst, False)
802                _            -> 
803                  do { wg_co <- 
804                        eitherEqInst inst
805                          -- old_co = co1 * new_co * sym co2
806                          (\old_covar ->
807                            do { new_cotv <- newMetaCoVar ty1' ty2'
808                               ; let new_co  = mkTyVarTy new_cotv
809                                     old_coi = coi1 `mkTransCoI` 
810                                               ACo new_co `mkTransCoI` 
811                                               (mkSymCoI coi2)
812                               ; writeMetaTyVar old_covar (fromACo old_coi)
813                               ; return $ mkWantedCo new_cotv
814                               })
815                          -- new_co = sym co1 * old_co * co2
816                          (\old_co -> 
817                            return $ 
818                              mkGivenCo $ 
819                                fromACo $ 
820                                  mkSymCoI coi1 `mkTransCoI` 
821                                  ACo old_co `mkTransCoI` coi2)  
822                    ; new_inst <- mkEqInst (EqPred ty1' ty2') wg_co 
823                    ; return (new_inst, True)
824                    }
825              }
826       where
827         (ty1,ty2) = eqInstTys inst
828 \end{code}
829
830
831 Rewriting with equalities: substRule
832 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
833 From a set of insts, use all insts that can be read as rewrite rules to
834 rewrite the types in all other insts.
835
836   (Subst)
837     g : F c ~ t,
838     forall g1 : s1{F c} ~ s2{F c}
839       >-->
840     g2 : s1{t} ~ s2{t}
841     g1 := s1{g} * g2  * sym s2{g}  <=>  g2 := sym s1{g} * g1 * s2{g}
842
843 Alternatively, the rewrite rule may have the form (g : a ~ t).
844
845 To avoid having to swap rules of the form (g : t ~ F c) and (g : t ~ a),
846 where t is neither a variable nor a type family application, we use them for
847 rewriting from right-to-left.  However, it is crucial to only apply rules
848 from right-to-left if they cannot be used left-to-right.
849
850 The workhorse is substInst, which performs an occurs check before actually
851 using an equality for rewriting.  If the type pattern occurs in the type we
852 substitute for the pattern, normalisation would diverge.
853
854 \begin{code}
855 substRule :: RewriteRule
856 substRule insts = tryAllInsts insts []
857   where
858     -- for every inst check whether it can be used to rewrite the others
859     -- (we make an effort to keep the insts in order; it makes debugging
860     -- easier)
861     tryAllInsts []           triedInsts = return (reverse triedInsts, False)
862     tryAllInsts (inst:insts) triedInsts
863       = do { (insts', changed) <- substInst inst (reverse triedInsts ++ insts)
864            ; if changed then return (insertAt (length triedInsts) inst insts',
865                                      True)
866                         else tryAllInsts insts (inst:triedInsts)
867            }
868       where
869         insertAt n x xs = let (xs1, xs2) = splitAt n xs
870                           in xs1 ++ [x] ++ xs2
871
872 -- Use the given inst as a rewrite rule to normalise the insts in the second
873 -- argument.  Don't do anything if the inst cannot be used as a rewrite rule,
874 -- but do apply it right-to-left, if possible, and if it cannot be used
875 -- left-to-right. 
876 --
877 substInst :: Inst -> [Inst] -> TcM ([Inst], Bool)
878 substInst inst insts
879   = case eqInstToRewrite inst of
880       Just (rewrite, _) -> substEquality rewrite insts
881       Nothing           -> return (insts, False)
882   where
883     substEquality :: Rewrite            -- elementary rewrite
884                   -> [Inst]             -- insts to rewrite
885                   -> TcM ([Inst], Bool)
886     substEquality eqRule@(Rewrite pat rhs _) insts
887       | pat `tcPartOfType` rhs      -- occurs check!
888       = occurCheckErr pat rhs
889       | otherwise
890       = do { (insts', changed) <- mapAndUnzipM substOne insts
891            ; return (insts', or changed)
892            }
893       where
894         substOne inst
895           = ASSERT( isEqInst inst )
896             do { (coi1, ty1') <- tcEqRuleNormaliseFamInst eqRule ty1
897                ; (coi2, ty2') <- tcEqRuleNormaliseFamInst eqRule ty2
898                ; case (coi1, coi2) of
899                 (IdCo, IdCo) -> return (inst, False)
900                 _            -> 
901                   do { gw_co <- 
902                          eitherEqInst inst
903                            -- old_co := co1 * new_co * sym co2
904                            (\old_covar ->
905                              do { new_cotv <- newMetaCoVar ty1' ty2'
906                                 ; let new_co  = mkTyVarTy new_cotv
907                                       old_coi = coi1 `mkTransCoI` 
908                                                 ACo new_co `mkTransCoI` 
909                                                 (mkSymCoI coi2)
910                                 ; writeMetaTyVar old_covar (fromACo old_coi)
911                                 ; return $ mkWantedCo new_cotv
912                                 })
913                            -- new_co := sym co1 * old_co * co2
914                            (\old_co -> 
915                              return $ 
916                                mkGivenCo $ 
917                                  fromACo $ 
918                                    mkSymCoI coi1 `mkTransCoI` 
919                                    ACo old_co `mkTransCoI` coi2)
920                      ; new_inst <- mkEqInst (EqPred ty1' ty2') gw_co
921                      ; return (new_inst, True)
922                      }
923                }
924           where 
925             (ty1,ty2) = eqInstTys inst
926 \end{code}
927
928
929 Instantiate meta variables: unifyMetaRule
930 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
931 If an equality equates a meta type variable with a type, we simply instantiate
932 the meta variable.
933
934   (UnifyMeta)
935     g : alpha ~ t
936       >-->
937     alpha := t
938     g     := t
939
940 Meta variables can only appear in wanted constraints, and this rule should
941 only be applied to wanted constraints.  We also know that t definitely is
942 distinct from alpha (as the trivialRule) has been run on the insts beforehand.
943
944 NB: We cannot assume that meta tyvars are empty.  They may have been updated
945 by another inst in the currently processed wanted list.  We need to be very
946 careful when updateing type variables (see TcUnify.uUnfilledVar), but at least
947 we know that we have no boxes.  It's unclear that it would be an advantage to
948 common up the code in TcUnify and the code below.  Firstly, we don't want
949 calls to TcUnify.defer_unification here, and secondly, TcUnify import the
950 current module, so we would have to move everything here (Yuk!) or to
951 TcMType.  Besides, the code here is much simpler due to the lack of boxes.
952
953 \begin{code}
954 unifyMetaRule :: RewriteRule
955 unifyMetaRule insts 
956   = do { (insts', changed) <- mapAndUnzipM unifyMeta insts
957        ; return (concat insts', or changed)
958        }
959   where
960     unifyMeta inst
961       = ASSERT( isEqInst inst )
962         go ty1 ty2
963            (fromWantedCo "unifyMetaRule" $ eqInstCoercion inst)
964       where
965         (ty1,ty2) = eqInstTys inst
966         go ty1 ty2 cotv
967           | Just ty1' <- tcView ty1 = go ty1' ty2 cotv
968           | Just ty2' <- tcView ty2 = go ty1 ty2' cotv
969
970           | TyVarTy tv1 <- ty1
971           , isMetaTyVar tv1         = do { lookupTV <- lookupTcTyVar tv1
972                                          ; uMeta False tv1 lookupTV ty2 cotv
973                                          }
974           | TyVarTy tv2 <- ty2
975           , isMetaTyVar tv2         = do { lookupTV <- lookupTcTyVar tv2
976                                          ; uMeta True tv2 lookupTV ty1 cotv
977                                          }
978           | otherwise               = return ([inst], False) 
979
980         -- meta variable has been filled already
981         -- => ignore this inst (we'll come around again, after zonking)
982         uMeta _swapped _tv (IndirectTv _) _ty _cotv
983           = return ([inst], False)
984
985         -- signature skolem meets non-variable type
986         -- => cannot update!
987         uMeta _swapped _tv (DoneTv (MetaTv (SigTv _) _)) ty _cotv
988           | not $ isTyVarTy ty
989           = return ([inst], False)
990
991         -- type variable meets type variable
992         -- => check that tv2 hasn't been updated yet and choose which to update
993         uMeta swapped tv1 (DoneTv details1) (TyVarTy tv2) cotv
994           = do { lookupTV2 <- lookupTcTyVar tv2
995                ; case lookupTV2 of
996                    IndirectTv ty  -> uMeta swapped tv1 (DoneTv details1) ty cotv
997                    DoneTv details2 -> 
998                      uMetaVar swapped tv1 details1 tv2 details2 cotv
999                }
1000
1001         -- updatable meta variable meets non-variable type
1002         -- => occurs check, monotype check, and kinds match check, then update
1003         uMeta swapped tv (DoneTv (MetaTv _ ref)) ty cotv
1004           = do { mb_ty' <- checkTauTvUpdate tv ty    -- occurs + monotype check
1005                ; case mb_ty' of
1006                    Nothing  -> return ([inst], False)  -- tv occurs in faminst
1007                    Just ty' ->
1008                      do { checkUpdateMeta swapped tv ref ty'  -- update meta var
1009                         ; writeMetaTyVar cotv ty'             -- update co var
1010                         ; return ([], True)
1011                         }
1012                }
1013
1014         uMeta _ _ _ _ _ = panic "uMeta"
1015
1016         -- meta variable meets skolem 
1017         -- => just update
1018         uMetaVar swapped tv1 (MetaTv _ ref) tv2 (SkolemTv _) cotv
1019           = do { checkUpdateMeta swapped tv1 ref (mkTyVarTy tv2)
1020                ; writeMetaTyVar cotv (mkTyVarTy tv2)
1021                ; return ([], True)
1022                }
1023
1024         -- meta variable meets meta variable 
1025         -- => be clever about which of the two to update 
1026         --   (from TcUnify.uUnfilledVars minus boxy stuff)
1027         uMetaVar swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2) cotv
1028           = do { case (info1, info2) of
1029                    -- Avoid SigTvs if poss
1030                    (SigTv _, _      ) | k1_sub_k2 -> update_tv2
1031                    (_,       SigTv _) | k2_sub_k1 -> update_tv1
1032
1033                    (_,   _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1034                                            then update_tv1      -- Same kinds
1035                                            else update_tv2
1036                             | k2_sub_k1 -> update_tv1
1037                             | otherwise -> kind_err
1038               -- Update the variable with least kind info
1039               -- See notes on type inference in Kind.lhs
1040               -- The "nicer to" part only applies if the two kinds are the same,
1041               -- so we can choose which to do.
1042
1043                ; writeMetaTyVar cotv (mkTyVarTy tv2)
1044                ; return ([], True)
1045                }
1046           where
1047                 -- Kinds should be guaranteed ok at this point
1048             update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1049             update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1050
1051             kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1052                        unifyKindMisMatch k1 k2
1053
1054             k1 = tyVarKind tv1
1055             k2 = tyVarKind tv2
1056             k1_sub_k2 = k1 `isSubKind` k2
1057             k2_sub_k1 = k2 `isSubKind` k1
1058
1059             nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1060                 -- Try to update sys-y type variables in preference to ones
1061                 -- gotten (say) by instantiating a polymorphic function with
1062                 -- a user-written type sig 
1063
1064         uMetaVar _ _ _ _ _ _ = panic "uMetaVar"
1065 \end{code}
1066
1067
1068 %************************************************************************
1069 %*                                                                      *
1070 \section{Normalisation of Insts}
1071 %*                                                                      *
1072 %************************************************************************
1073
1074 Normalises a set of dictionaries relative to a set of given equalities (which
1075 are interpreted as rewrite rules).  We only consider given equalities of the
1076 form
1077
1078   F ts ~ t    or    a ~ t
1079
1080 where F is a type family.
1081
1082 \begin{code}
1083 substEqInDictInsts :: [Inst]    -- given equalities (used as rewrite rules)
1084                    -> [Inst]    -- dictinaries to be normalised
1085                    -> TcM ([Inst], TcDictBinds)
1086 substEqInDictInsts eqInsts dictInsts 
1087   = do { traceTc (text "substEqInDictInst <-" <+> ppr dictInsts)
1088        ; dictInsts' <- 
1089            foldlM rewriteWithOneEquality (dictInsts, emptyBag) eqInsts
1090        ; traceTc (text "substEqInDictInst ->" <+> ppr dictInsts')
1091        ; return dictInsts'
1092        }
1093   where
1094       -- (1) Given equality of form 'F ts ~ t' or 'a ~ t': use for rewriting
1095     rewriteWithOneEquality (dictInsts, dictBinds)
1096                            eqInst@(EqInst {tci_left  = pattern, 
1097                                            tci_right = target})
1098       | isOpenSynTyConApp pattern || isTyVarTy pattern
1099       = do { (dictInsts', moreDictBinds) <- 
1100                genericNormaliseInsts True {- wanted -} applyThisEq dictInsts
1101            ; return (dictInsts', dictBinds `unionBags` moreDictBinds)
1102            }
1103       where
1104         applyThisEq = tcGenericNormaliseFamInstPred (return . matchResult)
1105
1106         -- rewrite in case of an exact match
1107         matchResult ty | tcEqType pattern ty = Just (target, eqInstType eqInst)
1108                        | otherwise           = Nothing
1109
1110       -- (2) Given equality has the wrong form: ignore
1111     rewriteWithOneEquality (dictInsts, dictBinds) _not_a_rewrite_rule
1112       = return (dictInsts, dictBinds)
1113 \end{code}
1114
1115
1116 Take a bunch of Insts (not EqInsts), and normalise them wrt the top-level
1117 type-function equations, where
1118
1119         (norm_insts, binds) = normaliseInsts is_wanted insts
1120
1121 If 'is_wanted'
1122   = True,  (binds + norm_insts) defines insts       (wanteds)
1123   = False, (binds + insts)      defines norm_insts  (givens)
1124
1125 Ie, in the case of normalising wanted dictionaries, we use the normalised
1126 dictionaries to define the originally wanted ones.  However, in the case of
1127 given dictionaries, we use the originally given ones to define the normalised
1128 ones. 
1129
1130 \begin{code}
1131 normaliseInsts :: Bool                          -- True <=> wanted insts
1132                -> [Inst]                        -- wanted or given insts 
1133                -> TcM ([Inst], TcDictBinds)     -- normalised insts and bindings
1134 normaliseInsts isWanted insts 
1135   = genericNormaliseInsts isWanted tcNormaliseFamInstPred insts
1136
1137 genericNormaliseInsts  :: Bool                      -- True <=> wanted insts
1138                        -> (TcPredType -> TcM (CoercionI, TcPredType))  
1139                                                     -- how to normalise
1140                        -> [Inst]                    -- wanted or given insts 
1141                        -> TcM ([Inst], TcDictBinds) -- normalised insts & binds
1142 genericNormaliseInsts isWanted fun insts
1143   = do { (insts', binds) <- mapAndUnzipM (normaliseOneInst isWanted fun) insts
1144        ; return (insts', unionManyBags binds)
1145        }
1146   where
1147     normaliseOneInst isWanted fun
1148                      dict@(Dict {tci_pred = pred,
1149                                  tci_loc  = loc})
1150       = do { traceTc $ text "genericNormaliseInst <-" <+> ppr dict
1151            ; (coi, pred') <- fun pred
1152
1153            ; case coi of
1154                IdCo   -> 
1155                  do { traceTc $ text "genericNormaliseInst ->" <+> ppr dict
1156                     ; return (dict, emptyBag)
1157                     }
1158                          -- don't use pred' in this case; otherwise, we get
1159                          -- more unfolded closed type synonyms in error messages
1160                ACo co -> 
1161                  do { -- an inst for the new pred
1162                     ; dict' <- newDictBndr loc pred'
1163                       -- relate the old inst to the new one
1164                       -- target_dict = source_dict `cast` st_co
1165                     ; let (target_dict, source_dict, st_co) 
1166                             | isWanted  = (dict,  dict', mkSymCoercion co)
1167                             | otherwise = (dict', dict,  co)
1168                               -- we have
1169                               --   co :: dict ~ dict'
1170                               -- hence, if isWanted
1171                               --          dict  = dict' `cast` sym co
1172                               --        else
1173                               --          dict' = dict  `cast` co
1174                           expr      = HsVar $ instToId source_dict
1175                           cast_expr = HsWrap (WpCo st_co) expr
1176                           rhs       = L (instLocSpan loc) cast_expr
1177                           binds     = instToDictBind target_dict rhs
1178                       -- return the new inst
1179                     ; traceTc $ text "genericNormaliseInst ->" <+> ppr dict'
1180                     ; return (dict', binds)
1181                     }
1182            }
1183         
1184         -- TOMDO: What do we have to do about ImplicInst, Method, and LitInst??
1185     normaliseOneInst _isWanted _fun inst
1186       = do { inst' <- zonkInst inst
1187            ; return (inst', emptyBag)
1188            }
1189 \end{code}
1190
1191
1192 %************************************************************************
1193 %*                                                                      *
1194 \section{Errors}
1195 %*                                                                      *
1196 %************************************************************************
1197
1198 The infamous couldn't match expected type soandso against inferred type
1199 somethingdifferent message.
1200
1201 \begin{code}
1202 eqInstMisMatch :: Inst -> TcM a
1203 eqInstMisMatch inst
1204   = ASSERT( isEqInst inst )
1205     setErrCtxt ctxt $ failWithMisMatch ty_act ty_exp
1206   where
1207     (ty_act, ty_exp) = eqInstTys inst
1208     InstLoc _ _ ctxt = instLoc   inst
1209
1210 -----------------------
1211 failWithMisMatch :: TcType -> TcType -> TcM a
1212 -- Generate the message when two types fail to match,
1213 -- going to some trouble to make it helpful.
1214 -- The argument order is: actual type, expected type
1215 failWithMisMatch ty_act ty_exp
1216   = do  { env0 <- tcInitTidyEnv
1217         ; ty_exp <- zonkTcType ty_exp
1218         ; ty_act <- zonkTcType ty_act
1219         ; failWithTcM (misMatchMsg env0 (ty_act, ty_exp))
1220         }
1221
1222 misMatchMsg :: TidyEnv -> (TcType, TcType) -> (TidyEnv, SDoc)
1223 misMatchMsg env0 (ty_act, ty_exp)
1224   = let (env1, pp_exp, extra_exp) = ppr_ty env0 ty_exp
1225         (env2, pp_act, extra_act) = ppr_ty env1 ty_act
1226         msg = sep [sep [ptext SLIT("Couldn't match expected type") <+> pp_exp, 
1227                         nest 7 $
1228                               ptext SLIT("against inferred type") <+> pp_act],
1229                    nest 2 (extra_exp $$ extra_act)]
1230     in
1231     (env2, msg)
1232
1233   where
1234     ppr_ty :: TidyEnv -> TcType -> (TidyEnv, SDoc, SDoc)
1235     ppr_ty env ty
1236       = let (env1, tidy_ty) = tidyOpenType env ty
1237             (env2, extra)  = ppr_extra env1 tidy_ty
1238         in
1239         (env2, quotes (ppr tidy_ty), extra)
1240
1241     -- (ppr_extra env ty) shows extra info about 'ty'
1242     ppr_extra :: TidyEnv -> Type -> (TidyEnv, SDoc)
1243     ppr_extra env (TyVarTy tv)
1244       | isTcTyVar tv && (isSkolemTyVar tv || isSigTyVar tv) && not (isUnk tv)
1245       = (env1, pprSkolTvBinding tv1)
1246       where
1247         (env1, tv1) = tidySkolemTyVar env tv
1248
1249     ppr_extra env _ty = (env, empty)            -- Normal case
1250 \end{code}