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