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