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