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