Typechecker performance fixes and flatten skolem bugfixing
[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 -- Split up an equality between function types into two equalities.
263 canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
264   = do { (argv, resv) <- 
265              if isWanted fl then 
266                  do { argv <- newWantedCoVar s1 s2 
267                     ; resv <- newWantedCoVar t1 t2 
268                     ; setWantedCoBind cv $ 
269                       mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv) 
270                     ; return (argv,resv) } 
271              else let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv) 
272                   in do { argv <- newGivOrDerCoVar s1 s2 arg 
273                         ; resv <- newGivOrDerCoVar t1 t2 res
274                         ; return (argv,resv) } 
275        ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
276        ; cc2 <- canEq fl resv t1 t2
277        ; return (cc1 `andCCan` cc2) }
278
279
280 canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
281   | isAlgTyCon tc1 && isAlgTyCon tc2
282   , tc1 == tc2
283   , length tys1 == length tys2
284   = -- Generate equalities for each of the corresponding arguments
285     do { argsv <- if isWanted fl then
286                     do { argsv <- zipWithM newWantedCoVar tys1 tys2
287                             ; setWantedCoBind cv $ mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
288                             ; return argsv } 
289                   else 
290                     let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
291                     in zipWith3M newGivOrDerCoVar tys1 tys2 cos
292        ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }
293
294 -- See Note [Equality between type applications]
295 --     Note [Care with type applications] in TcUnify
296 canEq fl cv ty1 ty2
297   | Just (s1,t1) <- tcSplitAppTy_maybe ty1
298   , Just (s2,t2) <- tcSplitAppTy_maybe ty2
299     = do { (cv1,cv2) <- 
300              if isWanted fl 
301              then do { cv1 <- newWantedCoVar s1 s2 
302                      ; cv2 <- newWantedCoVar t1 t2 
303                      ; setWantedCoBind cv $ 
304                        mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2) 
305                      ; return (cv1,cv2) } 
306              else let co1 = mkLeftCoercion  $ mkCoVarCoercion cv 
307                       co2 = mkRightCoercion $ mkCoVarCoercion cv
308                   in do { cv1 <- newGivOrDerCoVar s1 s2 co1 
309                         ; cv2 <- newGivOrDerCoVar t1 t2 co2 
310                         ; return (cv1,cv2) } 
311          ; cc1 <- canEq fl cv1 s1 s2 
312          ; cc2 <- canEq fl cv2 t1 t2 
313          ; return (cc1 `andCCan` cc2) } 
314
315 canEq fl _ s1@(ForAllTy {}) s2@(ForAllTy {}) 
316  | Wanted {} <- fl 
317  = misMatchErrorTcS fl s1 s2
318  | otherwise 
319  = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
320       ; return emptyCCan }
321
322 -- Finally expand any type synonym applications.
323 canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
324 canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
325
326 canEq fl _ ty1 ty2 
327   = misMatchErrorTcS fl ty1 ty2
328 \end{code}
329
330 Note [Equality between type applications]
331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
332 If we see an equality of the form s1 t1 ~ s2 t2 we can always split
333 it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
334 functions (type functions use the TyConApp constructor, which never
335 shows up as the LHS of an AppTy).  Other than type functions, types
336 in Haskell are always 
337
338   (1) generative: a b ~ c d implies a ~ c, since different type
339       constructors always generate distinct types
340
341   (2) injective: a b ~ a d implies b ~ d; we never generate the
342       same type from different type arguments.
343
344
345 Note [Kinding] 
346 ~~~~~~~~~~~~~~
347 The canonicalizer assumes that it's provided with well-kinded equalities
348 as wanted or given, that is LHS kind and the RHS kind agree, modulo subkinding.
349
350 Both canonicalization and interaction solving must preserve this invariant. 
351 DV: TODO TODO: Check! 
352
353 Note [Canonical ordering for equality constraints]
354 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
355 Implemented as (<+=) below:
356
357   - Type function applications always come before anything else.  
358   - Variables always come before non-variables (other than type
359       function applications).
360
361 Note that we don't need to unfold type synonyms on the RHS to check
362 the ordering; that is, in the rules above it's OK to consider only
363 whether something is *syntactically* a type function application or
364 not.  To illustrate why this is OK, suppose we have an equality of the
365 form 'tv ~ S a b c', where S is a type synonym which expands to a
366 top-level application of the type function F, something like
367
368   type S a b c = F d e
369
370 Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
371 expansion contains type function applications the flattener will do
372 the expansion and then generate a skolem variable for the type
373 function application, so we end up with something like this:
374
375   tv ~ x
376   F d e ~ x
377
378 where x is the skolem variable.  This is one extra equation than
379 absolutely necessary (we could have gotten away with just 'F d e ~ tv'
380 if we had noticed that S expanded to a top-level type function
381 application and flipped it around in the first place) but this way
382 keeps the code simpler.
383
384 Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
385 ordering of tv ~ tv constraints.  There are several reasons why we
386 might:
387
388   (1) In order to be able to extract a substitution that doesn't
389       mention untouchable variables after we are done solving, we might
390       prefer to put touchable variables on the left. However, in and
391       of itself this isn't necessary; we can always re-orient equality
392       constraints at the end if necessary when extracting a substitution.
393
394   (2) To ensure termination we might think it necessary to put
395       variables in lexicographic order. However, this isn't actually 
396       necessary as outlined below.
397
398 While building up an inert set of canonical constraints, we maintain
399 the invariant that the equality constraints in the inert set form an
400 acyclic rewrite system when viewed as L-R rewrite rules.  Moreover,
401 the given constraints form an idempotent substitution (i.e. none of
402 the variables on the LHS occur in any of the RHS's, and type functions
403 never show up in the RHS at all), the wanted constraints also form an
404 idempotent substitution, and finally the LHS of a given constraint
405 never shows up on the RHS of a wanted constraint.  There may, however,
406 be a wanted LHS that shows up in a given RHS, since we do not rewrite
407 given constraints with wanted constraints.
408
409 Suppose we have an inert constraint set
410
411
412   tg_1 ~ xig_1         -- givens
413   tg_2 ~ xig_2
414   ...
415   tw_1 ~ xiw_1         -- wanteds
416   tw_2 ~ xiw_2
417   ...
418
419 where each t_i can be either a type variable or a type function
420 application. Now suppose we take a new canonical equality constraint,
421 t' ~ xi' (note among other things this means t' does not occur in xi')
422 and try to react it with the existing inert set.  We show by induction
423 on the number of t_i which occur in t' ~ xi' that this process will
424 terminate.
425
426 There are several ways t' ~ xi' could react with an existing constraint:
427
428 TODO: finish this proof.  The below was for the case where the entire
429 inert set is an idempotent subustitution...
430
431 (b) We could have t' = t_j for some j.  Then we obtain the new
432     equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j.  We
433     now canonicalize the new equality, which may involve decomposing it
434     into several canonical equalities, and recurse on these.  However,
435     none of the new equalities will contain t_j, so they have fewer
436     occurrences of the t_i than the original equation.
437
438 (a) We could have t_j occurring in xi' for some j, with t' /=
439     t_j. Then we substitute xi_j for t_j in xi' and continue.  However,
440     since none of the t_i occur in xi_j, we have decreased the
441     number of t_i that occur in xi', since we eliminated t_j and did not
442     introduce any new ones.
443
444 \begin{code}
445 data TypeClassifier 
446   = VarCls TcTyVar      -- Type variable
447   | FunCls TyCon [Type] -- Type function, exactly saturated
448   | OtherCls TcType     -- Neither of the above
449
450 unClassify :: TypeClassifier -> TcType
451 unClassify (VarCls tv)     = TyVarTy tv
452 unClassify (FunCls fn tys) = TyConApp fn tys
453 unClassify (OtherCls ty)   = ty
454
455 classify :: TcType -> TypeClassifier
456 classify (TyVarTy tv)      = VarCls tv
457 classify (TyConApp tc tys) | isSynFamilyTyCon tc
458                            , tyConArity tc == length tys
459                            = FunCls tc tys
460 classify ty                | Just ty' <- tcView ty
461                            = case classify ty' of
462                                OtherCls {} -> OtherCls ty
463                                var_or_fn   -> var_or_fn
464                            | otherwise 
465                            = OtherCls ty
466
467 -- See note [Canonical ordering for equality constraints].
468 reOrient :: TypeClassifier -> TypeClassifier -> Bool    
469 -- (t1 `reOrient` t2) responds True 
470 --   iff we should flip to (t2~t1)
471 -- We try to say False if possible, to minimise evidence generation
472 --
473 -- Postcondition: After re-orienting, first arg is not OTherCls
474 reOrient (OtherCls {}) (FunCls {})   = True
475 reOrient (OtherCls {}) (VarCls {})   = True
476 reOrient (OtherCls {}) (OtherCls {}) = panic "reOrient"  -- One must be Var/Fun
477
478 reOrient (FunCls {})   (VarCls tv2)   = isMetaTyVar tv2
479   -- See Note [No touchables as FunEq RHS] in TcSMonad
480   -- For convenience we enforce the stronger invariant that no 
481   -- meta type variable is the RHS of a function equality
482 reOrient (FunCls {}) _                = False   -- Fun/Other on rhs
483
484
485 reOrient (VarCls tv1) (FunCls {}) = not (isMetaTyVar tv1)
486 reOrient (VarCls {})  (OtherCls {}) = False
487
488 -- Variables-variables are oriented according to their kind 
489 -- so that the invariant of CTyEqCan has the best chance of
490 -- holding:   tv ~ xi
491 --   * If tv is a MetaTyVar, then typeKind xi <: typeKind tv 
492 --              a skolem,    then typeKind xi =  typeKind tv 
493 reOrient (VarCls tv1) (VarCls tv2)
494   | k1 `eqKind` k2 = False
495   | otherwise      = k1 `isSubKind` k2 
496   where
497     k1 = tyVarKind tv1
498     k2 = tyVarKind tv2
499
500 ------------------
501 canEqLeaf :: CtFlavor -> CoVar 
502           -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts 
503 -- Canonicalizing "leaf" equality constraints which cannot be
504 -- decomposed further (ie one of the types is a variable or
505 -- saturated type function application).  
506
507   -- Preconditions: 
508   --    * one of the two arguments is not OtherCls
509   --    * the two types are not equal (looking through synonyms)
510 canEqLeaf fl cv cls1 cls2 
511   | cls1 `reOrient` cls2 
512   = do { cv' <- if isWanted fl 
513                 then do { cv' <- newWantedCoVar s2 s1 
514                         ; setWantedCoBind cv $ mkSymCoercion (mkCoVarCoercion cv') 
515                         ; return cv' } 
516                 else newGivOrDerCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv)) 
517        ; canEqLeafOriented fl cv' cls2 s1 }
518
519   | otherwise
520   = canEqLeafOriented fl cv cls1 s2
521   where
522     s1 = unClassify cls1  
523     s2 = unClassify cls2  
524
525 ------------------
526 canEqLeafOriented :: CtFlavor -> CoVar 
527                   -> TypeClassifier -> TcType -> TcS CanonicalCts 
528 -- First argument is not OtherCls
529 canEqLeafOriented fl cv cls1@(FunCls fn tys) s2 
530   | not (kindAppResult (tyConKind fn) tys `eqKind` typeKind s2 )
531   = do { kindErrorTcS fl (unClassify cls1) s2
532        ; return emptyCCan }
533   | otherwise 
534   = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
535     do { (xis1,ccs1) <- flattenMany fl tys -- flatten type function arguments
536        ; (xi2,ccs2)  <- flatten fl s2      -- flatten entire RHS
537        ; let final_cc = CFunEqCan { cc_id     = cv 
538                                   , cc_flavor = fl 
539                                   , cc_fun    = fn
540                                   , cc_tyargs = xis1 
541                                   , cc_rhs    = xi2 }
542        ; return $ ccs1 `andCCan` ccs2 `extendCCans` final_cc }
543
544 -- Otherwise, we have a variable on the left, so we flatten the RHS
545 -- and then do an occurs check.
546 canEqLeafOriented fl cv (VarCls tv) s2 
547   | not (k1 `eqKind` k2 || (isMetaTyVar tv && k2 `isSubKind` k1))
548       -- Establish the kind invariant for CTyEqCan
549   = do { kindErrorTcS fl (mkTyVarTy tv) s2
550        ; return emptyCCan }
551
552   | otherwise
553   = do { (xi2,ccs2) <- flatten fl s2      -- flatten RHS
554        ; xi2' <- canOccursCheck fl tv xi2 -- do an occurs check, and return a possibly 
555                                           -- unfolded version of the RHS, if we had to 
556                                           -- unfold any type synonyms to get rid of tv.
557        ; let final_cc = CTyEqCan { cc_id     = cv 
558                                  , cc_flavor = fl
559                                  , cc_tyvar  = tv
560                                  , cc_rhs    = xi2'
561                                  } 
562        ; return $ ccs2 `extendCCans` final_cc }
563   where
564     k1 = tyVarKind tv
565     k2 = typeKind s2
566
567 canEqLeafOriented _ cv (OtherCls ty1) ty2 
568   = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)
569
570 -- See Note [Type synonyms and canonicalization].
571 -- Check whether the given variable occurs in the given type.  We may
572 -- have needed to do some type synonym unfolding in order to get rid
573 -- of the variable, so we also return the unfolded version of the
574 -- type, which is guaranteed to be syntactically free of the given
575 -- type variable.  If the type is already syntactically free of the
576 -- variable, then the same type is returned.
577 --
578 -- Precondition: the two types are not equal (looking though synonyms)
579 canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS Xi
580 canOccursCheck gw tv xi 
581   | Just xi' <- expandAway tv xi = return xi'
582   | otherwise = occursCheckErrorTcS gw tv xi
583 \end{code}
584
585 @expandAway tv xi@ expands synonyms in xi just enough to get rid of
586 occurrences of tv, if that is possible; otherwise, it returns Nothing.
587 For example, suppose we have
588   type F a b = [a]
589 Then
590   expandAway b (F Int b) = Just [Int]
591 but
592   expandAway a (F a Int) = Nothing
593
594 We don't promise to do the absolute minimum amount of expanding
595 necessary, but we try not to do expansions we don't need to.  We
596 prefer doing inner expansions first.  For example,
597   type F a b = (a, Int, a, [a])
598   type G b   = Char
599 We have
600   expandAway b (F (G b)) = F Char
601 even though we could also expand F to get rid of b.
602
603 \begin{code}
604 expandAway :: TcTyVar -> Xi -> Maybe Xi
605 expandAway tv t@(TyVarTy tv') 
606   | tv == tv' = Nothing
607   | otherwise = Just t
608 expandAway tv xi
609   | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
610 expandAway tv (AppTy ty1 ty2) 
611   = mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
612 expandAway tv (FunTy ty1 ty2)
613   = mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
614 expandAway _ (ForAllTy {}) = error "blorg"  -- TODO
615 expandAway _ (PredTy {})   = error "flerg"  -- TODO
616
617 -- For a type constructor application, first try expanding away the
618 -- offending variable from the arguments.  If that doesn't work, next
619 -- see if the type constructor is a type synonym, and if so, expand
620 -- it and try again.
621 expandAway tv ty@(TyConApp tc tys)
622     = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)
623 \end{code}
624
625 Note [Type synonyms and canonicalization]
626 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
627
628 We treat type synonym applications as xi types, that is, they do not
629 count as type function applications.  However, we do need to be a bit
630 careful with type synonyms: like type functions they may not be
631 generative or injective.  However, unlike type functions, they are
632 parametric, so there is no problem in expanding them whenever we see
633 them, since we do not need to know anything about their arguments in
634 order to expand them; this is what justifies not having to treat them
635 as specially as type function applications.  The thing that causes
636 some subtleties is that we prefer to leave type synonym applications
637 *unexpanded* whenever possible, in order to generate better error
638 messages.
639
640 If we encounter an equality constraint with type synonym applications
641 on both sides, or a type synonym application on one side and some sort
642 of type application on the other, we simply must expand out the type
643 synonyms in order to continue decomposing the equality constraint into
644 primitive equality constraints.  For example, suppose we have
645
646   type F a = [Int]
647
648 and we encounter the equality
649
650   F a ~ [b]
651
652 In order to continue we must expand F a into [Int], giving us the
653 equality
654
655   [Int] ~ [b]
656
657 which we can then decompose into the more primitive equality
658 constraint
659
660   Int ~ b.
661
662 However, if we encounter an equality constraint with a type synonym
663 application on one side and a variable on the other side, we should
664 NOT (necessarily) expand the type synonym, since for the purpose of
665 good error messages we want to leave type synonyms unexpanded as much
666 as possible.
667
668 However, there is a subtle point with type synonyms and the occurs
669 check that takes place for equality constraints of the form tv ~ xi.
670 As an example, suppose we have
671
672   type F a = Int
673
674 and we come across the equality constraint
675
676   a ~ F a
677
678 This should not actually fail the occurs check, since expanding out
679 the type synonym results in the legitimate equality constraint a ~
680 Int.  We must actually do this expansion, because unifying a with F a
681 will lead the type checker into infinite loops later.  Put another
682 way, canonical equality constraints should never *syntactically*
683 contain the LHS variable in the RHS type.  However, we don't always
684 need to expand type synonyms when doing an occurs check; for example,
685 the constraint
686
687   a ~ F b
688
689 is obviously fine no matter what F expands to. And in this case we
690 would rather unify a with F b (rather than F b's expansion) in order
691 to get better error messages later.
692
693 So, when doing an occurs check with a type synonym application on the
694 RHS, we use some heuristics to find an expansion of the RHS which does
695 not contain the variable from the LHS.  In particular, given
696
697   a ~ F t1 ... tn
698
699 we first try expanding each of the ti to types which no longer contain
700 a.  If this turns out to be impossible, we next try expanding F
701 itself, and so on.
702
703
704