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