59cc736083e5883ac4a0da65fd178856c59fa04a
[ghc-hetmet.git] / compiler / typecheck / TcCanonical.lhs
1 \begin{code}
2 module TcCanonical(
3     mkCanonical, mkCanonicals, mkCanonicalFEV, mkCanonicalFEVs, canWanteds, canGivens,
4     canOccursCheck, canEqToWorkList,
5     rewriteWithFunDeps
6  ) where
7
8 #include "HsVersions.h"
9
10 import BasicTypes
11 import Type
12 import TcRnTypes
13 import FunDeps
14 import qualified TcMType as TcM
15 import TcType
16 import TcErrors
17 import Coercion
18 import Class
19 import TyCon
20 import TypeRep
21 import Name
22 import Var
23 import VarEnv           ( TidyEnv )
24 import Outputable
25 import Control.Monad    ( unless, when, zipWithM, zipWithM_ )
26 import MonadUtils
27 import Control.Applicative ( (<|>) )
28
29 import VarSet
30 import Bag
31
32 import HsBinds
33 import TcSMonad
34 import FastString
35 \end{code}
36
37 Note [Canonicalisation]
38 ~~~~~~~~~~~~~~~~~~~~~~~
39 * Converts (Constraint f) _which_does_not_contain_proper_implications_ to CanonicalCts
40 * Unary: treats individual constraints one at a time
41 * Does not do any zonking
42 * Lives in TcS monad so that it can create new skolem variables
43
44
45 %************************************************************************
46 %*                                                                      *
47 %*        Flattening (eliminating all function symbols)                 *
48 %*                                                                      *
49 %************************************************************************
50
51 Note [Flattening]
52 ~~~~~~~~~~~~~~~~~~~~
53   flatten ty  ==>   (xi, cc)
54     where
55       xi has no type functions
56       cc = Auxiliary given (equality) constraints constraining
57            the fresh type variables in xi.  Evidence for these 
58            is always the identity coercion, because internally the
59            fresh flattening skolem variables are actually identified
60            with the types they have been generated to stand in for.
61
62 Note that it is flatten's job to flatten *every type function it sees*.
63 flatten is only called on *arguments* to type functions, by canEqGiven.
64
65 Recall that in comments we use alpha[flat = ty] to represent a
66 flattening skolem variable alpha which has been generated to stand in
67 for ty.
68
69 ----- Example of flattening a constraint: ------
70   flatten (List (F (G Int)))  ==>  (xi, cc)
71     where
72       xi  = List alpha
73       cc  = { G Int ~ beta[flat = G Int],
74               F beta ~ alpha[flat = F beta] }
75 Here
76   * alpha and beta are 'flattening skolem variables'.
77   * All the constraints in cc are 'given', and all their coercion terms 
78     are the identity.
79
80 NB: Flattening Skolems only occur in canonical constraints, which
81 are never zonked, so we don't need to worry about zonking doing
82 accidental unflattening.
83
84 Note that we prefer to leave type synonyms unexpanded when possible,
85 so when the flattener encounters one, it first asks whether its
86 transitive expansion contains any type function applications.  If so,
87 it expands the synonym and proceeds; if not, it simply returns the
88 unexpanded synonym.
89
90 TODO: caching the information about whether transitive synonym
91 expansions contain any type function applications would speed things
92 up a bit; right now we waste a lot of energy traversing the same types
93 multiple times.
94
95 \begin{code}
96 -- Flatten a bunch of types all at once.
97 flattenMany :: CtFlavor -> [Type] -> TcS ([Xi], [Coercion], CanonicalCts)
98 -- Coercions :: Xi ~ Type 
99 flattenMany ctxt tys 
100   = do { (xis, cos, cts_s) <- mapAndUnzip3M (flatten ctxt) tys
101        ; return (xis, cos, andCCans cts_s) }
102
103 -- Flatten a type to get rid of type function applications, returning
104 -- the new type-function-free type, and a collection of new equality
105 -- constraints.  See Note [Flattening] for more detail.
106 flatten :: CtFlavor -> TcType -> TcS (Xi, Coercion, CanonicalCts)
107 -- Postcondition: Coercion :: Xi ~ TcType 
108 flatten ctxt ty 
109   | Just ty' <- tcView ty
110   = do { (xi, co, ccs) <- flatten ctxt ty'
111         -- Preserve type synonyms if possible
112         -- We can tell if ty' is function-free by
113         -- whether there are any floated constraints
114        ; if isEmptyCCan ccs then
115              return (ty, ty, emptyCCan)  
116          else
117              return (xi, co, ccs) }
118
119 flatten _ v@(TyVarTy _)
120   = return (v, v, emptyCCan)
121
122 flatten ctxt (AppTy ty1 ty2)
123   = do { (xi1,co1,c1) <- flatten ctxt ty1
124        ; (xi2,co2,c2) <- flatten ctxt ty2
125        ; return (mkAppTy xi1 xi2, mkAppCoercion co1 co2, c1 `andCCan` c2) }
126
127 flatten ctxt (FunTy ty1 ty2)
128   = do { (xi1,co1,c1) <- flatten ctxt ty1
129        ; (xi2,co2,c2) <- flatten ctxt ty2
130        ; return (mkFunTy xi1 xi2, mkFunCoercion co1 co2, c1 `andCCan` c2) }
131
132 flatten fl (TyConApp tc tys)
133   -- For a normal type constructor or data family application, we just
134   -- recursively flatten the arguments.
135   | not (isSynFamilyTyCon tc)
136     = do { (xis,cos,ccs) <- flattenMany fl tys
137          ; return (mkTyConApp tc xis, mkTyConCoercion tc cos, ccs) }
138
139   -- Otherwise, it's a type function application, and we have to
140   -- flatten it away as well, and generate a new given equality constraint
141   -- between the application and a newly generated flattening skolem variable.
142   | otherwise 
143   = ASSERT( tyConArity tc <= length tys )       -- Type functions are saturated
144       do { (xis, cos, ccs) <- flattenMany fl tys
145          ; let (xi_args, xi_rest)  = splitAt (tyConArity tc) xis
146                (cos_args, cos_rest) = splitAt (tyConArity tc) cos 
147                  -- The type function might be *over* saturated
148                  -- in which case the remaining arguments should
149                  -- be dealt with by AppTys
150                fam_ty = mkTyConApp tc xi_args 
151                fam_co = fam_ty -- identity 
152
153          ; (ret_co, rhs_var, ct) <- 
154              if isGiven fl then
155                do { rhs_var <- newFlattenSkolemTy fam_ty
156                   ; cv <- newGivenCoVar fam_ty rhs_var fam_co
157                   ; let ct = CFunEqCan { cc_id     = cv
158                                        , cc_flavor = fl -- Given
159                                        , cc_fun    = tc 
160                                        , cc_tyargs = xi_args 
161                                        , cc_rhs    = rhs_var }
162                   ; return $ (mkCoVarCoercion cv, rhs_var, ct) }
163              else -- Derived or Wanted: make a new *unification* flatten variable
164                do { rhs_var <- newFlexiTcSTy (typeKind fam_ty)
165                   ; cv <- newCoVar fam_ty rhs_var
166                   ; let ct = CFunEqCan { cc_id = cv
167                                        , cc_flavor = mkWantedFlavor fl
168                                            -- Always Wanted, not Derived
169                                        , cc_fun = tc
170                                        , cc_tyargs = xi_args
171                                        , cc_rhs    = rhs_var }
172                   ; return $ (mkCoVarCoercion cv, rhs_var, ct) }
173
174          ; return ( foldl AppTy rhs_var xi_rest
175                   , foldl AppTy (mkSymCoercion ret_co 
176                                     `mkTransCoercion` mkTyConCoercion tc cos_args) cos_rest
177                   , ccs `extendCCans` ct) }
178
179
180 flatten ctxt (PredTy pred) 
181   = do { (pred', co, ccs) <- flattenPred ctxt pred
182        ; return (PredTy pred', co, ccs) }
183
184 flatten ctxt ty@(ForAllTy {})
185 -- We allow for-alls when, but only when, no type function
186 -- applications inside the forall involve the bound type variables
187 -- TODO: What if it is a (t1 ~ t2) => t3
188 --       Must revisit when the New Coercion API is here! 
189   = do { let (tvs, rho) = splitForAllTys ty
190        ; (rho', co, ccs) <- flatten ctxt rho
191        ; let bad_eqs  = filterBag is_bad ccs
192              is_bad c = tyVarsOfCanonical c `intersectsVarSet` tv_set
193              tv_set   = mkVarSet tvs
194        ; unless (isEmptyBag bad_eqs)
195                 (flattenForAllErrorTcS ctxt ty bad_eqs)
196        ; return (mkForAllTys tvs rho', mkForAllTys tvs co, ccs)  }
197
198 ---------------
199 flattenPred :: CtFlavor -> TcPredType -> TcS (TcPredType, Coercion, CanonicalCts)
200 flattenPred ctxt (ClassP cls tys)
201   = do { (tys', cos, ccs) <- flattenMany ctxt tys
202        ; return (ClassP cls tys', mkClassPPredCo cls cos, ccs) }
203 flattenPred ctxt (IParam nm ty)
204   = do { (ty', co, ccs) <- flatten ctxt ty
205        ; return (IParam nm ty', mkIParamPredCo nm co, ccs) }
206 -- TODO: Handling of coercions between EqPreds must be revisited once the New Coercion API is ready!
207 flattenPred ctxt (EqPred ty1 ty2)
208   = do { (ty1', co1, ccs1) <- flatten ctxt ty1
209        ; (ty2', co2, ccs2) <- flatten ctxt ty2
210        ; return (EqPred ty1' ty2', mkEqPredCo co1 co2, ccs1 `andCCan` ccs2) }
211
212 \end{code}
213
214 %************************************************************************
215 %*                                                                      *
216 %*                Canonicalising given constraints                      *
217 %*                                                                      *
218 %************************************************************************
219
220 \begin{code}
221 canWanteds :: [WantedEvVar] -> TcS WorkList
222 canWanteds = fmap unionWorkLists . mapM (\(EvVarX ev loc) -> mkCanonical (Wanted loc) ev)
223
224 canGivens :: GivenLoc -> [EvVar] -> TcS WorkList
225 canGivens loc givens = do { ccs <- mapM (mkCanonical (Given loc)) givens
226                           ; return (unionWorkLists ccs) }
227
228 mkCanonicals :: CtFlavor -> [EvVar] -> TcS WorkList
229 mkCanonicals fl vs = fmap unionWorkLists (mapM (mkCanonical fl) vs)
230
231 mkCanonicalFEV :: FlavoredEvVar -> TcS WorkList
232 mkCanonicalFEV (EvVarX ev fl) = mkCanonical fl ev
233
234 mkCanonicalFEVs :: Bag FlavoredEvVar -> TcS WorkList
235 mkCanonicalFEVs = foldrBagM canon_one emptyWorkList
236   where         -- Preserves order (shouldn't be important, but curently
237                 --                  is important for the vectoriser)
238     canon_one fev wl = do { wl' <- mkCanonicalFEV fev
239                           ; return (unionWorkList wl' wl) }
240
241 mkCanonical :: CtFlavor -> EvVar -> TcS WorkList
242 mkCanonical fl ev = case evVarPred ev of 
243                         ClassP clas tys -> canClassToWorkList fl ev clas tys 
244                         IParam ip ty    -> canIPToWorkList    fl ev ip ty 
245                         EqPred ty1 ty2  -> canEqToWorkList    fl ev ty1 ty2 
246                          
247
248 canClassToWorkList :: CtFlavor -> EvVar -> Class -> [TcType] -> TcS WorkList
249 canClassToWorkList fl v cn tys 
250   = do { (xis,cos,ccs) <- flattenMany fl tys  -- cos :: xis ~ tys
251        ; let no_flattening_happened = isEmptyCCan ccs
252              dict_co = mkTyConCoercion (classTyCon cn) cos
253        ; v_new <- if no_flattening_happened then return v
254                   else if isGiven fl        then return v
255                          -- The cos are all identities if fl=Given,
256                          -- hence nothing to do
257                   else do { v' <- newDictVar cn xis  -- D xis
258                           ; when (isWanted fl) $ setDictBind v  (EvCast v' dict_co)
259                           ; when (isGiven fl)  $ setDictBind v' (EvCast v (mkSymCoercion dict_co))
260                                  -- NB: No more setting evidence for derived now 
261                           ; return v' }
262
263        -- Add the superclasses of this one here, See Note [Adding superclasses]. 
264        -- But only if we are not simplifying the LHS of a rule. 
265        ; sctx <- getTcSContext
266        ; sc_cts <- if simplEqsOnly sctx then return emptyWorkList
267                    else newSCWorkFromFlavored v_new fl cn xis
268
269        ; return (sc_cts `unionWorkList` 
270                  workListFromEqs ccs `unionWorkList` 
271                  workListFromNonEq CDictCan { cc_id     = v_new
272                                            , cc_flavor = fl
273                                            , cc_class  = cn 
274                                            , cc_tyargs = xis }) }
275 \end{code}
276
277 Note [Adding superclasses]
278 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 
279 Since dictionaries are canonicalized only once in their lifetime, the
280 place to add their superclasses is canonicalisation (The alternative
281 would be to do it during constraint solving, but we'd have to be
282 extremely careful to not repeatedly introduced the same superclass in
283 our worklist). Here is what we do:
284
285 For Givens: 
286        We add all their superclasses as Givens. 
287
288 For Wanteds: 
289        Generally speaking we want to be able to add superclasses of 
290        wanteds for two reasons:
291
292        (1) Oportunities for improvement. Example: 
293                   class (a ~ b) => C a b 
294            Wanted constraint is: C alpha beta 
295            We'd like to simply have C alpha alpha. Similar 
296            situations arise in relation to functional dependencies. 
297            
298        (2) To have minimal constraints to quantify over: 
299            For instance, if our wanted constraint is (Eq a, Ord a) 
300            we'd only like to quantify over Ord a. 
301
302        To deal with (1) above we only add the superclasses of wanteds
303        which may lead to improvement, that is: equality superclasses or 
304        superclasses with functional dependencies. 
305
306        We deal with (2) completely independently in TcSimplify. See 
307        Note [Minimize by SuperClasses] in TcSimplify. 
308
309
310        Moreover, in all cases the extra improvement constraints are 
311        Derived. Derived constraints have an identity (for now), but 
312        we don't do anything with their evidence. For instance they 
313        are never used to rewrite other constraints. 
314
315        See also [New Wanted Superclass Work] in TcInteract. 
316
317
318 For Deriveds: 
319        We do nothing.
320
321 Here's an example that demonstrates why we chose to NOT add
322 superclasses during simplification: [Comes from ticket #4497]
323
324    class Num (RealOf t) => Normed t
325    type family RealOf x
326
327 Assume the generated wanted constraint is: 
328    RealOf e ~ e, Normed e 
329 If we were to be adding the superclasses during simplification we'd get: 
330    Num uf, Normed e, RealOf e ~ e, RealOf e ~ uf 
331 ==> 
332    e ~ uf, Num uf, Normed e, RealOf e ~ e 
333 ==> [Spontaneous solve] 
334    Num uf, Normed uf, RealOf uf ~ uf 
335
336 While looks exactly like our original constraint. If we add the superclass again we'd loop. 
337 By adding superclasses definitely only once, during canonicalisation, this situation can't 
338 happen.
339
340 \begin{code}
341
342 newSCWorkFromFlavored :: EvVar -> CtFlavor -> Class -> [Xi] -> TcS WorkList
343 -- Returns superclasses, see Note [Adding superclasses]
344 newSCWorkFromFlavored ev orig_flavor cls xis 
345   | isDerived orig_flavor 
346   = return emptyWorkList  -- Deriveds don't yield more superclasses because we will
347                           -- add them transitively in the case of wanteds. 
348
349   | isGiven orig_flavor 
350   = do { let sc_theta = immSuperClasses cls xis 
351              flavor   = orig_flavor
352        ; sc_vars <- mapM newEvVar sc_theta
353        ; _ <- zipWithM_ setEvBind sc_vars [EvSuperClass ev n | n <- [0..]]
354        ; mkCanonicals flavor sc_vars }
355
356   | isEmptyVarSet (tyVarsOfTypes xis) 
357   = return emptyWorkList -- Wanteds with no variables yield no deriveds.
358                          -- See Note [Improvement from Ground Wanteds]
359
360   | otherwise -- Wanted case, just add those SC that can lead to improvement. 
361   = do { let sc_rec_theta = transSuperClasses cls xis 
362              impr_theta   = filter is_improvement_pty sc_rec_theta 
363              Wanted wloc  = orig_flavor
364        ; der_ids <- mapM newDerivedId impr_theta
365        ; mkCanonicals (Derived wloc) der_ids }
366
367
368 is_improvement_pty :: PredType -> Bool 
369 -- Either it's an equality, or has some functional dependency
370 is_improvement_pty (EqPred {})      = True 
371 is_improvement_pty (ClassP cls _ty) = not $ null fundeps
372  where (_,fundeps,_,_,_,_) = classExtraBigSig cls
373 is_improvement_pty _ = False
374
375
376
377
378 canIPToWorkList :: CtFlavor -> EvVar -> IPName Name -> TcType -> TcS WorkList
379 -- See Note [Canonical implicit parameter constraints] to see why we don't 
380 -- immediately canonicalize (flatten) IP constraints. 
381 canIPToWorkList fl v nm ty 
382   = return $ workListFromNonEq (CIPCan { cc_id = v
383                                       , cc_flavor = fl
384                                       , cc_ip_nm = nm
385                                       , cc_ip_ty = ty })
386
387 -----------------
388 canEqToWorkList :: CtFlavor -> EvVar -> Type -> Type -> TcS WorkList
389 canEqToWorkList fl cv ty1 ty2 = do { cts <- canEq fl cv ty1 ty2 
390                          ; return $ workListFromEqs cts }
391
392 canEq :: CtFlavor -> EvVar -> Type -> Type -> TcS CanonicalCts 
393 canEq fl cv ty1 ty2 
394   | tcEqType ty1 ty2    -- Dealing with equality here avoids
395                         -- later spurious occurs checks for a~a
396   = do { when (isWanted fl) (setCoBind cv ty1)
397        ; return emptyCCan }
398
399 -- If one side is a variable, orient and flatten, 
400 -- WITHOUT expanding type synonyms, so that we tend to 
401 -- substitute a ~ Age rather than a ~ Int when @type Age = Int@
402 canEq fl cv ty1@(TyVarTy {}) ty2 
403   = do { untch <- getUntouchables 
404        ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
405 canEq fl cv ty1 ty2@(TyVarTy {}) 
406   = do { untch <- getUntouchables 
407        ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
408       -- NB: don't use VarCls directly because tv1 or tv2 may be scolems!
409
410 canEq fl cv (TyConApp fn tys) ty2 
411   | isSynFamilyTyCon fn, length tys == tyConArity fn
412   = do { untch <- getUntouchables 
413        ; canEqLeaf untch fl cv (FunCls fn tys) (classify ty2) }
414 canEq fl cv ty1 (TyConApp fn tys)
415   | isSynFamilyTyCon fn, length tys == tyConArity fn
416   = do { untch <- getUntouchables 
417        ; canEqLeaf untch fl cv (classify ty1) (FunCls fn tys) }
418
419 canEq fl cv s1 s2
420   | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe s1, 
421     Just (t2a,t2b,t2c) <- splitCoPredTy_maybe s2
422   = do { (v1,v2,v3) 
423              <- if isWanted fl then                   -- Wanted
424                     do { v1 <- newCoVar t1a t2a
425                        ; v2 <- newCoVar t1b t2b 
426                        ; v3 <- newCoVar t1c t2c 
427                        ; let res_co = mkCoPredCo (mkCoVarCoercion v1) 
428                                         (mkCoVarCoercion v2) (mkCoVarCoercion v3)
429                        ; setCoBind cv res_co
430                        ; return (v1,v2,v3) }
431                 else if isGiven fl then               -- Given 
432                          let co_orig = mkCoVarCoercion cv 
433                              coa = mkCsel1Coercion co_orig
434                              cob = mkCsel2Coercion co_orig
435                              coc = mkCselRCoercion co_orig
436                          in do { v1 <- newGivenCoVar t1a t2a coa
437                                ; v2 <- newGivenCoVar t1b t2b cob
438                                ; v3 <- newGivenCoVar t1c t2c coc 
439                                ; return (v1,v2,v3) }
440                 else                                  -- Derived 
441                     do { v1 <- newDerivedId (EqPred t1a t2a)
442                        ; v2 <- newDerivedId (EqPred t1b t2b)
443                        ; v3 <- newDerivedId (EqPred t1c t2c)
444                        ; return (v1,v2,v3) }
445        ; cc1 <- canEq fl v1 t1a t2a 
446        ; cc2 <- canEq fl v2 t1b t2b 
447        ; cc3 <- canEq fl v3 t1c t2c 
448        ; return (cc1 `andCCan` cc2 `andCCan` cc3) }
449
450
451 -- Split up an equality between function types into two equalities.
452 canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
453   = do { (argv, resv) <- 
454              if isWanted fl then 
455                  do { argv <- newCoVar s1 s2 
456                     ; resv <- newCoVar t1 t2 
457                     ; setCoBind cv $ 
458                       mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv) 
459                     ; return (argv,resv) } 
460
461              else if isGiven fl then 
462                       let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv) 
463                       in do { argv <- newGivenCoVar s1 s2 arg 
464                             ; resv <- newGivenCoVar t1 t2 res
465                             ; return (argv,resv) } 
466
467              else -- Derived 
468                  do { argv <- newDerivedId (EqPred s1 s2)
469                     ; resv <- newDerivedId (EqPred t1 t2)
470                     ; return (argv,resv) }
471
472        ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
473        ; cc2 <- canEq fl resv t1 t2
474        ; return (cc1 `andCCan` cc2) }
475
476 canEq fl cv (PredTy (IParam n1 t1)) (PredTy (IParam n2 t2))
477   | n1 == n2
478   = if isWanted fl then 
479         do { v <- newCoVar t1 t2 
480            ; setCoBind cv $ mkIParamPredCo n1 (mkCoVarCoercion cv)
481            ; canEq fl v t1 t2 } 
482     else return emptyCCan -- DV: How to decompose given IP coercions? 
483
484 canEq fl cv (PredTy (ClassP c1 tys1)) (PredTy (ClassP c2 tys2))
485   | c1 == c2
486   = if isWanted fl then 
487        do { vs <- zipWithM newCoVar tys1 tys2 
488           ; setCoBind cv $ mkClassPPredCo c1 (map mkCoVarCoercion vs) 
489           ; andCCans <$> zipWith3M (canEq fl) vs tys1 tys2
490           }
491     else return emptyCCan 
492   -- How to decompose given dictionary (and implicit parameter) coercions? 
493   -- You may think that the following is right: 
494   --    let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
495   --    in  zipWith3M newGivOrDerCoVar tys1 tys2 cos
496   -- But this assumes that the coercion is a type constructor-based 
497   -- coercion, and not a PredTy (ClassP cn cos) coercion. So we chose
498   -- to not decompose these coercions. We have to get back to this 
499   -- when we clean up the Coercion API.
500
501 canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2)
502   | isAlgTyCon tc1 && isAlgTyCon tc2
503   , tc1 == tc2
504   , length tys1 == length tys2
505   = -- Generate equalities for each of the corresponding arguments
506     do { argsv 
507              <- if isWanted fl then
508                     do { argsv <- zipWithM newCoVar tys1 tys2
509                        ; setCoBind cv $ 
510                          mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
511                        ; return argsv } 
512
513                 else if isGiven fl then 
514                     let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
515                     in zipWith3M newGivenCoVar tys1 tys2 cos
516
517                 else -- Derived 
518                     zipWithM (\t1 t2 -> newDerivedId (EqPred t1 t2)) tys1 tys2
519
520        ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }
521
522 -- See Note [Equality between type applications]
523 --     Note [Care with type applications] in TcUnify
524 canEq fl cv ty1 ty2
525   | Just (s1,t1) <- tcSplitAppTy_maybe ty1
526   , Just (s2,t2) <- tcSplitAppTy_maybe ty2
527     = do { (cv1,cv2) <- 
528              if isWanted fl 
529              then do { cv1 <- newCoVar s1 s2 
530                      ; cv2 <- newCoVar t1 t2 
531                      ; setCoBind cv $ 
532                        mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2) 
533                      ; return (cv1,cv2) } 
534
535              else if isGiven fl then 
536                     let co1 = mkLeftCoercion  $ mkCoVarCoercion cv 
537                         co2 = mkRightCoercion $ mkCoVarCoercion cv
538                     in do { cv1 <- newGivenCoVar s1 s2 co1 
539                           ; cv2 <- newGivenCoVar t1 t2 co2 
540                           ; return (cv1,cv2) } 
541              else -- Derived
542                  do { cv1 <- newDerivedId (EqPred s1 s2)
543                     ; cv2 <- newDerivedId (EqPred t1 t2)
544                     ; return (cv1,cv2) }
545
546          ; cc1 <- canEq fl cv1 s1 s2 
547          ; cc2 <- canEq fl cv2 t1 t2 
548          ; return (cc1 `andCCan` cc2) } 
549
550 canEq fl cv s1@(ForAllTy {}) s2@(ForAllTy {})
551  | tcIsForAllTy s1, tcIsForAllTy s2, 
552    Wanted {} <- fl 
553  = canEqFailure fl cv
554  | otherwise
555  = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
556       ; return emptyCCan }
557
558 -- Finally expand any type synonym applications.
559 canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
560 canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
561 canEq fl cv _ _                               = canEqFailure fl cv
562
563 canEqFailure :: CtFlavor -> EvVar -> TcS CanonicalCts
564 canEqFailure fl cv = return (singleCCan (mkFrozenError fl cv))
565 \end{code}
566
567 Note [Equality between type applications]
568 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
569 If we see an equality of the form s1 t1 ~ s2 t2 we can always split
570 it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
571 functions (type functions use the TyConApp constructor, which never
572 shows up as the LHS of an AppTy).  Other than type functions, types
573 in Haskell are always 
574
575   (1) generative: a b ~ c d implies a ~ c, since different type
576       constructors always generate distinct types
577
578   (2) injective: a b ~ a d implies b ~ d; we never generate the
579       same type from different type arguments.
580
581
582 Note [Canonical ordering for equality constraints]
583 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
584 Implemented as (<+=) below:
585
586   - Type function applications always come before anything else.  
587   - Variables always come before non-variables (other than type
588       function applications).
589
590 Note that we don't need to unfold type synonyms on the RHS to check
591 the ordering; that is, in the rules above it's OK to consider only
592 whether something is *syntactically* a type function application or
593 not.  To illustrate why this is OK, suppose we have an equality of the
594 form 'tv ~ S a b c', where S is a type synonym which expands to a
595 top-level application of the type function F, something like
596
597   type S a b c = F d e
598
599 Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
600 expansion contains type function applications the flattener will do
601 the expansion and then generate a skolem variable for the type
602 function application, so we end up with something like this:
603
604   tv ~ x
605   F d e ~ x
606
607 where x is the skolem variable.  This is one extra equation than
608 absolutely necessary (we could have gotten away with just 'F d e ~ tv'
609 if we had noticed that S expanded to a top-level type function
610 application and flipped it around in the first place) but this way
611 keeps the code simpler.
612
613 Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
614 ordering of tv ~ tv constraints.  There are several reasons why we
615 might:
616
617   (1) In order to be able to extract a substitution that doesn't
618       mention untouchable variables after we are done solving, we might
619       prefer to put touchable variables on the left. However, in and
620       of itself this isn't necessary; we can always re-orient equality
621       constraints at the end if necessary when extracting a substitution.
622
623   (2) To ensure termination we might think it necessary to put
624       variables in lexicographic order. However, this isn't actually 
625       necessary as outlined below.
626
627 While building up an inert set of canonical constraints, we maintain
628 the invariant that the equality constraints in the inert set form an
629 acyclic rewrite system when viewed as L-R rewrite rules.  Moreover,
630 the given constraints form an idempotent substitution (i.e. none of
631 the variables on the LHS occur in any of the RHS's, and type functions
632 never show up in the RHS at all), the wanted constraints also form an
633 idempotent substitution, and finally the LHS of a given constraint
634 never shows up on the RHS of a wanted constraint.  There may, however,
635 be a wanted LHS that shows up in a given RHS, since we do not rewrite
636 given constraints with wanted constraints.
637
638 Suppose we have an inert constraint set
639
640
641   tg_1 ~ xig_1         -- givens
642   tg_2 ~ xig_2
643   ...
644   tw_1 ~ xiw_1         -- wanteds
645   tw_2 ~ xiw_2
646   ...
647
648 where each t_i can be either a type variable or a type function
649 application. Now suppose we take a new canonical equality constraint,
650 t' ~ xi' (note among other things this means t' does not occur in xi')
651 and try to react it with the existing inert set.  We show by induction
652 on the number of t_i which occur in t' ~ xi' that this process will
653 terminate.
654
655 There are several ways t' ~ xi' could react with an existing constraint:
656
657 TODO: finish this proof.  The below was for the case where the entire
658 inert set is an idempotent subustitution...
659
660 (b) We could have t' = t_j for some j.  Then we obtain the new
661     equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j.  We
662     now canonicalize the new equality, which may involve decomposing it
663     into several canonical equalities, and recurse on these.  However,
664     none of the new equalities will contain t_j, so they have fewer
665     occurrences of the t_i than the original equation.
666
667 (a) We could have t_j occurring in xi' for some j, with t' /=
668     t_j. Then we substitute xi_j for t_j in xi' and continue.  However,
669     since none of the t_i occur in xi_j, we have decreased the
670     number of t_i that occur in xi', since we eliminated t_j and did not
671     introduce any new ones.
672
673 \begin{code}
674 data TypeClassifier 
675   = FskCls TcTyVar      -- ^ Flatten skolem 
676   | VarCls TcTyVar      -- ^ Non-flatten-skolem variable 
677   | FunCls TyCon [Type] -- ^ Type function, exactly saturated
678   | OtherCls TcType     -- ^ Neither of the above
679
680 unClassify :: TypeClassifier -> TcType
681 unClassify (VarCls tv)      = TyVarTy tv
682 unClassify (FskCls tv) = TyVarTy tv 
683 unClassify (FunCls fn tys)  = TyConApp fn tys
684 unClassify (OtherCls ty)    = ty
685
686 classify :: TcType -> TypeClassifier
687
688 classify (TyVarTy tv) 
689   | isTcTyVar tv, 
690     FlatSkol {} <- tcTyVarDetails tv = FskCls tv
691   | otherwise                        = VarCls tv
692 classify (TyConApp tc tys) | isSynFamilyTyCon tc
693                            , tyConArity tc == length tys
694                            = FunCls tc tys
695 classify ty                | Just ty' <- tcView ty
696                            = case classify ty' of
697                                OtherCls {} -> OtherCls ty
698                                var_or_fn   -> var_or_fn
699                            | otherwise 
700                            = OtherCls ty
701
702 -- See note [Canonical ordering for equality constraints].
703 reOrient :: CtFlavor -> TypeClassifier -> TypeClassifier -> Bool        
704 -- (t1 `reOrient` t2) responds True 
705 --   iff we should flip to (t2~t1)
706 -- We try to say False if possible, to minimise evidence generation
707 --
708 -- Postcondition: After re-orienting, first arg is not OTherCls
709 reOrient _fl (OtherCls {}) (FunCls {})   = True
710 reOrient _fl (OtherCls {}) (FskCls {})   = True
711 reOrient _fl (OtherCls {}) (VarCls {})   = True
712 reOrient _fl (OtherCls {}) (OtherCls {}) = panic "reOrient"  -- One must be Var/Fun
713
714 reOrient _fl (FunCls {})   (VarCls _tv)  = False  
715   -- But consider the following variation: isGiven fl && isMetaTyVar tv
716
717   -- See Note [No touchables as FunEq RHS] in TcSMonad
718 reOrient _fl (FunCls {}) _                = False             -- Fun/Other on rhs
719
720 reOrient _fl (VarCls {}) (FunCls {})      = True 
721
722 reOrient _fl (VarCls {}) (FskCls {})      = False
723
724 reOrient _fl (VarCls {})  (OtherCls {})   = False
725 reOrient _fl (VarCls tv1)  (VarCls tv2)  
726   | isMetaTyVar tv2 && not (isMetaTyVar tv1) = True 
727   | otherwise                                = False 
728   -- Just for efficiency, see CTyEqCan invariants 
729
730 reOrient _fl (FskCls {}) (VarCls tv2)     = isMetaTyVar tv2 
731   -- Just for efficiency, see CTyEqCan invariants
732
733 reOrient _fl (FskCls {}) (FskCls {})     = False
734 reOrient _fl (FskCls {}) (FunCls {})     = True 
735 reOrient _fl (FskCls {}) (OtherCls {})   = False 
736
737 ------------------
738 canEqLeaf :: TcsUntouchables 
739           -> CtFlavor -> CoVar 
740           -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts 
741 -- Canonicalizing "leaf" equality constraints which cannot be
742 -- decomposed further (ie one of the types is a variable or
743 -- saturated type function application).  
744
745   -- Preconditions: 
746   --    * one of the two arguments is not OtherCls
747   --    * the two types are not equal (looking through synonyms)
748 canEqLeaf _untch fl cv cls1 cls2 
749   | cls1 `re_orient` cls2
750   = do { cv' <- if isWanted fl 
751                 then do { cv' <- newCoVar s2 s1 
752                         ; setCoBind cv $ mkSymCoercion (mkCoVarCoercion cv') 
753                         ; return cv' } 
754                 else if isGiven fl then 
755                          newGivenCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv))
756                 else -- Derived
757                     newDerivedId (EqPred s2 s1)
758        ; canEqLeafOriented fl cv' cls2 s1 }
759
760   | otherwise
761   = do { traceTcS "canEqLeaf" (ppr (unClassify cls1) $$ ppr (unClassify cls2))
762        ; canEqLeafOriented fl cv cls1 s2 }
763   where
764     re_orient = reOrient fl 
765     s1 = unClassify cls1  
766     s2 = unClassify cls2  
767
768 ------------------
769 canEqLeafOriented :: CtFlavor -> CoVar 
770                   -> TypeClassifier -> TcType -> TcS CanonicalCts 
771 -- First argument is not OtherCls
772 canEqLeafOriented fl cv cls1@(FunCls fn tys1) s2         -- cv : F tys1
773   | let k1 = kindAppResult (tyConKind fn) tys1,
774     let k2 = typeKind s2, 
775     not (k1 `compatKind` k2) -- Establish the kind invariant for CFunEqCan
776   = canEqFailure fl cv
777     -- Eagerly fails, see Note [Kind errors] in TcInteract
778
779   | otherwise 
780   = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
781     do { (xis1,cos1,ccs1) <- flattenMany fl tys1 -- Flatten type function arguments
782                                                  -- cos1 :: xis1 ~ tys1
783        ; (xi2, co2, ccs2) <- flatten fl s2       -- Flatten entire RHS
784                                                  -- co2  :: xi2 ~ s2
785        ; let ccs = ccs1 `andCCan` ccs2
786              no_flattening_happened = isEmptyCCan ccs
787        ; cv_new <- if no_flattening_happened then return cv
788                    else if isGiven fl        then return cv
789                    else if isWanted fl then 
790                          do { cv' <- newCoVar (unClassify (FunCls fn xis1)) xi2
791                                  -- cv' : F xis ~ xi2
792                             ; let -- fun_co :: F xis1 ~ F tys1
793                                  fun_co = mkTyConCoercion fn cos1
794                                  -- want_co :: F tys1 ~ s2
795                                  want_co = mkSymCoercion fun_co
796                                            `mkTransCoercion` mkCoVarCoercion cv'
797                                            `mkTransCoercion` co2
798                             ; setCoBind cv  want_co
799                             ; return cv' }
800                    else -- Derived 
801                        newDerivedId (EqPred (unClassify (FunCls fn xis1)) xi2)
802
803        ; let final_cc = CFunEqCan { cc_id     = cv_new
804                                   , cc_flavor = fl
805                                   , cc_fun    = fn
806                                   , cc_tyargs = xis1 
807                                   , cc_rhs    = xi2 }
808        ; return $ ccs `extendCCans` final_cc }
809
810 -- Otherwise, we have a variable on the left, so call canEqLeafTyVarLeft
811 canEqLeafOriented fl cv (FskCls tv) s2 
812   = canEqLeafTyVarLeft fl cv tv s2 
813 canEqLeafOriented fl cv (VarCls tv) s2 
814   = canEqLeafTyVarLeft fl cv tv s2 
815 canEqLeafOriented _ cv (OtherCls ty1) ty2 
816   = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)
817
818 canEqLeafTyVarLeft :: CtFlavor -> CoVar -> TcTyVar -> TcType -> TcS CanonicalCts
819 -- Establish invariants of CTyEqCans 
820 canEqLeafTyVarLeft fl cv tv s2       -- cv : tv ~ s2
821   | not (k1 `compatKind` k2) -- Establish the kind invariant for CTyEqCan
822   = canEqFailure fl cv
823        -- Eagerly fails, see Note [Kind errors] in TcInteract
824   | otherwise
825   = do { (xi2, co, ccs2) <- flatten fl s2  -- Flatten RHS   co : xi2 ~ s2
826        ; mxi2' <- canOccursCheck fl tv xi2 -- Do an occurs check, and return a possibly
827                                            -- unfolded version of the RHS, if we had to 
828                                            -- unfold any type synonyms to get rid of tv.
829        ; case mxi2' of {
830            Nothing   -> canEqFailure fl cv ;
831            Just xi2' ->
832     do { let no_flattening_happened = isEmptyCCan ccs2
833        ; cv_new <- if no_flattening_happened then return cv
834                    else if isGiven fl        then return cv
835                    else if isWanted fl then 
836                          do { cv' <- newCoVar (mkTyVarTy tv) xi2'  -- cv' : tv ~ xi2
837                             ; setCoBind cv  (mkCoVarCoercion cv' `mkTransCoercion` co)
838                             ; return cv' }
839                    else -- Derived
840                        newDerivedId (EqPred (mkTyVarTy tv) xi2')
841
842        ; return $ ccs2 `extendCCans` CTyEqCan { cc_id     = cv_new
843                                               , cc_flavor = fl
844                                               , cc_tyvar  = tv
845                                               , cc_rhs    = xi2' } } } }
846   where
847     k1 = tyVarKind tv
848     k2 = typeKind s2
849
850 -- See Note [Type synonyms and canonicalization].
851 -- Check whether the given variable occurs in the given type.  We may
852 -- have needed to do some type synonym unfolding in order to get rid
853 -- of the variable, so we also return the unfolded version of the
854 -- type, which is guaranteed to be syntactically free of the given
855 -- type variable.  If the type is already syntactically free of the
856 -- variable, then the same type is returned.
857 --
858 -- Precondition: the two types are not equal (looking though synonyms)
859 canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS (Maybe Xi)
860 canOccursCheck _gw tv xi = return (expandAway tv xi)
861 \end{code}
862
863 @expandAway tv xi@ expands synonyms in xi just enough to get rid of
864 occurrences of tv, if that is possible; otherwise, it returns Nothing.
865 For example, suppose we have
866   type F a b = [a]
867 Then
868   expandAway b (F Int b) = Just [Int]
869 but
870   expandAway a (F a Int) = Nothing
871
872 We don't promise to do the absolute minimum amount of expanding
873 necessary, but we try not to do expansions we don't need to.  We
874 prefer doing inner expansions first.  For example,
875   type F a b = (a, Int, a, [a])
876   type G b   = Char
877 We have
878   expandAway b (F (G b)) = F Char
879 even though we could also expand F to get rid of b.
880
881 \begin{code}
882 expandAway :: TcTyVar -> Xi -> Maybe Xi
883 expandAway tv t@(TyVarTy tv') 
884   | tv == tv' = Nothing
885   | otherwise = Just t
886 expandAway tv xi
887   | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
888 expandAway tv (AppTy ty1 ty2) 
889   = do { ty1' <- expandAway tv ty1
890        ; ty2' <- expandAway tv ty2 
891        ; return (mkAppTy ty1' ty2') }
892 -- mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
893 expandAway tv (FunTy ty1 ty2)
894   = do { ty1' <- expandAway tv ty1 
895        ; ty2' <- expandAway tv ty2 
896        ; return (mkFunTy ty1' ty2') } 
897 -- mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
898 expandAway tv ty@(ForAllTy {}) 
899   = let (tvs,rho) = splitForAllTys ty
900         tvs_knds  = map tyVarKind tvs 
901     in if tv `elemVarSet` tyVarsOfTypes tvs_knds then 
902        -- Can't expand away the kinds unless we create 
903        -- fresh variables which we don't want to do at this point.
904            Nothing 
905        else do { rho' <- expandAway tv rho
906                ; return (mkForAllTys tvs rho') }
907 expandAway tv (PredTy pred) 
908   = do { pred' <- expandAwayPred tv pred  
909        ; return (PredTy pred') }
910 -- For a type constructor application, first try expanding away the
911 -- offending variable from the arguments.  If that doesn't work, next
912 -- see if the type constructor is a type synonym, and if so, expand
913 -- it and try again.
914 expandAway tv ty@(TyConApp tc tys)
915   = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)
916
917 expandAwayPred :: TcTyVar -> TcPredType -> Maybe TcPredType 
918 expandAwayPred tv (ClassP cls tys) 
919   = do { tys' <- mapM (expandAway tv) tys; return (ClassP cls tys') } 
920 expandAwayPred tv (EqPred ty1 ty2)
921   = do { ty1' <- expandAway tv ty1
922        ; ty2' <- expandAway tv ty2 
923        ; return (EqPred ty1' ty2') }
924 expandAwayPred tv (IParam nm ty) 
925   = do { ty' <- expandAway tv ty
926        ; return (IParam nm ty') }
927
928                 
929
930 \end{code}
931
932 Note [Type synonyms and canonicalization]
933 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
934
935 We treat type synonym applications as xi types, that is, they do not
936 count as type function applications.  However, we do need to be a bit
937 careful with type synonyms: like type functions they may not be
938 generative or injective.  However, unlike type functions, they are
939 parametric, so there is no problem in expanding them whenever we see
940 them, since we do not need to know anything about their arguments in
941 order to expand them; this is what justifies not having to treat them
942 as specially as type function applications.  The thing that causes
943 some subtleties is that we prefer to leave type synonym applications
944 *unexpanded* whenever possible, in order to generate better error
945 messages.
946
947 If we encounter an equality constraint with type synonym applications
948 on both sides, or a type synonym application on one side and some sort
949 of type application on the other, we simply must expand out the type
950 synonyms in order to continue decomposing the equality constraint into
951 primitive equality constraints.  For example, suppose we have
952
953   type F a = [Int]
954
955 and we encounter the equality
956
957   F a ~ [b]
958
959 In order to continue we must expand F a into [Int], giving us the
960 equality
961
962   [Int] ~ [b]
963
964 which we can then decompose into the more primitive equality
965 constraint
966
967   Int ~ b.
968
969 However, if we encounter an equality constraint with a type synonym
970 application on one side and a variable on the other side, we should
971 NOT (necessarily) expand the type synonym, since for the purpose of
972 good error messages we want to leave type synonyms unexpanded as much
973 as possible.
974
975 However, there is a subtle point with type synonyms and the occurs
976 check that takes place for equality constraints of the form tv ~ xi.
977 As an example, suppose we have
978
979   type F a = Int
980
981 and we come across the equality constraint
982
983   a ~ F a
984
985 This should not actually fail the occurs check, since expanding out
986 the type synonym results in the legitimate equality constraint a ~
987 Int.  We must actually do this expansion, because unifying a with F a
988 will lead the type checker into infinite loops later.  Put another
989 way, canonical equality constraints should never *syntactically*
990 contain the LHS variable in the RHS type.  However, we don't always
991 need to expand type synonyms when doing an occurs check; for example,
992 the constraint
993
994   a ~ F b
995
996 is obviously fine no matter what F expands to. And in this case we
997 would rather unify a with F b (rather than F b's expansion) in order
998 to get better error messages later.
999
1000 So, when doing an occurs check with a type synonym application on the
1001 RHS, we use some heuristics to find an expansion of the RHS which does
1002 not contain the variable from the LHS.  In particular, given
1003
1004   a ~ F t1 ... tn
1005
1006 we first try expanding each of the ti to types which no longer contain
1007 a.  If this turns out to be impossible, we next try expanding F
1008 itself, and so on.
1009
1010
1011 %************************************************************************
1012 %*                                                                      *
1013 %*          Functional dependencies, instantiation of equations
1014 %*                                                                      *
1015 %************************************************************************
1016
1017 When we spot an equality arising from a functional dependency,
1018 we now use that equality (a "wanted") to rewrite the work-item
1019 constraint right away.  This avoids two dangers
1020
1021  Danger 1: If we send the original constraint on down the pipeline
1022            it may react with an instance declaration, and in delicate
1023            situations (when a Given overlaps with an instance) that
1024            may produce new insoluble goals: see Trac #4952
1025
1026  Danger 2: If we don't rewrite the constraint, it may re-react
1027            with the same thing later, and produce the same equality
1028            again --> termination worries.
1029
1030 To achieve this required some refactoring of FunDeps.lhs (nicer
1031 now!).  
1032
1033 \begin{code}
1034 rewriteWithFunDeps :: [Equation]
1035                    -> [Xi] -> CtFlavor
1036                    -> TcS (Maybe ([Xi], [Coercion], WorkList))
1037 rewriteWithFunDeps eqn_pred_locs xis fl
1038  = do { fd_ev_poss <- mapM (instFunDepEqn fl) eqn_pred_locs
1039       ; let fd_ev_pos :: [(Int,FlavoredEvVar)]
1040             fd_ev_pos = concat fd_ev_poss
1041             (rewritten_xis, cos) = unzip (rewriteDictParams fd_ev_pos xis)
1042       ; fds <- mapM (\(_,fev) -> mkCanonicalFEV fev) fd_ev_pos
1043       ; let fd_work = unionWorkLists fds
1044       ; if isEmptyWorkList fd_work 
1045         then return Nothing
1046         else return (Just (rewritten_xis, cos, fd_work)) }
1047
1048 instFunDepEqn :: CtFlavor -- Precondition: Only Wanted or Derived
1049               -> Equation
1050               -> TcS [(Int, FlavoredEvVar)]
1051 -- Post: Returns the position index as well as the corresponding FunDep equality
1052 instFunDepEqn fl (FDEqn { fd_qtvs = qtvs, fd_eqs = eqs
1053                         , fd_pred1 = d1, fd_pred2 = d2 })
1054   = do { let tvs = varSetElems qtvs
1055        ; tvs' <- mapM instFlexiTcS tvs
1056        ; let subst = zipTopTvSubst tvs (mkTyVarTys tvs')
1057        ; mapM (do_one subst) eqs }
1058   where 
1059     fl' = case fl of 
1060              Given _     -> panic "mkFunDepEqns"
1061              Wanted  loc -> Wanted  (push_ctx loc)
1062              Derived loc -> Derived (push_ctx loc)
1063
1064     push_ctx loc = pushErrCtxt FunDepOrigin (False, mkEqnMsg d1 d2) loc
1065
1066     do_one subst (FDEq { fd_pos = i, fd_ty_left = ty1, fd_ty_right = ty2 })
1067        = do { let sty1 = substTy subst ty1
1068                   sty2 = substTy subst ty2
1069             ; ev <- newCoVar sty1 sty2
1070             ; return (i, mkEvVarX ev fl') }
1071
1072 rewriteDictParams :: [(Int,FlavoredEvVar)] -- A set of coercions : (pos, ty' ~ ty)
1073                   -> [Type]                -- A sequence of types: tys
1074                   -> [(Type,Coercion)]     -- Returns            : [(ty', co : ty' ~ ty)]
1075 rewriteDictParams param_eqs tys
1076   = zipWith do_one tys [0..]
1077   where
1078     do_one :: Type -> Int -> (Type,Coercion)
1079     do_one ty n = case lookup n param_eqs of
1080                     Just wev -> (get_fst_ty wev, mkCoVarCoercion (evVarOf wev))
1081                     Nothing  -> (ty,ty)         -- Identity
1082
1083     get_fst_ty wev = case evVarOfPred wev of
1084                           EqPred ty1 _ -> ty1
1085                           _ -> panic "rewriteDictParams: non equality fundep"
1086
1087 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
1088          -> TcM (TidyEnv, SDoc)
1089 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1090   = do  { zpred1 <- TcM.zonkTcPredType pred1
1091         ; zpred2 <- TcM.zonkTcPredType pred2
1092         ; let { tpred1 = tidyPred tidy_env zpred1
1093               ; tpred2 = tidyPred tidy_env zpred2 }
1094         ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
1095                           nest 2 (sep [ppr tpred1 <> comma, nest 2 from1]), 
1096                           nest 2 (sep [ppr tpred2 <> comma, nest 2 from2])]
1097         ; return (tidy_env, msg) }
1098 \end{code}