Rename -XPArr to -XParallelArrays
[ghc-hetmet.git] / compiler / typecheck / TcCanonical.lhs
1 \begin{code}
2 module TcCanonical(
3     mkCanonical, mkCanonicals, canWanteds, canGivens, canOccursCheck, canEq,
4  ) where
5
6 #include "HsVersions.h"
7
8 import BasicTypes 
9 import Type
10 import TcRnTypes
11
12 import TcType
13 import TcErrors
14 import Coercion
15 import Class
16 import TyCon
17 import TypeRep
18 import Name
19 import Var
20 import Outputable
21 import Control.Monad    ( when, zipWithM )
22 import MonadUtils
23 import Control.Applicative ( (<|>) )
24
25 import VarSet
26 import Bag
27
28 import HsBinds 
29
30 import Control.Monad  ( unless )
31 import TcSMonad  -- The TcS Monad 
32 \end{code}
33
34 Note [Canonicalisation]
35 ~~~~~~~~~~~~~~~~~~~~~~~
36 * Converts (Constraint f) _which_does_not_contain_proper_implications_ to CanonicalCts
37 * Unary: treats individual constraints one at a time
38 * Does not do any zonking
39 * Lives in TcS monad so that it can create new skolem variables
40
41
42 %************************************************************************
43 %*                                                                      *
44 %*        Flattening (eliminating all function symbols)                 *
45 %*                                                                      *
46 %************************************************************************
47
48 Note [Flattening]
49 ~~~~~~~~~~~~~~~~~~~~
50   flatten ty  ==>   (xi, cc)
51     where
52       xi has no type functions
53       cc = Auxiliary given (equality) constraints constraining
54            the fresh type variables in xi.  Evidence for these 
55            is always the identity coercion, because internally the
56            fresh flattening skolem variables are actually identified
57            with the types they have been generated to stand in for.
58
59 Note that it is flatten's job to flatten *every type function it sees*.
60 flatten is only called on *arguments* to type functions, by canEqGiven.
61
62 Recall that in comments we use alpha[flat = ty] to represent a
63 flattening skolem variable alpha which has been generated to stand in
64 for ty.
65
66 ----- Example of flattening a constraint: ------
67   flatten (List (F (G Int)))  ==>  (xi, cc)
68     where
69       xi  = List alpha
70       cc  = { G Int ~ beta[flat = G Int],
71               F beta ~ alpha[flat = F beta] }
72 Here
73   * alpha and beta are 'flattening skolem variables'.
74   * All the constraints in cc are 'given', and all their coercion terms 
75     are the identity.
76
77 NB: Flattening Skolems only occur in canonical constraints, which
78 are never zonked, so we don't need to worry about zonking doing
79 accidental unflattening.
80
81 Note that we prefer to leave type synonyms unexpanded when possible,
82 so when the flattener encounters one, it first asks whether its
83 transitive expansion contains any type function applications.  If so,
84 it expands the synonym and proceeds; if not, it simply returns the
85 unexpanded synonym.
86
87 TODO: caching the information about whether transitive synonym
88 expansions contain any type function applications would speed things
89 up a bit; right now we waste a lot of energy traversing the same types
90 multiple times.
91
92 \begin{code}
93 -- Flatten a bunch of types all at once.
94 flattenMany :: CtFlavor -> [Type] -> TcS ([Xi], [Coercion], CanonicalCts)
95 -- Coercions :: Xi ~ Type 
96 flattenMany ctxt tys 
97   = do { (xis, cos, cts_s) <- mapAndUnzip3M (flatten ctxt) tys
98        ; return (xis, cos, andCCans cts_s) }
99
100 -- Flatten a type to get rid of type function applications, returning
101 -- the new type-function-free type, and a collection of new equality
102 -- constraints.  See Note [Flattening] for more detail.
103 flatten :: CtFlavor -> TcType -> TcS (Xi, Coercion, CanonicalCts)
104 -- Postcondition: Coercion :: Xi ~ TcType 
105 flatten ctxt ty 
106   | Just ty' <- tcView ty
107   = do { (xi, co, ccs) <- flatten ctxt ty'
108         -- Preserve type synonyms if possible
109         -- We can tell if ty' is function-free by
110         -- whether there are any floated constraints
111        ; if isEmptyCCan ccs then
112              return (ty, ty, emptyCCan)  
113          else
114              return (xi, co, ccs) }
115
116 flatten _ v@(TyVarTy _)
117   = return (v, v, emptyCCan)
118
119 flatten ctxt (AppTy ty1 ty2)
120   = do { (xi1,co1,c1) <- flatten ctxt ty1
121        ; (xi2,co2,c2) <- flatten ctxt ty2
122        ; return (mkAppTy xi1 xi2, mkAppCoercion co1 co2, c1 `andCCan` c2) }
123
124 flatten ctxt (FunTy ty1 ty2)
125   = do { (xi1,co1,c1) <- flatten ctxt ty1
126        ; (xi2,co2,c2) <- flatten ctxt ty2
127        ; return (mkFunTy xi1 xi2, mkFunCoercion co1 co2, c1 `andCCan` c2) }
128
129 flatten fl (TyConApp tc tys)
130   -- For a normal type constructor or data family application, we just
131   -- recursively flatten the arguments.
132   | not (isSynFamilyTyCon tc)
133     = do { (xis,cos,ccs) <- flattenMany fl tys
134          ; return (mkTyConApp tc xis, mkTyConCoercion tc cos, ccs) }
135
136   -- Otherwise, it's a type function application, and we have to
137   -- flatten it away as well, and generate a new given equality constraint
138   -- between the application and a newly generated flattening skolem variable.
139   | otherwise 
140   = ASSERT( tyConArity tc <= length tys )       -- Type functions are saturated
141       do { (xis, cos, ccs) <- flattenMany fl tys
142          ; let (xi_args, xi_rest)  = splitAt (tyConArity tc) xis
143                (cos_args, cos_rest) = splitAt (tyConArity tc) cos 
144                  -- The type function might be *over* saturated
145                  -- in which case the remaining arguments should
146                  -- be dealt with by AppTys
147                fam_ty = mkTyConApp tc xi_args 
148                fam_co = fam_ty -- identity 
149
150          ; (ret_co, rhs_var, ct) <- 
151              if isGiven fl then
152                do { rhs_var <- newFlattenSkolemTy fam_ty
153                   ; cv <- newGivOrDerCoVar fam_ty rhs_var fam_co
154                   ; let ct = CFunEqCan { cc_id     = cv
155                                        , cc_flavor = fl -- Given
156                                        , cc_fun    = tc 
157                                        , cc_tyargs = xi_args 
158                                        , cc_rhs    = rhs_var }
159                   ; return $ (mkCoVarCoercion cv, rhs_var, ct) }
160              else -- Derived or Wanted: make a new *unification* flatten variable
161                do { rhs_var <- newFlexiTcSTy (typeKind fam_ty)
162                   ; cv <- newWantedCoVar fam_ty rhs_var
163                   ; let ct = CFunEqCan { cc_id = cv
164                                        , cc_flavor = mkWantedFlavor fl
165                                            -- Always Wanted, not Derived
166                                        , cc_fun = tc
167                                        , cc_tyargs = xi_args
168                                        , cc_rhs    = rhs_var }
169                   ; return $ (mkCoVarCoercion cv, rhs_var, ct) }
170
171          ; return ( foldl AppTy rhs_var xi_rest
172                   , foldl AppTy (mkSymCoercion ret_co 
173                                     `mkTransCoercion` mkTyConCoercion tc cos_args) cos_rest
174                   , ccs `extendCCans` ct) }
175
176
177 flatten ctxt (PredTy pred) 
178   = do { (pred', co, ccs) <- flattenPred ctxt pred
179        ; return (PredTy pred', co, ccs) }
180
181 flatten ctxt ty@(ForAllTy {})
182 -- We allow for-alls when, but only when, no type function
183 -- applications inside the forall involve the bound type variables
184 -- TODO: What if it is a (t1 ~ t2) => t3
185 --       Must revisit when the New Coercion API is here! 
186   = do { let (tvs, rho) = splitForAllTys ty
187        ; (rho', co, ccs) <- flatten ctxt rho
188        ; let bad_eqs  = filterBag is_bad ccs
189              is_bad c = tyVarsOfCanonical c `intersectsVarSet` tv_set
190              tv_set   = mkVarSet tvs
191        ; unless (isEmptyBag bad_eqs)
192                 (flattenForAllErrorTcS ctxt ty bad_eqs)
193        ; return (mkForAllTys tvs rho', mkForAllTys tvs co, ccs)  }
194
195 ---------------
196 flattenPred :: CtFlavor -> TcPredType -> TcS (TcPredType, Coercion, CanonicalCts)
197 flattenPred ctxt (ClassP cls tys)
198   = do { (tys', cos, ccs) <- flattenMany ctxt tys
199        ; return (ClassP cls tys', mkClassPPredCo cls cos, ccs) }
200 flattenPred ctxt (IParam nm ty)
201   = do { (ty', co, ccs) <- flatten ctxt ty
202        ; return (IParam nm ty', mkIParamPredCo nm co, ccs) }
203 -- TODO: Handling of coercions between EqPreds must be revisited once the New Coercion API is ready!
204 flattenPred ctxt (EqPred ty1 ty2)
205   = do { (ty1', co1, ccs1) <- flatten ctxt ty1
206        ; (ty2', co2, ccs2) <- flatten ctxt ty2
207        ; return (EqPred ty1' ty2', mkEqPredCo co1 co2, ccs1 `andCCan` ccs2) }
208
209 \end{code}
210
211 %************************************************************************
212 %*                                                                      *
213 %*                Canonicalising given constraints                      *
214 %*                                                                      *
215 %************************************************************************
216
217 \begin{code}
218 canWanteds :: [WantedEvVar] -> TcS CanonicalCts 
219 canWanteds = fmap andCCans . mapM (\(WantedEvVar ev loc) -> mkCanonical (Wanted loc) ev)
220
221 canGivens :: GivenLoc -> [EvVar] -> TcS CanonicalCts
222 canGivens loc givens = do { ccs <- mapM (mkCanonical (Given loc)) givens
223                           ; return (andCCans ccs) }
224
225 mkCanonicals :: CtFlavor -> [EvVar] -> TcS CanonicalCts 
226 mkCanonicals fl vs = fmap andCCans (mapM (mkCanonical fl) vs)
227
228 mkCanonical :: CtFlavor -> EvVar -> TcS CanonicalCts 
229 mkCanonical fl ev = case evVarPred ev of 
230                         ClassP clas tys -> canClass fl ev clas tys 
231                         IParam ip ty    -> canIP    fl ev ip ty
232                         EqPred ty1 ty2  -> canEq    fl ev ty1 ty2 
233                          
234
235 canClass :: CtFlavor -> EvVar -> Class -> [TcType] -> TcS CanonicalCts 
236 canClass fl v cn tys 
237   = do { (xis,cos,ccs) <- flattenMany fl tys  -- cos :: xis ~ tys
238        ; let no_flattening_happened = isEmptyCCan ccs
239              dict_co = mkTyConCoercion (classTyCon cn) cos
240        ; v_new <- if no_flattening_happened then return v
241                   else if isGiven fl        then return v
242                          -- The cos are all identities if fl=Given,
243                          -- hence nothing to do
244                   else do { v' <- newDictVar cn xis  -- D xis
245                           ; if isWanted fl
246                             then setDictBind v  (EvCast v' dict_co)
247                             else setDictBind v' (EvCast v (mkSymCoercion dict_co))
248                           ; return v' }
249
250        -- Add the superclasses of this one here, See Note [Adding superclasses]
251        ; sc_cts <- newSCWorkFromFlavored v_new fl cn xis
252
253        ; return (sc_cts `andCCan` ccs `extendCCans` CDictCan { cc_id     = v_new
254                                                              , cc_flavor = fl
255                                                              , cc_class  = cn 
256                                                              , cc_tyargs = xis }) }
257
258 \end{code}
259
260 Note [Adding superclasses]
261 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 
262 Since dictionaries are canonicalized only once in their lifetime, the
263 place to add their superclasses is canonicalisation (The alternative
264 would be to do it during constraint solving, but we'd have to be
265 extremely careful to not repeatedly introduced the same superclass in
266 our worklist). Here is what we do:
267
268 For Givens: 
269        We add all their superclasses as Givens. 
270
271 For Wanteds: 
272        Generally speaking, we want to be able to add derived
273        superclasses of unsolved wanteds, and wanteds that have been
274        partially being solved via an instance. This is important to be
275        able to simplify the inferred constraints more (and to allow
276        for recursive dictionaries, less importantly).
277
278        Example: Inferred wanted constraint is (Eq a, Ord a), but we'd
279        only like to quantify over Ord a, hence we would like to be
280        able to add the superclass of Ord a as Derived and use it to
281        solve the wanted Eq a.
282
283 For Deriveds: 
284        Deriveds either arise as wanteds that have been partially
285        solved, or as superclasses of other wanteds or deriveds. Hence,
286        their superclasses must be already there so we must do nothing
287        at al.
288
289        DV: In fact, it is probably true that the canonicaliser is
290           *never* asked to canonicalise Derived dictionaries
291
292 There is one disadvantage to this. Suppose the wanted constraints are
293 (Num a, Num a).  Then we'll add all the superclasses of both during
294 canonicalisation, only to eliminate them later when they are
295 interacted.  That seems like a waste of work.  Still, it's simple.
296
297 Here's an example that demonstrates why we chose to NOT add
298 superclasses during simplification: [Comes from ticket #4497]
299
300    class Num (RealOf t) => Normed t
301    type family RealOf x
302
303 Assume the generated wanted constraint is: 
304    RealOf e ~ e, Normed e 
305 If we were to be adding the superclasses during simplification we'd get: 
306    Num uf, Normed e, RealOf e ~ e, RealOf e ~ uf 
307 ==> 
308    e ~ uf, Num uf, Normed e, RealOf e ~ e 
309 ==> [Spontaneous solve] 
310    Num uf, Normed uf, RealOf uf ~ uf 
311
312 While looks exactly like our original constraint. If we add the superclass again we'd loop. 
313 By adding superclasses definitely only once, during canonicalisation, this situation can't 
314 happen.
315
316 \begin{code}
317 newSCWorkFromFlavored :: EvVar -> CtFlavor -> Class -> [Xi] -> TcS CanonicalCts
318 -- Returns superclasses, see Note [Adding superclasses]
319 newSCWorkFromFlavored ev orig_flavor cls xis 
320   | Given loc <- orig_flavor   -- Very important!
321   , NoScSkol  <- ctLocOrigin loc
322   = return emptyCCan
323   | otherwise
324   = do { let (tyvars, sc_theta, _, _) = classBigSig cls 
325              sc_theta1 = substTheta (zipTopTvSubst tyvars xis) sc_theta
326        ; sc_vars <- zipWithM inst_one sc_theta1 [0..]
327        ; mkCanonicals flavor sc_vars }
328              -- NB: Since there is a call to mkCanonicals,
329              -- this will add *recursively* all superclasses
330   where
331     inst_one pred n = newGivOrDerEvVar pred (EvSuperClass ev n)
332     flavor = case orig_flavor of 
333                Given loc  -> Given loc
334                Wanted loc -> Derived loc DerSC
335                Derived {} -> orig_flavor
336                    -- NB: the non-immediate superclasses will show up as
337                    --     Derived, and we want their superclasses too!
338
339 canIP :: CtFlavor -> EvVar -> IPName Name -> TcType -> TcS CanonicalCts
340 -- See Note [Canonical implicit parameter constraints] to see why we don't 
341 -- immediately canonicalize (flatten) IP constraints. 
342 canIP fl v nm ty 
343   = return $ singleCCan $ CIPCan { cc_id = v
344                                  , cc_flavor = fl
345                                  , cc_ip_nm = nm
346                                  , cc_ip_ty = ty } 
347
348 -----------------
349 canEq :: CtFlavor -> EvVar -> Type -> Type -> TcS CanonicalCts 
350 canEq fl cv ty1 ty2 
351   | tcEqType ty1 ty2    -- Dealing with equality here avoids
352                         -- later spurious occurs checks for a~a
353   = do { when (isWanted fl) (setWantedCoBind cv ty1)
354        ; return emptyCCan }
355
356 -- If one side is a variable, orient and flatten, 
357 -- WITHOUT expanding type synonyms, so that we tend to 
358 -- substitute a ~ Age rather than a ~ Int when @type Age = Int@
359 canEq fl cv ty1@(TyVarTy {}) ty2 
360   = do { untch <- getUntouchables 
361        ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
362 canEq fl cv ty1 ty2@(TyVarTy {}) 
363   = do { untch <- getUntouchables 
364        ; canEqLeaf untch fl cv (classify ty1) (classify ty2) }
365       -- NB: don't use VarCls directly because tv1 or tv2 may be scolems!
366
367 canEq fl cv (TyConApp fn tys) ty2 
368   | isSynFamilyTyCon fn, length tys == tyConArity fn
369   = do { untch <- getUntouchables 
370        ; canEqLeaf untch fl cv (FunCls fn tys) (classify ty2) }
371 canEq fl cv ty1 (TyConApp fn tys)
372   | isSynFamilyTyCon fn, length tys == tyConArity fn
373   = do { untch <- getUntouchables 
374        ; canEqLeaf untch fl cv (classify ty1) (FunCls fn tys) }
375
376 canEq fl cv s1 s2
377   | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe s1, 
378     Just (t2a,t2b,t2c) <- splitCoPredTy_maybe s2
379   = do { (v1,v2,v3) <- if isWanted fl then 
380                          do { v1 <- newWantedCoVar t1a t2a
381                             ; v2 <- newWantedCoVar t1b t2b 
382                             ; v3 <- newWantedCoVar t1c t2c 
383                             ; let res_co = mkCoPredCo (mkCoVarCoercion v1) 
384                                                       (mkCoVarCoercion v2) (mkCoVarCoercion v3)
385                             ; setWantedCoBind cv res_co
386                             ; return (v1,v2,v3) }
387                        else let co_orig = mkCoVarCoercion cv 
388                                 coa = mkCsel1Coercion co_orig
389                                 cob = mkCsel2Coercion co_orig
390                                 coc = mkCselRCoercion co_orig
391                             in do { v1 <- newGivOrDerCoVar t1a t2a coa
392                                   ; v2 <- newGivOrDerCoVar t1b t2b cob
393                                   ; v3 <- newGivOrDerCoVar t1c t2c coc 
394                                   ; return (v1,v2,v3) }
395        ; cc1 <- canEq fl v1 t1a t2a 
396        ; cc2 <- canEq fl v2 t1b t2b 
397        ; cc3 <- canEq fl v3 t1c t2c 
398        ; return (cc1 `andCCan` cc2 `andCCan` cc3) }
399
400
401 -- Split up an equality between function types into two equalities.
402 canEq fl cv (FunTy s1 t1) (FunTy s2 t2)
403   = do { (argv, resv) <- 
404              if isWanted fl then 
405                  do { argv <- newWantedCoVar s1 s2 
406                     ; resv <- newWantedCoVar t1 t2 
407                     ; setWantedCoBind cv $ 
408                       mkFunCoercion (mkCoVarCoercion argv) (mkCoVarCoercion resv) 
409                     ; return (argv,resv) } 
410              else let [arg,res] = decomposeCo 2 (mkCoVarCoercion cv) 
411                   in do { argv <- newGivOrDerCoVar s1 s2 arg 
412                         ; resv <- newGivOrDerCoVar t1 t2 res
413                         ; return (argv,resv) } 
414        ; cc1 <- canEq fl argv s1 s2 -- inherit original kinds and locations
415        ; cc2 <- canEq fl resv t1 t2
416        ; return (cc1 `andCCan` cc2) }
417
418 canEq fl cv (PredTy (IParam n1 t1)) (PredTy (IParam n2 t2))
419   | n1 == n2
420   = if isWanted fl then 
421         do { v <- newWantedCoVar t1 t2 
422            ; setWantedCoBind cv $ mkIParamPredCo n1 (mkCoVarCoercion cv)
423            ; canEq fl v t1 t2 } 
424     else return emptyCCan -- DV: How to decompose given IP coercions? 
425
426 canEq fl cv (PredTy (ClassP c1 tys1)) (PredTy (ClassP c2 tys2))
427   | c1 == c2
428   = if isWanted fl then 
429        do { vs <- zipWithM newWantedCoVar tys1 tys2 
430           ; setWantedCoBind cv $ mkClassPPredCo c1 (map mkCoVarCoercion vs) 
431           ; andCCans <$> zipWith3M (canEq fl) vs tys1 tys2
432           }
433     else return emptyCCan 
434   -- How to decompose given dictionary (and implicit parameter) coercions? 
435   -- You may think that the following is right: 
436   --    let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
437   --    in  zipWith3M newGivOrDerCoVar tys1 tys2 cos
438   -- But this assumes that the coercion is a type constructor-based 
439   -- coercion, and not a PredTy (ClassP cn cos) coercion. So we chose
440   -- to not decompose these coercions. We have to get back to this 
441   -- when we clean up the Coercion API.
442
443 canEq fl cv (TyConApp tc1 tys1) (TyConApp tc2 tys2)
444   | isAlgTyCon tc1 && isAlgTyCon tc2
445   , tc1 == tc2
446   , length tys1 == length tys2
447   = -- Generate equalities for each of the corresponding arguments
448     do { argsv <- if isWanted fl then
449                     do { argsv <- zipWithM newWantedCoVar tys1 tys2
450                             ; setWantedCoBind cv $ mkTyConCoercion tc1 (map mkCoVarCoercion argsv)
451                             ; return argsv } 
452                   else 
453                     let cos = decomposeCo (length tys1) (mkCoVarCoercion cv) 
454                     in zipWith3M newGivOrDerCoVar tys1 tys2 cos
455        ; andCCans <$> zipWith3M (canEq fl) argsv tys1 tys2 }
456
457 -- See Note [Equality between type applications]
458 --     Note [Care with type applications] in TcUnify
459 canEq fl cv ty1 ty2
460   | Just (s1,t1) <- tcSplitAppTy_maybe ty1
461   , Just (s2,t2) <- tcSplitAppTy_maybe ty2
462     = do { (cv1,cv2) <- 
463              if isWanted fl 
464              then do { cv1 <- newWantedCoVar s1 s2 
465                      ; cv2 <- newWantedCoVar t1 t2 
466                      ; setWantedCoBind cv $ 
467                        mkAppCoercion (mkCoVarCoercion cv1) (mkCoVarCoercion cv2) 
468                      ; return (cv1,cv2) } 
469              else let co1 = mkLeftCoercion  $ mkCoVarCoercion cv 
470                       co2 = mkRightCoercion $ mkCoVarCoercion cv
471                   in do { cv1 <- newGivOrDerCoVar s1 s2 co1 
472                         ; cv2 <- newGivOrDerCoVar t1 t2 co2 
473                         ; return (cv1,cv2) } 
474          ; cc1 <- canEq fl cv1 s1 s2 
475          ; cc2 <- canEq fl cv2 t1 t2 
476          ; return (cc1 `andCCan` cc2) } 
477
478 canEq fl _ s1@(ForAllTy {}) s2@(ForAllTy {})  
479  | tcIsForAllTy s1, tcIsForAllTy s2, 
480    Wanted {} <- fl 
481  = canEqFailure fl s1 s2
482  | otherwise
483  = do { traceTcS "Ommitting decomposition of given polytype equality" (pprEq s1 s2)
484       ; return emptyCCan }
485
486 -- Finally expand any type synonym applications.
487 canEq fl cv ty1 ty2 | Just ty1' <- tcView ty1 = canEq fl cv ty1' ty2
488 canEq fl cv ty1 ty2 | Just ty2' <- tcView ty2 = canEq fl cv ty1 ty2'
489 canEq fl _  ty1 ty2                           = canEqFailure fl ty1 ty2
490
491 canEqFailure :: CtFlavor -> Type -> Type -> TcS CanonicalCts
492 canEqFailure fl ty1 ty2
493   = do { addErrorTcS MisMatchError fl ty1 ty2
494        ; return emptyCCan }
495 \end{code}
496
497 Note [Equality between type applications]
498 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
499 If we see an equality of the form s1 t1 ~ s2 t2 we can always split
500 it up into s1 ~ s2 /\ t1 ~ t2, since s1 and s2 can't be type
501 functions (type functions use the TyConApp constructor, which never
502 shows up as the LHS of an AppTy).  Other than type functions, types
503 in Haskell are always 
504
505   (1) generative: a b ~ c d implies a ~ c, since different type
506       constructors always generate distinct types
507
508   (2) injective: a b ~ a d implies b ~ d; we never generate the
509       same type from different type arguments.
510
511
512 Note [Canonical ordering for equality constraints]
513 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
514 Implemented as (<+=) below:
515
516   - Type function applications always come before anything else.  
517   - Variables always come before non-variables (other than type
518       function applications).
519
520 Note that we don't need to unfold type synonyms on the RHS to check
521 the ordering; that is, in the rules above it's OK to consider only
522 whether something is *syntactically* a type function application or
523 not.  To illustrate why this is OK, suppose we have an equality of the
524 form 'tv ~ S a b c', where S is a type synonym which expands to a
525 top-level application of the type function F, something like
526
527   type S a b c = F d e
528
529 Then to canonicalize 'tv ~ S a b c' we flatten the RHS, and since S's
530 expansion contains type function applications the flattener will do
531 the expansion and then generate a skolem variable for the type
532 function application, so we end up with something like this:
533
534   tv ~ x
535   F d e ~ x
536
537 where x is the skolem variable.  This is one extra equation than
538 absolutely necessary (we could have gotten away with just 'F d e ~ tv'
539 if we had noticed that S expanded to a top-level type function
540 application and flipped it around in the first place) but this way
541 keeps the code simpler.
542
543 Unlike the OutsideIn(X) draft of May 7, 2010, we do not care about the
544 ordering of tv ~ tv constraints.  There are several reasons why we
545 might:
546
547   (1) In order to be able to extract a substitution that doesn't
548       mention untouchable variables after we are done solving, we might
549       prefer to put touchable variables on the left. However, in and
550       of itself this isn't necessary; we can always re-orient equality
551       constraints at the end if necessary when extracting a substitution.
552
553   (2) To ensure termination we might think it necessary to put
554       variables in lexicographic order. However, this isn't actually 
555       necessary as outlined below.
556
557 While building up an inert set of canonical constraints, we maintain
558 the invariant that the equality constraints in the inert set form an
559 acyclic rewrite system when viewed as L-R rewrite rules.  Moreover,
560 the given constraints form an idempotent substitution (i.e. none of
561 the variables on the LHS occur in any of the RHS's, and type functions
562 never show up in the RHS at all), the wanted constraints also form an
563 idempotent substitution, and finally the LHS of a given constraint
564 never shows up on the RHS of a wanted constraint.  There may, however,
565 be a wanted LHS that shows up in a given RHS, since we do not rewrite
566 given constraints with wanted constraints.
567
568 Suppose we have an inert constraint set
569
570
571   tg_1 ~ xig_1         -- givens
572   tg_2 ~ xig_2
573   ...
574   tw_1 ~ xiw_1         -- wanteds
575   tw_2 ~ xiw_2
576   ...
577
578 where each t_i can be either a type variable or a type function
579 application. Now suppose we take a new canonical equality constraint,
580 t' ~ xi' (note among other things this means t' does not occur in xi')
581 and try to react it with the existing inert set.  We show by induction
582 on the number of t_i which occur in t' ~ xi' that this process will
583 terminate.
584
585 There are several ways t' ~ xi' could react with an existing constraint:
586
587 TODO: finish this proof.  The below was for the case where the entire
588 inert set is an idempotent subustitution...
589
590 (b) We could have t' = t_j for some j.  Then we obtain the new
591     equality xi_j ~ xi'; note that neither xi_j or xi' contain t_j.  We
592     now canonicalize the new equality, which may involve decomposing it
593     into several canonical equalities, and recurse on these.  However,
594     none of the new equalities will contain t_j, so they have fewer
595     occurrences of the t_i than the original equation.
596
597 (a) We could have t_j occurring in xi' for some j, with t' /=
598     t_j. Then we substitute xi_j for t_j in xi' and continue.  However,
599     since none of the t_i occur in xi_j, we have decreased the
600     number of t_i that occur in xi', since we eliminated t_j and did not
601     introduce any new ones.
602
603 \begin{code}
604 data TypeClassifier 
605   = FskCls TcTyVar      -- ^ Flatten skolem 
606   | VarCls TcTyVar      -- ^ Non-flatten-skolem variable 
607   | FunCls TyCon [Type] -- ^ Type function, exactly saturated
608   | OtherCls TcType     -- ^ Neither of the above
609
610 unClassify :: TypeClassifier -> TcType
611 unClassify (VarCls tv)      = TyVarTy tv
612 unClassify (FskCls tv) = TyVarTy tv 
613 unClassify (FunCls fn tys)  = TyConApp fn tys
614 unClassify (OtherCls ty)    = ty
615
616 classify :: TcType -> TypeClassifier
617
618 classify (TyVarTy tv) 
619   | isTcTyVar tv, 
620     FlatSkol {} <- tcTyVarDetails tv = FskCls tv
621   | otherwise                        = VarCls tv
622 classify (TyConApp tc tys) | isSynFamilyTyCon tc
623                            , tyConArity tc == length tys
624                            = FunCls tc tys
625 classify ty                | Just ty' <- tcView ty
626                            = case classify ty' of
627                                OtherCls {} -> OtherCls ty
628                                var_or_fn   -> var_or_fn
629                            | otherwise 
630                            = OtherCls ty
631
632 -- See note [Canonical ordering for equality constraints].
633 reOrient :: TcsUntouchables -> TypeClassifier -> TypeClassifier -> Bool 
634 -- (t1 `reOrient` t2) responds True 
635 --   iff we should flip to (t2~t1)
636 -- We try to say False if possible, to minimise evidence generation
637 --
638 -- Postcondition: After re-orienting, first arg is not OTherCls
639 reOrient _untch (OtherCls {}) (FunCls {})   = True
640 reOrient _untch (OtherCls {}) (FskCls {})   = True
641 reOrient _untch (OtherCls {}) (VarCls {})   = True
642 reOrient _untch (OtherCls {}) (OtherCls {}) = panic "reOrient"  -- One must be Var/Fun
643
644 reOrient _untch (FunCls {})   (VarCls {})    = False
645   -- See Note [No touchables as FunEq RHS] in TcSMonad
646 reOrient _untch (FunCls {}) _                = False             -- Fun/Other on rhs
647
648 reOrient _untch (VarCls {}) (FunCls {})      = True 
649
650 reOrient _untch (VarCls {}) (FskCls {})      = False
651
652 reOrient _untch (VarCls {})  (OtherCls {})   = False
653 reOrient _untch (VarCls tv1)  (VarCls tv2)  
654   | isMetaTyVar tv2 && not (isMetaTyVar tv1) = True 
655   | otherwise                                = False 
656   -- Just for efficiency, see CTyEqCan invariants 
657
658 reOrient _untch (FskCls {}) (VarCls tv2)     = isMetaTyVar tv2 
659   -- Just for efficiency, see CTyEqCan invariants
660
661 reOrient _untch (FskCls {}) (FskCls {})     = False
662 reOrient _untch (FskCls {}) (FunCls {})     = True 
663 reOrient _untch (FskCls {}) (OtherCls {})   = False 
664
665 ------------------
666 canEqLeaf :: TcsUntouchables 
667           -> CtFlavor -> CoVar 
668           -> TypeClassifier -> TypeClassifier -> TcS CanonicalCts 
669 -- Canonicalizing "leaf" equality constraints which cannot be
670 -- decomposed further (ie one of the types is a variable or
671 -- saturated type function application).  
672
673   -- Preconditions: 
674   --    * one of the two arguments is not OtherCls
675   --    * the two types are not equal (looking through synonyms)
676 canEqLeaf untch fl cv cls1 cls2 
677   | cls1 `re_orient` cls2
678   = do { cv' <- if isWanted fl 
679                 then do { cv' <- newWantedCoVar s2 s1 
680                         ; setWantedCoBind cv $ mkSymCoercion (mkCoVarCoercion cv') 
681                         ; return cv' } 
682                 else newGivOrDerCoVar s2 s1 (mkSymCoercion (mkCoVarCoercion cv)) 
683        ; canEqLeafOriented fl cv' cls2 s1 }
684
685   | otherwise
686   = canEqLeafOriented fl cv cls1 s2
687   where
688     re_orient = reOrient untch 
689     s1 = unClassify cls1  
690     s2 = unClassify cls2  
691
692 ------------------
693 canEqLeafOriented :: CtFlavor -> CoVar 
694                   -> TypeClassifier -> TcType -> TcS CanonicalCts 
695 -- First argument is not OtherCls
696 canEqLeafOriented fl cv cls1@(FunCls fn tys1) s2         -- cv : F tys1
697   | let k1 = kindAppResult (tyConKind fn) tys1,
698     let k2 = typeKind s2, 
699     isGiven fl && not (k1 `compatKind` k2) -- Establish the kind invariant for CFunEqCan
700   = addErrorTcS KindError fl (unClassify cls1) s2 >> return emptyCCan
701     -- Eagerly fails, see Note [Kind errors] in TcInteract
702
703   | otherwise 
704   = ASSERT2( isSynFamilyTyCon fn, ppr (unClassify cls1) )
705     do { (xis1,cos1,ccs1) <- flattenMany fl tys1 -- Flatten type function arguments
706                                                  -- cos1 :: xis1 ~ tys1
707        ; (xi2, co2, ccs2) <- flatten fl s2       -- Flatten entire RHS
708                                                  -- co2  :: xi2 ~ s2
709        ; let ccs = ccs1 `andCCan` ccs2
710              no_flattening_happened = isEmptyCCan ccs
711        ; cv_new <- if no_flattening_happened then return cv
712                    else if isGiven fl        then return cv
713                    else do { cv' <- newWantedCoVar (unClassify (FunCls fn xis1)) xi2
714                                  -- cv' : F xis ~ xi2
715                            ; let -- fun_co :: F xis1 ~ F tys1
716                                  fun_co = mkTyConCoercion fn cos1
717                                  -- want_co :: F tys1 ~ s2
718                                  want_co = mkSymCoercion fun_co
719                                            `mkTransCoercion` mkCoVarCoercion cv'
720                                            `mkTransCoercion` co2
721                                  -- der_co :: F xis1 ~ xi2
722                                  der_co = fun_co
723                                           `mkTransCoercion` mkCoVarCoercion cv
724                                           `mkTransCoercion` mkSymCoercion co2
725                            ; if isWanted fl
726                              then setWantedCoBind cv  want_co
727                              else setWantedCoBind cv' der_co
728                            ; return cv' }
729
730        ; let final_cc = CFunEqCan { cc_id     = cv_new
731                                   , cc_flavor = fl
732                                   , cc_fun    = fn
733                                   , cc_tyargs = xis1 
734                                   , cc_rhs    = xi2 }
735        ; return $ ccs `extendCCans` final_cc }
736
737 -- Otherwise, we have a variable on the left, so call canEqLeafTyVarLeft
738 canEqLeafOriented fl cv (FskCls tv) s2 
739   = canEqLeafTyVarLeft fl cv tv s2 
740 canEqLeafOriented fl cv (VarCls tv) s2 
741   = canEqLeafTyVarLeft fl cv tv s2 
742 canEqLeafOriented _ cv (OtherCls ty1) ty2 
743   = pprPanic "canEqLeaf" (ppr cv $$ ppr ty1 $$ ppr ty2)
744
745 canEqLeafTyVarLeft :: CtFlavor -> CoVar -> TcTyVar -> TcType -> TcS CanonicalCts
746 -- Establish invariants of CTyEqCans 
747 canEqLeafTyVarLeft fl cv tv s2       -- cv : tv ~ s2
748   | isGiven fl && not (k1 `compatKind` k2) -- Establish the kind invariant for CTyEqCan
749   = addErrorTcS KindError fl (mkTyVarTy tv) s2 >> return emptyCCan
750        -- Eagerly fails, see Note [Kind errors] in TcInteract
751   | otherwise
752   = do { (xi2, co, ccs2) <- flatten fl s2  -- Flatten RHS   co : xi2 ~ s2
753        ; mxi2' <- canOccursCheck fl tv xi2 -- Do an occurs check, and return a possibly
754                                            -- unfolded version of the RHS, if we had to 
755                                            -- unfold any type synonyms to get rid of tv.
756        ; case mxi2' of {
757            Nothing   -> addErrorTcS OccCheckError fl (mkTyVarTy tv) xi2 >> return emptyCCan ;
758            Just xi2' ->
759     do { let no_flattening_happened = isEmptyCCan ccs2
760        ; cv_new <- if no_flattening_happened then return cv
761                    else if isGiven fl        then return cv
762                    else do { cv' <- newWantedCoVar (mkTyVarTy tv) xi2'  -- cv' : tv ~ xi2
763                            ; if isWanted fl
764                              then setWantedCoBind cv  (mkCoVarCoercion cv' `mkTransCoercion` co)
765                              else setWantedCoBind cv' (mkCoVarCoercion cv  `mkTransCoercion`
766                                                        mkSymCoercion co)
767                            ; return cv' }
768
769        ; return $ ccs2 `extendCCans` CTyEqCan { cc_id     = cv_new
770                                               , cc_flavor = fl
771                                               , cc_tyvar  = tv
772                                               , cc_rhs    = xi2' } } } }
773   where
774     k1 = tyVarKind tv
775     k2 = typeKind s2
776
777 -- See Note [Type synonyms and canonicalization].
778 -- Check whether the given variable occurs in the given type.  We may
779 -- have needed to do some type synonym unfolding in order to get rid
780 -- of the variable, so we also return the unfolded version of the
781 -- type, which is guaranteed to be syntactically free of the given
782 -- type variable.  If the type is already syntactically free of the
783 -- variable, then the same type is returned.
784 --
785 -- Precondition: the two types are not equal (looking though synonyms)
786 canOccursCheck :: CtFlavor -> TcTyVar -> Xi -> TcS (Maybe Xi)
787 canOccursCheck _gw tv xi = return (expandAway tv xi)
788 \end{code}
789
790 @expandAway tv xi@ expands synonyms in xi just enough to get rid of
791 occurrences of tv, if that is possible; otherwise, it returns Nothing.
792 For example, suppose we have
793   type F a b = [a]
794 Then
795   expandAway b (F Int b) = Just [Int]
796 but
797   expandAway a (F a Int) = Nothing
798
799 We don't promise to do the absolute minimum amount of expanding
800 necessary, but we try not to do expansions we don't need to.  We
801 prefer doing inner expansions first.  For example,
802   type F a b = (a, Int, a, [a])
803   type G b   = Char
804 We have
805   expandAway b (F (G b)) = F Char
806 even though we could also expand F to get rid of b.
807
808 \begin{code}
809 expandAway :: TcTyVar -> Xi -> Maybe Xi
810 expandAway tv t@(TyVarTy tv') 
811   | tv == tv' = Nothing
812   | otherwise = Just t
813 expandAway tv xi
814   | not (tv `elemVarSet` tyVarsOfType xi) = Just xi
815 expandAway tv (AppTy ty1 ty2) 
816   = do { ty1' <- expandAway tv ty1
817        ; ty2' <- expandAway tv ty2 
818        ; return (mkAppTy ty1' ty2') }
819 -- mkAppTy <$> expandAway tv ty1 <*> expandAway tv ty2
820 expandAway tv (FunTy ty1 ty2)
821   = do { ty1' <- expandAway tv ty1 
822        ; ty2' <- expandAway tv ty2 
823        ; return (mkFunTy ty1' ty2') } 
824 -- mkFunTy <$> expandAway tv ty1 <*> expandAway tv ty2
825 expandAway tv ty@(ForAllTy {}) 
826   = let (tvs,rho) = splitForAllTys ty
827         tvs_knds  = map tyVarKind tvs 
828     in if tv `elemVarSet` tyVarsOfTypes tvs_knds then 
829        -- Can't expand away the kinds unless we create 
830        -- fresh variables which we don't want to do at this point.
831            Nothing 
832        else do { rho' <- expandAway tv rho
833                ; return (mkForAllTys tvs rho') }
834 expandAway tv (PredTy pred) 
835   = do { pred' <- expandAwayPred tv pred  
836        ; return (PredTy pred') }
837 -- For a type constructor application, first try expanding away the
838 -- offending variable from the arguments.  If that doesn't work, next
839 -- see if the type constructor is a type synonym, and if so, expand
840 -- it and try again.
841 expandAway tv ty@(TyConApp tc tys)
842   = (mkTyConApp tc <$> mapM (expandAway tv) tys) <|> (tcView ty >>= expandAway tv)
843
844 expandAwayPred :: TcTyVar -> TcPredType -> Maybe TcPredType 
845 expandAwayPred tv (ClassP cls tys) 
846   = do { tys' <- mapM (expandAway tv) tys; return (ClassP cls tys') } 
847 expandAwayPred tv (EqPred ty1 ty2)
848   = do { ty1' <- expandAway tv ty1
849        ; ty2' <- expandAway tv ty2 
850        ; return (EqPred ty1' ty2') }
851 expandAwayPred tv (IParam nm ty) 
852   = do { ty' <- expandAway tv ty
853        ; return (IParam nm ty') }
854
855                 
856
857 \end{code}
858
859 Note [Type synonyms and canonicalization]
860 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
861
862 We treat type synonym applications as xi types, that is, they do not
863 count as type function applications.  However, we do need to be a bit
864 careful with type synonyms: like type functions they may not be
865 generative or injective.  However, unlike type functions, they are
866 parametric, so there is no problem in expanding them whenever we see
867 them, since we do not need to know anything about their arguments in
868 order to expand them; this is what justifies not having to treat them
869 as specially as type function applications.  The thing that causes
870 some subtleties is that we prefer to leave type synonym applications
871 *unexpanded* whenever possible, in order to generate better error
872 messages.
873
874 If we encounter an equality constraint with type synonym applications
875 on both sides, or a type synonym application on one side and some sort
876 of type application on the other, we simply must expand out the type
877 synonyms in order to continue decomposing the equality constraint into
878 primitive equality constraints.  For example, suppose we have
879
880   type F a = [Int]
881
882 and we encounter the equality
883
884   F a ~ [b]
885
886 In order to continue we must expand F a into [Int], giving us the
887 equality
888
889   [Int] ~ [b]
890
891 which we can then decompose into the more primitive equality
892 constraint
893
894   Int ~ b.
895
896 However, if we encounter an equality constraint with a type synonym
897 application on one side and a variable on the other side, we should
898 NOT (necessarily) expand the type synonym, since for the purpose of
899 good error messages we want to leave type synonyms unexpanded as much
900 as possible.
901
902 However, there is a subtle point with type synonyms and the occurs
903 check that takes place for equality constraints of the form tv ~ xi.
904 As an example, suppose we have
905
906   type F a = Int
907
908 and we come across the equality constraint
909
910   a ~ F a
911
912 This should not actually fail the occurs check, since expanding out
913 the type synonym results in the legitimate equality constraint a ~
914 Int.  We must actually do this expansion, because unifying a with F a
915 will lead the type checker into infinite loops later.  Put another
916 way, canonical equality constraints should never *syntactically*
917 contain the LHS variable in the RHS type.  However, we don't always
918 need to expand type synonyms when doing an occurs check; for example,
919 the constraint
920
921   a ~ F b
922
923 is obviously fine no matter what F expands to. And in this case we
924 would rather unify a with F b (rather than F b's expansion) in order
925 to get better error messages later.
926
927 So, when doing an occurs check with a type synonym application on the
928 RHS, we use some heuristics to find an expansion of the RHS which does
929 not contain the variable from the LHS.  In particular, given
930
931   a ~ F t1 ... tn
932
933 we first try expanding each of the ti to types which no longer contain
934 a.  If this turns out to be impossible, we next try expanding F
935 itself, and so on.
936
937
938