Minor
[ghc-hetmet.git] / compiler / typecheck / TcCanonical.lhs
1 \begin{code}
2 module TcCanonical(
3     mkCanonical, mkCanonicals, canWanteds, canGivens, canOccursCheck, 
4     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    ( when, zipWithM )
23 import MonadUtils
24 import Control.Applicative ( (<|>) )
25
26 import VarSet
27 import Bag
28
29 import Control.Monad  ( unless )
30 import TcSMonad  -- The TcS Monad 
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 NB: Note that (unlike the OutsideIn(X) draft of 7 May 2010) we are
81 actually doing the SAME thing here no matter whether we are flattening
82 a wanted or a given constraint.  In both cases we simply generate some
83 flattening skolem variables and some extra given constraints; we never
84 generate actual unification variables or non-identity coercions.
85 Hopefully this will work, although SPJ had some vague worries about
86 unification variables from wanted constraints finding their way into
87 the generated given constraints...?
88
89 Note that we prefer to leave type synonyms unexpanded when possible,
90 so when the flattener encounters one, it first asks whether its
91 transitive expansion contains any type function applications.  If so,
92 it expands the synonym and proceeds; if not, it simply returns the
93 unexpanded synonym.
94
95 TODO: caching the information about whether transitive synonym
96 expansions contain any type function applications would speed things
97 up a bit; right now we waste a lot of energy traversing the same types
98 multiple times.
99
100 \begin{code}
101 -- Flatten a bunch of types all at once.
102 flattenMany :: CtFlavor -> [Type] -> TcS ([Xi], CanonicalCts)
103 flattenMany ctxt tys 
104   = do { (xis, cts_s) <- mapAndUnzipM (flatten ctxt) tys
105        ; return (xis, andCCans cts_s) }
106
107 -- Flatten a type to get rid of type function applications, returning
108 -- the new type-function-free type, and a collection of new equality
109 -- constraints.  See Note [Flattening] for more detail.  This needs to
110 -- be in the TcS monad so we can generate new flattening skolem
111 -- variables.
112 flatten :: CtFlavor -> TcType -> TcS (Xi, CanonicalCts)
113
114 flatten ctxt ty 
115   | Just ty' <- tcView ty
116   = do { (xi, ccs) <- flatten ctxt ty'
117         -- Preserve type synonyms if possible
118         -- We can tell if t' is function-free by
119         -- whether there are any floated constraints
120        ; if isEmptyCCan ccs then
121              return (ty, emptyCCan)  
122          else
123              return (xi, ccs) }
124
125 flatten _ v@(TyVarTy _)
126   = return (v, emptyCCan)
127
128 flatten ctxt (AppTy ty1 ty2)
129   = do { (xi1,c1) <- flatten ctxt ty1
130        ; (xi2,c2) <- flatten ctxt ty2
131        ; return (mkAppTy xi1 xi2, c1 `andCCan` c2) }
132
133 flatten ctxt (FunTy ty1 ty2)
134   = do { (xi1,c1) <- flatten ctxt ty1
135        ; (xi2,c2) <- flatten ctxt ty2
136        ; return (mkFunTy xi1 xi2, c1 `andCCan` c2) }
137
138 flatten fl (TyConApp tc tys)
139   -- For a normal type constructor or data family application, we just
140   -- recursively flatten the arguments.
141   | not (isSynFamilyTyCon tc)
142     = do { (xis,ccs) <- flattenMany fl tys
143          ; return (mkTyConApp tc xis, ccs) }
144
145   -- Otherwise, it's a type function application, and we have to
146   -- flatten it away as well, and generate a new given equality constraint
147   -- between the application and a newly generated flattening skolem variable.
148   | otherwise
149     = ASSERT( tyConArity tc <= length tys )     -- Type functions are saturated
150       do { (xis, ccs) <- flattenMany fl tys
151          ; let (xi_args, xi_rest) = splitAt (tyConArity tc) xis
152                  -- The type function might be *over* saturated
153                  -- in which case the remaining arguments should
154                  -- be dealt with by AppTys
155                fam_ty = mkTyConApp tc xi_args 
156                fam_co = fam_ty -- identity 
157
158          ; xi_skol <- newFlattenSkolemTy fam_ty
159          ; cv <- newGivOrDerCoVar fam_ty xi_skol fam_co 
160
161          ; let ceq_given = CFunEqCan { cc_id     = cv 
162                                      , cc_flavor = mkGivenFlavor fl UnkSkol
163                                      , cc_fun    = tc 
164                                      , cc_tyargs = xi_args 
165                                      , cc_rhs    = xi_skol
166                                      }
167                  -- ceq_given : F xi_args ~ xi_skol
168
169          ; return ( foldl AppTy xi_skol xi_rest
170                   , ccs `extendCCans` ceq_given) }
171
172 flatten ctxt (PredTy pred) 
173   = do { (pred',ccs) <- flattenPred ctxt pred
174        ; return (PredTy pred', ccs) }
175
176 flatten ctxt ty@(ForAllTy {})
177 -- We allow for-alls when, but only when, no type function
178 -- applications inside the forall involve the bound type variables
179   = do { let (tvs, rho) = splitForAllTys ty
180        ; (rho', ccs) <- flatten ctxt rho
181        ; let bad_eqs  = filterBag is_bad ccs
182              is_bad c = tyVarsOfCanonical c `intersectsVarSet` tv_set
183              tv_set   = mkVarSet tvs
184        ; unless (isEmptyBag bad_eqs)
185                 (flattenForAllErrorTcS ctxt ty bad_eqs)
186        ; return (mkForAllTys tvs rho', ccs)  }
187
188 ---------------
189 flattenPred :: CtFlavor -> TcPredType -> TcS (TcPredType, CanonicalCts)
190 flattenPred ctxt (ClassP cls tys)
191   = do { (tys', ccs) <- flattenMany ctxt tys
192        ; return (ClassP cls tys', ccs) }
193 flattenPred ctxt (IParam nm ty)
194   = do { (ty', ccs) <- flatten ctxt ty
195        ; return (IParam nm ty', ccs) }
196 flattenPred ctxt (EqPred ty1 ty2)
197   = do { (ty1', ccs1) <- flatten ctxt ty1
198        ; (ty2', ccs2) <- flatten ctxt ty2
199        ; return (EqPred ty1' ty2', ccs1 `andCCan` ccs2) }
200 \end{code}
201
202 %************************************************************************
203 %*                                                                      *
204 %*                Canonicalising given constraints                      *
205 %*                                                                      *
206 %************************************************************************
207
208 \begin{code}
209 canWanteds :: [WantedEvVar] -> TcS CanonicalCts 
210 canWanteds = fmap andCCans . mapM (\(WantedEvVar ev loc) -> mkCanonical (Wanted loc) ev)
211
212 canGivens :: GivenLoc -> [EvVar] -> TcS CanonicalCts
213 canGivens loc givens = do { ccs <- mapM (mkCanonical (Given loc)) givens
214                           ; return (andCCans ccs) }
215
216 mkCanonicals :: CtFlavor -> [EvVar] -> TcS CanonicalCts 
217 mkCanonicals fl vs = fmap andCCans (mapM (mkCanonical fl) vs)
218
219 mkCanonical :: CtFlavor -> EvVar -> TcS CanonicalCts 
220 mkCanonical fl ev = case evVarPred ev of 
221                         ClassP clas tys -> canClass fl ev clas tys 
222                         IParam ip ty    -> canIP    fl ev ip ty
223                         EqPred ty1 ty2  -> canEq    fl ev ty1 ty2 
224                          
225
226 canClass :: CtFlavor -> EvVar -> Class -> [TcType] -> TcS CanonicalCts 
227 canClass fl v cn tys 
228   = do { (xis,ccs) <- flattenMany fl tys 
229        ; return $ ccs `extendCCans` CDictCan { cc_id = v 
230                                              , cc_flavor = fl 
231                                              , cc_class = cn 
232                                              , cc_tyargs = xis } }
233 canIP :: CtFlavor -> EvVar -> IPName Name -> TcType -> TcS CanonicalCts 
234 canIP fl v nm ty 
235   = return $ singleCCan $ CIPCan { cc_id = v
236                                  , cc_flavor = fl
237                                  , cc_ip_nm = nm
238                                  , cc_ip_ty = ty } 
239
240
241 -----------------
242 canEq :: CtFlavor -> EvVar -> Type -> Type -> TcS CanonicalCts 
243 canEq fl cv ty1 ty2 
244   | tcEqType ty1 ty2    -- Dealing with equality here avoids
245                         -- later spurious occurs checks for a~a
246   = do { when (isWanted fl) (setWantedCoBind cv ty1)
247        ; return emptyCCan }
248
249 -- If one side is a variable, orient and flatten, 
250 -- WITHOUT expanding type synonyms, so that we tend to 
251 -- substitute a~Age rather than a~Int when type Age=Ing
252 canEq fl cv (TyVarTy tv1) ty2 = canEqLeaf fl cv (VarCls tv1) (classify ty2)
253 canEq fl cv ty1 (TyVarTy tv2) = canEqLeaf fl cv (classify ty1) (VarCls tv2)
254
255 canEq fl cv (TyConApp fn tys) ty2 
256   | isSynFamilyTyCon fn, length tys == tyConArity fn
257   = canEqLeaf fl cv (FunCls fn tys) (classify ty2)
258 canEq fl cv ty1 (TyConApp fn tys)
259   | isSynFamilyTyCon fn, length tys == tyConArity fn
260   = canEqLeaf fl cv (classify ty1) (FunCls fn tys) 
261
262 canEq fl cv s1 s2
263   | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe s1, 
264     Just (t2a,t2b,t2c) <- splitCoPredTy_maybe s2
265   = do { (v1,v2,v3) <- if isWanted fl then 
266                          do { v1 <- newWantedCoVar t1a t2a
267                             ; v2 <- newWantedCoVar t1b t2b 
268                             ; v3 <- newWantedCoVar t1c t2c 
269                             ; let res_co = mkCoPredCo (mkCoVarCoercion v1) 
270                                                       (mkCoVarCoercion v2) (mkCoVarCoercion v3)
271                             ; setWantedCoBind cv res_co
272                             ; return (v1,v2,v3) }
273                        else let co_orig = mkCoVarCoercion cv 
274                                 coa = mkCsel1Coercion co_orig
275                                 cob = mkCsel2Coercion co_orig
276                                 coc = mkCselRCoercion co_orig
277                             in do { v1 <- newGivOrDerCoVar t1a t2a coa
278                                   ; v2 <- newGivOrDerCoVar t1b t2b cob
279                                   ; v3 <- newGivOrDerCoVar t1c t2c coc 
280                                   ; return (v1,v2,v3) }
281        ; cc1 <- canEq fl v1 t1a t2a 
282        ; cc2 <- canEq fl v2 t1b t2b 
283        ; cc3 <- canEq fl v3 t1c t2c 
284        ; return (cc1 `andCCan` cc2 `andCCan` cc3) }
285
286
287 -- Split up an equality between function types into two equalities.
288 canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
289   = do { (argv, resv) <- 
290              if isWanted fl then 
291                  do { argv <- newWantedCoVar s1 s2 
292                     ; resv <- newWantedCoVar t1 t2 
293                     ; setWantedCoBind cv $ 
294                       mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv) 
295                     ; return (argv,resv) } 
296              else let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv) 
297                   in do { argv <- newGivOrDerCoVar s1 s2 arg 
298                         ; resv <- newGivOrDerCoVar t1 t2 res
299                         ; return (argv,resv) } 
300        ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
301        ; cc2 <- canEq fl resv t1 t2
302        ; return (cc1 `andCCan` cc2) }
303
304 canEq fl cv (PredTy p1) (PredTy p2) = canEqPred p1 p2 
305   where canEqPred (IParam n1 t1) (IParam n2 t2) 
306           | n1 == n2 
307           = if isWanted fl then 
308                 do { v <- newWantedCoVar t1 t2 
309                    ; setWantedCoBind cv $ mkIParamPredCo n1 (mkCoVarCoercion cv)
310                    ; canEq fl v t1 t2 } 
311             else return emptyCCan -- DV: How to decompose given IP coercions? 
312
313         canEqPred (ClassP c1 tys1) (ClassP c2 tys2) 
314           | c1 == c2 
315           = if isWanted fl then 
316                do { vs <- zipWithM newWantedCoVar tys1 tys2 
317                   ; setWantedCoBind cv $ mkClassPPredCo c1 (map mkCoVarCoercion vs) 
318                   ; andCCans <$> zipWith3M (canEq fl) vs tys1 tys2
319                   }
320             else return emptyCCan 
321           -- How to decompose given dictionary (and implicit parameter) coercions? 
322           -- You may think that the following is right: 
323           --    let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
324           --    in  zipWith3M newGivOrDerCoVar tys1 tys2 cos
325           -- But this assumes that the coercion is a type constructor-based 
326           -- coercion, and not a PredTy (ClassP cn cos) coercion. So we chose
327           -- to not decompose these coercions. We have to get back to this 
328           -- when we clean up the Coercion API.
329
330         canEqPred p1 p2 = misMatchErrorTcS fl (mkPredTy p1) (mkPredTy p2) 
331
332
333 canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
334   | isAlgTyCon tc1 && isAlgTyCon tc2
335   , tc1 == tc2
336   , length tys1 == length tys2
337   = -- Generate equalities for each of the corresponding arguments
338     do { argsv <- if isWanted fl then
339                     do { argsv <- zipWithM newWantedCoVar tys1 tys2
340                             ; setWantedCoBind cv $ mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
341                             ; return argsv } 
342                   else 
343                     let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
344                     in zipWith3M newGivOrDerCoVar tys1 tys2 cos
345        ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }
346
347 -- See Note [Equality between type applications]
348 --     Note [Care with type applications] in TcUnify
349 canEq fl cv ty1 ty2
350   | Just (s1,t1) <- tcSplitAppTy_maybe ty1
351   , Just (s2,t2) <- tcSplitAppTy_maybe ty2
352     = do { (cv1,cv2) <- 
353              if isWanted fl 
354              then do { cv1 <- newWantedCoVar s1 s2 
355                      ; cv2 <- newWantedCoVar t1 t2 
356                      ; setWantedCoBind cv $ 
357                        mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2) 
358                      ; return (cv1,cv2) } 
359              else let co1 = mkLeftCoercion  $ mkCoVarCoercion cv 
360                       co2 = mkRightCoercion $ mkCoVarCoercion cv
361                   in do { cv1 <- newGivOrDerCoVar s1 s2 co1 
362                         ; cv2 <- newGivOrDerCoVar t1 t2 co2 
363                         ; return (cv1,cv2) } 
364          ; cc1 <- canEq fl cv1 s1 s2 
365          ; cc2 <- canEq fl cv2 t1 t2 
366          ; return (cc1 `andCCan` cc2) } 
367
368 canEq fl _ s1@(ForAllTy {}) s2@(ForAllTy {})  
369  | tcIsForAllTy s1, tcIsForAllTy s2, 
370    Wanted {} <- fl 
371  = misMatchErrorTcS fl s1 s2 
372  | otherwise 
373  = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
374       ; return emptyCCan }
375
376 -- Finally expand any type synonym applications.
377 canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
378 canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
379 canEq fl _ ty1 ty2 
380   = misMatchErrorTcS fl ty1 ty2
381
382
383 \end{code}
384
385 Note [Equality between type applications]
386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387 If we see an equality of the form s1 t1 ~ s2 t2 we can always split
388 it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
389 functions (type functions use the TyConApp constructor, which never
390 shows up as the LHS of an AppTy).  Other than type functions, types
391 in Haskell are always 
392
393   (1) generative: a b ~ c d implies a ~ c, since different type
394       constructors always generate distinct types
395
396   (2) injective: a b ~ a d implies b ~ d; we never generate the
397       same type from different type arguments.
398
399
400 Note [Canonical ordering for equality constraints]
401 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
402 Implemented as (<+=) below:
403
404   - Type function applications always come before anything else.  
405   - Variables always come before non-variables (other than type
406       function applications).
407
408 Note that we don't need to unfold type synonyms on the RHS to check
409 the ordering; that is, in the rules above it's OK to consider only
410 whether something is *syntactically* a type function application or
411 not.  To illustrate why this is OK, suppose we have an equality of the
412 form 'tv ~ S a b c', where S is a type synonym which expands to a
413 top-level application of the type function F, something like
414
415   type S a b c = F d e
416
417 Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
418 expansion contains type function applications the flattener will do
419 the expansion and then generate a skolem variable for the type
420 function application, so we end up with something like this:
421
422   tv ~ x
423   F d e ~ x
424
425 where x is the skolem variable.  This is one extra equation than
426 absolutely necessary (we could have gotten away with just 'F d e ~ tv'
427 if we had noticed that S expanded to a top-level type function
428 application and flipped it around in the first place) but this way
429 keeps the code simpler.
430
431 Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
432 ordering of tv ~ tv constraints.  There are several reasons why we
433 might:
434
435   (1) In order to be able to extract a substitution that doesn't
436       mention untouchable variables after we are done solving, we might
437       prefer to put touchable variables on the left. However, in and
438       of itself this isn't necessary; we can always re-orient equality
439       constraints at the end if necessary when extracting a substitution.
440
441   (2) To ensure termination we might think it necessary to put
442       variables in lexicographic order. However, this isn't actually 
443       necessary as outlined below.
444
445 While building up an inert set of canonical constraints, we maintain
446 the invariant that the equality constraints in the inert set form an
447 acyclic rewrite system when viewed as L-R rewrite rules.  Moreover,
448 the given constraints form an idempotent substitution (i.e. none of
449 the variables on the LHS occur in any of the RHS's, and type functions
450 never show up in the RHS at all), the wanted constraints also form an
451 idempotent substitution, and finally the LHS of a given constraint
452 never shows up on the RHS of a wanted constraint.  There may, however,
453 be a wanted LHS that shows up in a given RHS, since we do not rewrite
454 given constraints with wanted constraints.
455
456 Suppose we have an inert constraint set
457
458
459   tg_1 ~ xig_1         -- givens
460   tg_2 ~ xig_2
461   ...
462   tw_1 ~ xiw_1         -- wanteds
463   tw_2 ~ xiw_2
464   ...
465
466 where each t_i can be either a type variable or a type function
467 application. Now suppose we take a new canonical equality constraint,
468 t' ~ xi' (note among other things this means t' does not occur in xi')
469 and try to react it with the existing inert set.  We show by induction
470 on the number of t_i which occur in t' ~ xi' that this process will
471 terminate.
472
473 There are several ways t' ~ xi' could react with an existing constraint:
474
475 TODO: finish this proof.  The below was for the case where the entire
476 inert set is an idempotent subustitution...
477
478 (b) We could have t' = t_j for some j.  Then we obtain the new
479     equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j.  We
480     now canonicalize the new equality, which may involve decomposing it
481     into several canonical equalities, and recurse on these.  However,
482     none of the new equalities will contain t_j, so they have fewer
483     occurrences of the t_i than the original equation.
484
485 (a) We could have t_j occurring in xi' for some j, with t' /=
486     t_j. Then we substitute xi_j for t_j in xi' and continue.  However,
487     since none of the t_i occur in xi_j, we have decreased the
488     number of t_i that occur in xi', since we eliminated t_j and did not
489     introduce any new ones.
490
491 \begin{code}
492 data TypeClassifier 
493   = VarCls TcTyVar      -- Type variable
494   | FunCls TyCon [Type] -- Type function, exactly saturated
495   | OtherCls TcType     -- Neither of the above
496
497 unClassify :: TypeClassifier -> TcType
498 unClassify (VarCls tv)     = TyVarTy tv
499 unClassify (FunCls fn tys) = TyConApp fn tys
500 unClassify (OtherCls ty)   = ty
501
502 classify :: TcType -> TypeClassifier
503 classify (TyVarTy tv)      = VarCls tv
504 classify (TyConApp tc tys) | isSynFamilyTyCon tc
505                            , tyConArity tc == length tys
506                            = FunCls tc tys
507 classify ty                | Just ty' <- tcView ty
508                            = case classify ty' of
509                                OtherCls {} -> OtherCls ty
510                                var_or_fn   -> var_or_fn
511                            | otherwise 
512                            = OtherCls ty
513
514 -- See note [Canonical ordering for equality constraints].
515 reOrient :: TypeClassifier -> TypeClassifier -> Bool    
516 -- (t1 `reOrient` t2) responds True 
517 --   iff we should flip to (t2~t1)
518 -- We try to say False if possible, to minimise evidence generation
519 --
520 -- Postcondition: After re-orienting, first arg is not OTherCls
521 reOrient (OtherCls {}) (FunCls {})   = True
522 reOrient (OtherCls {}) (VarCls {})   = True
523 reOrient (OtherCls {}) (OtherCls {}) = panic "reOrient"  -- One must be Var/Fun
524
525 reOrient (FunCls {})   (VarCls tv2)   = isMetaTyVar tv2
526   -- See Note [No touchables as FunEq RHS] in TcSMonad
527   -- For convenience we enforce the stronger invariant that no 
528   -- meta type variable is the RHS of a function equality
529 reOrient (FunCls {}) _                = False   -- Fun/Other on rhs
530
531 reOrient (VarCls tv1) (FunCls {})   = not (isMetaTyVar tv1)
532 reOrient (VarCls {})  (OtherCls {}) = False
533 reOrient (VarCls {})  (VarCls {})   = False 
534
535 {- 
536 -- Variables-variables are oriented according to their kind 
537 -- so that the following property has the best chance of
538 -- holding:   tv ~ xi
539 --   * If tv is a MetaTyVar, then typeKind xi <: typeKind tv 
540 --              a skolem,    then typeKind xi =  typeKind tv 
541
542   | k1 `eqKind` k2 = False
543   | otherwise      = k1 `isSubKind` k2 
544   where
545     k1 = tyVarKind tv1
546     k2 = tyVarKind tv2
547 -} 
548
549 ------------------
550 canEqLeaf :: CtFlavor -> CoVar 
551           -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts 
552 -- Canonicalizing "leaf" equality constraints which cannot be
553 -- decomposed further (ie one of the types is a variable or
554 -- saturated type function application).  
555
556   -- Preconditions: 
557   --    * one of the two arguments is not OtherCls
558   --    * the two types are not equal (looking through synonyms)
559 canEqLeaf fl cv cls1 cls2 
560   | cls1 `reOrient` cls2 
561   = do { cv' <- if isWanted fl 
562                 then do { cv' <- newWantedCoVar s2 s1 
563                         ; setWantedCoBind cv $ mkSymCoercion (mkCoVarCoercion cv') 
564                         ; return cv' } 
565                 else newGivOrDerCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv)) 
566        ; canEqLeafOriented fl cv' cls2 s1 }
567
568   | otherwise
569   = canEqLeafOriented fl cv cls1 s2
570   where
571     s1 = unClassify cls1  
572     s2 = unClassify cls2  
573
574 ------------------
575 canEqLeafOriented :: CtFlavor -> CoVar 
576                   -> TypeClassifier -> TcType -> TcS CanonicalCts 
577 -- First argument is not OtherCls
578 canEqLeafOriented fl cv cls1@(FunCls fn tys) s2 
579   | let k1 = kindAppResult (tyConKind fn) tys, 
580     let k2 = typeKind s2, 
581     isGiven fl && not (k1 `eqKind` k2) -- Establish the kind invariant for CFunEqCan
582   = do { kindErrorTcS fl (unClassify cls1) s2
583        ; return emptyCCan }
584   | otherwise 
585   = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
586     do { (xis1,ccs1) <- flattenMany fl tys -- flatten type function arguments
587        ; (xi2,ccs2)  <- flatten fl s2      -- flatten entire RHS
588        ; let final_cc = CFunEqCan { cc_id     = cv 
589                                   , cc_flavor = fl 
590                                   , cc_fun    = fn
591                                   , cc_tyargs = xis1 
592                                   , cc_rhs    = xi2 }
593        ; return $ ccs1 `andCCan` ccs2 `extendCCans` final_cc }
594
595 -- Otherwise, we have a variable on the left, so we flatten the RHS
596 -- and then do an occurs check.
597 canEqLeafOriented fl cv (VarCls tv) s2 
598   | isGiven fl && not (k1 `eqKind` k2) -- Establish the kind invariant for CTyEqCan
599   = do { kindErrorTcS fl (mkTyVarTy tv) s2
600        ; return emptyCCan }
601
602   | otherwise
603   = do { (xi2,ccs2) <- flatten fl s2      -- flatten RHS
604        ; xi2' <- canOccursCheck fl tv xi2 -- do an occurs check, and return a possibly 
605                                           -- unfolded version of the RHS, if we had to 
606                                           -- unfold any type synonyms to get rid of tv.
607        ; let final_cc = CTyEqCan { cc_id     = cv 
608                                  , cc_flavor = fl
609                                  , cc_tyvar  = tv
610                                  , cc_rhs    = xi2'
611                                  } 
612        ; return $ ccs2 `extendCCans` final_cc }
613   where
614     k1 = tyVarKind tv
615     k2 = typeKind s2
616
617 canEqLeafOriented _ cv (OtherCls ty1) ty2 
618   = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)
619
620 -- See Note [Type synonyms and canonicalization].
621 -- Check whether the given variable occurs in the given type.  We may
622 -- have needed to do some type synonym unfolding in order to get rid
623 -- of the variable, so we also return the unfolded version of the
624 -- type, which is guaranteed to be syntactically free of the given
625 -- type variable.  If the type is already syntactically free of the
626 -- variable, then the same type is returned.
627 --
628 -- Precondition: the two types are not equal (looking though synonyms)
629 canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS Xi
630 canOccursCheck gw tv xi 
631   | Just xi' <- expandAway tv xi = return xi'
632   | otherwise = occursCheckErrorTcS gw tv xi
633 \end{code}
634
635 @expandAway tv xi@ expands synonyms in xi just enough to get rid of
636 occurrences of tv, if that is possible; otherwise, it returns Nothing.
637 For example, suppose we have
638   type F a b = [a]
639 Then
640   expandAway b (F Int b) = Just [Int]
641 but
642   expandAway a (F a Int) = Nothing
643
644 We don't promise to do the absolute minimum amount of expanding
645 necessary, but we try not to do expansions we don't need to.  We
646 prefer doing inner expansions first.  For example,
647   type F a b = (a, Int, a, [a])
648   type G b   = Char
649 We have
650   expandAway b (F (G b)) = F Char
651 even though we could also expand F to get rid of b.
652
653 \begin{code}
654 expandAway :: TcTyVar -> Xi -> Maybe Xi
655 expandAway tv t@(TyVarTy tv') 
656   | tv == tv' = Nothing
657   | otherwise = Just t
658 expandAway tv xi
659   | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
660 expandAway tv (AppTy ty1 ty2) 
661   = mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
662 expandAway tv (FunTy ty1 ty2)
663   = mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
664 expandAway _ (ForAllTy {}) = error "blorg"  -- TODO
665 expandAway _ (PredTy {})   = error "flerg"  -- TODO
666
667 -- For a type constructor application, first try expanding away the
668 -- offending variable from the arguments.  If that doesn't work, next
669 -- see if the type constructor is a type synonym, and if so, expand
670 -- it and try again.
671 expandAway tv ty@(TyConApp tc tys)
672     = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)
673 \end{code}
674
675 Note [Type synonyms and canonicalization]
676 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
677
678 We treat type synonym applications as xi types, that is, they do not
679 count as type function applications.  However, we do need to be a bit
680 careful with type synonyms: like type functions they may not be
681 generative or injective.  However, unlike type functions, they are
682 parametric, so there is no problem in expanding them whenever we see
683 them, since we do not need to know anything about their arguments in
684 order to expand them; this is what justifies not having to treat them
685 as specially as type function applications.  The thing that causes
686 some subtleties is that we prefer to leave type synonym applications
687 *unexpanded* whenever possible, in order to generate better error
688 messages.
689
690 If we encounter an equality constraint with type synonym applications
691 on both sides, or a type synonym application on one side and some sort
692 of type application on the other, we simply must expand out the type
693 synonyms in order to continue decomposing the equality constraint into
694 primitive equality constraints.  For example, suppose we have
695
696   type F a = [Int]
697
698 and we encounter the equality
699
700   F a ~ [b]
701
702 In order to continue we must expand F a into [Int], giving us the
703 equality
704
705   [Int] ~ [b]
706
707 which we can then decompose into the more primitive equality
708 constraint
709
710   Int ~ b.
711
712 However, if we encounter an equality constraint with a type synonym
713 application on one side and a variable on the other side, we should
714 NOT (necessarily) expand the type synonym, since for the purpose of
715 good error messages we want to leave type synonyms unexpanded as much
716 as possible.
717
718 However, there is a subtle point with type synonyms and the occurs
719 check that takes place for equality constraints of the form tv ~ xi.
720 As an example, suppose we have
721
722   type F a = Int
723
724 and we come across the equality constraint
725
726   a ~ F a
727
728 This should not actually fail the occurs check, since expanding out
729 the type synonym results in the legitimate equality constraint a ~
730 Int.  We must actually do this expansion, because unifying a with F a
731 will lead the type checker into infinite loops later.  Put another
732 way, canonical equality constraints should never *syntactically*
733 contain the LHS variable in the RHS type.  However, we don't always
734 need to expand type synonyms when doing an occurs check; for example,
735 the constraint
736
737   a ~ F b
738
739 is obviously fine no matter what F expands to. And in this case we
740 would rather unify a with F b (rather than F b's expansion) in order
741 to get better error messages later.
742
743 So, when doing an occurs check with a type synonym application on the
744 RHS, we use some heuristics to find an expansion of the RHS which does
745 not contain the variable from the LHS.  In particular, given
746
747   a ~ F t1 ... tn
748
749 we first try expanding each of the ti to types which no longer contain
750 a.  If this turns out to be impossible, we next try expanding F
751 itself, and so on.
752
753
754