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