Fix another fundep error (fixes Trac #4969)
[ghc-hetmet.git] / compiler / typecheck / TcUnify.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Type subsumption and unification
7
8 \begin{code}
9 module TcUnify (
10         -- Full-blown subsumption
11   tcWrapResult, tcSubType, tcGen, 
12   checkConstraints, newImplication, sigCtxt,
13
14         -- Various unifications
15   unifyType, unifyTypeList, unifyTheta, unifyKind, 
16
17   --------------------------------
18   -- Holes
19   tcInfer, 
20   matchExpectedListTy, matchExpectedPArrTy, 
21   matchExpectedTyConApp, matchExpectedAppTy, 
22   matchExpectedFunTys, matchExpectedFunKind,
23   wrapFunResCoercion
24   ) where
25
26 #include "HsVersions.h"
27
28 import HsSyn
29 import TypeRep
30 import CoreUtils( mkPiTypes )
31 import TcErrors ( unifyCtxt )
32 import TcMType
33 import TcIface
34 import TcRnMonad
35 import TcType
36 import Type
37 import Coercion
38 import Inst
39 import TyCon
40 import TysWiredIn
41 import Var
42 import VarSet
43 import VarEnv
44 import Name
45 import ErrUtils
46 import BasicTypes
47
48 import Maybes ( allMaybes )  
49 import Util
50 import Outputable
51 import FastString
52
53 import Control.Monad
54 \end{code}
55
56
57 %************************************************************************
58 %*                                                                      *
59              matchExpected functions
60 %*                                                                      *
61 %************************************************************************
62
63 Note [Herald for matchExpectedFunTys]
64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65 The 'herald' always looks like:
66    "The equation(s) for 'f' have"
67    "The abstraction (\x.e) takes"
68    "The section (+ x) expects"
69    "The function 'f' is applied to"
70
71 This is used to construct a message of form
72
73    The abstraction `\Just 1 -> ...' takes two arguments
74    but its type `Maybe a -> a' has only one
75
76    The equation(s) for `f' have two arguments
77    but its type `Maybe a -> a' has only one
78
79    The section `(f 3)' requires 'f' to take two arguments
80    but its type `Int -> Int' has only one
81
82    The function 'f' is applied to two arguments
83    but its type `Int -> Int' has only one
84
85 Note [matchExpectedFunTys]
86 ~~~~~~~~~~~~~~~~~~~~~~~~~~
87 matchExpectedFunTys checks that an (Expected rho) has the form
88 of an n-ary function.  It passes the decomposed type to the
89 thing_inside, and returns a wrapper to coerce between the two types
90
91 It's used wherever a language construct must have a functional type,
92 namely:
93         A lambda expression
94         A function definition
95      An operator section
96
97 This is not (currently) where deep skolemisation occurs;
98 matchExpectedFunTys does not skolmise nested foralls in the 
99 expected type, becuase it expects that to have been done already
100
101
102 \begin{code}
103 matchExpectedFunTys :: SDoc     -- See Note [Herald for matchExpectedFunTys]
104                     -> Arity
105                     -> TcRhoType 
106                     -> TcM (CoercionI, [TcSigmaType], TcRhoType)                        
107
108 -- If    matchExpectFunTys n ty = (co, [t1,..,tn], ty_r)
109 -- then  co : ty ~ (t1 -> ... -> tn -> ty_r)
110 --
111 -- Does not allocate unnecessary meta variables: if the input already is 
112 -- a function, we just take it apart.  Not only is this efficient, 
113 -- it's important for higher rank: the argument might be of form
114 --              (forall a. ty) -> other
115 -- If allocated (fresh-meta-var1 -> fresh-meta-var2) and unified, we'd
116 -- hide the forall inside a meta-variable
117
118 matchExpectedFunTys herald arity orig_ty 
119   = go arity orig_ty
120   where
121     -- If     go n ty = (co, [t1,..,tn], ty_r)
122     -- then   co : ty ~ t1 -> .. -> tn -> ty_r
123
124     go n_req ty
125       | n_req == 0 = return (IdCo ty, [], ty)
126
127     go n_req ty
128       | Just ty' <- tcView ty = go n_req ty'
129
130     go n_req (FunTy arg_ty res_ty)
131       | not (isPredTy arg_ty) 
132       = do { (coi, tys, ty_r) <- go (n_req-1) res_ty
133            ; return (mkFunTyCoI (IdCo arg_ty) coi, arg_ty:tys, ty_r) }
134
135     go _ (TyConApp tc _)              -- A common case
136       | not (isSynFamilyTyCon tc)
137       = do { (env,msg) <- mk_ctxt emptyTidyEnv
138            ; failWithTcM (env,msg) }
139
140     go n_req ty@(TyVarTy tv)
141       | ASSERT( isTcTyVar tv) isMetaTyVar tv
142       = do { cts <- readMetaTyVar tv
143            ; case cts of
144                Indirect ty' -> go n_req ty'
145                Flexi        -> defer n_req ty }
146
147        -- In all other cases we bale out into ordinary unification
148     go n_req ty = defer n_req ty
149
150     ------------
151     defer n_req fun_ty 
152       = addErrCtxtM mk_ctxt $
153         do { arg_tys <- newFlexiTyVarTys n_req argTypeKind
154            ; res_ty  <- newFlexiTyVarTy openTypeKind
155            ; coi     <- unifyType fun_ty (mkFunTys arg_tys res_ty)
156            ; return (coi, arg_tys, res_ty) }
157
158     ------------
159     mk_ctxt :: TidyEnv -> TcM (TidyEnv, Message)
160     mk_ctxt env = do { orig_ty1 <- zonkTcType orig_ty
161                      ; let (env', orig_ty2) = tidyOpenType env orig_ty1
162                            (args, _) = tcSplitFunTys orig_ty2
163                            n_actual = length args
164                      ; return (env', mk_msg orig_ty2 n_actual) }
165
166     mk_msg ty n_args
167       = herald <+> speakNOf arity (ptext (sLit "argument")) <> comma $$ 
168         sep [ptext (sLit "but its type") <+> quotes (pprType ty), 
169              if n_args == 0 then ptext (sLit "has none") 
170              else ptext (sLit "has only") <+> speakN n_args]
171 \end{code}
172
173
174 \begin{code}
175 ----------------------
176 matchExpectedListTy :: TcRhoType -> TcM (CoercionI, TcRhoType)
177 -- Special case for lists
178 matchExpectedListTy exp_ty
179  = do { (coi, [elt_ty]) <- matchExpectedTyConApp listTyCon exp_ty
180       ; return (coi, elt_ty) }
181
182 ----------------------
183 matchExpectedPArrTy :: TcRhoType -> TcM (CoercionI, TcRhoType)
184 -- Special case for parrs
185 matchExpectedPArrTy exp_ty
186   = do { (coi, [elt_ty]) <- matchExpectedTyConApp parrTyCon exp_ty
187        ; return (coi, elt_ty) }
188
189 ----------------------
190 matchExpectedTyConApp :: TyCon                -- T :: k1 -> ... -> kn -> *
191                       -> TcRhoType            -- orig_ty
192                       -> TcM (CoercionI,      -- T a b c ~ orig_ty
193                               [TcSigmaType])  -- Element types, a b c
194                               
195 -- It's used for wired-in tycons, so we call checkWiredInTyCon
196 -- Precondition: never called with FunTyCon
197 -- Precondition: input type :: *
198
199 matchExpectedTyConApp tc orig_ty
200   = do  { checkWiredInTyCon tc
201         ; go (tyConArity tc) orig_ty [] }
202   where
203     go :: Int -> TcRhoType -> [TcSigmaType] -> TcM (CoercionI, [TcSigmaType])
204     -- If     go n ty tys = (co, [t1..tn] ++ tys)
205     -- then   co : T t1..tn ~ ty
206
207     go n_req ty tys
208       | Just ty' <- tcView ty = go n_req ty' tys
209
210     go n_req ty@(TyVarTy tv) tys
211       | ASSERT( isTcTyVar tv) isMetaTyVar tv
212       = do { cts <- readMetaTyVar tv
213            ; case cts of
214                Indirect ty -> go n_req ty tys
215                Flexi       -> defer n_req ty tys }
216
217     go n_req ty@(TyConApp tycon args) tys
218       | tc == tycon
219       = ASSERT( n_req == length args)   -- ty::*
220         return (IdCo ty, args ++ tys)
221
222     go n_req (AppTy fun arg) tys
223       | n_req > 0
224       = do { (coi, args) <- go (n_req - 1) fun (arg : tys) 
225            ; return (mkAppTyCoI coi (IdCo arg), args) }
226
227     go n_req ty tys = defer n_req ty tys
228
229     ----------
230     defer n_req ty tys
231       = do { tau_tys <- mapM newFlexiTyVarTy arg_kinds
232            ; coi <- unifyType (mkTyConApp tc tau_tys) ty
233            ; return (coi, tau_tys ++ tys) }
234       where
235         (arg_kinds, _) = splitKindFunTysN n_req (tyConKind tc)
236
237 ----------------------
238 matchExpectedAppTy :: TcRhoType                         -- orig_ty
239                    -> TcM (CoercionI,                   -- m a ~ orig_ty
240                            (TcSigmaType, TcSigmaType))  -- Returns m, a
241 -- If the incoming type is a mutable type variable of kind k, then
242 -- matchExpectedAppTy returns a new type variable (m: * -> k); note the *.
243
244 matchExpectedAppTy orig_ty
245   = go orig_ty
246   where
247     go ty
248       | Just ty' <- tcView ty = go ty'
249
250       | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
251       = return (IdCo orig_ty, (fun_ty, arg_ty))
252
253     go (TyVarTy tv)
254       | ASSERT( isTcTyVar tv) isMetaTyVar tv
255       = do { cts <- readMetaTyVar tv
256            ; case cts of
257                Indirect ty -> go ty
258                Flexi       -> defer }
259
260     go _ = defer
261
262     -- Defer splitting by generating an equality constraint
263     defer = do { ty1 <- newFlexiTyVarTy kind1
264                ; ty2 <- newFlexiTyVarTy kind2
265                ; coi <- unifyType (mkAppTy ty1 ty2) orig_ty
266                ; return (coi, (ty1, ty2)) }
267
268     orig_kind = typeKind orig_ty
269     kind1 = mkArrowKind liftedTypeKind (defaultKind orig_kind)
270     kind2 = liftedTypeKind    -- m :: * -> k
271                               -- arg type :: *
272         -- The defaultKind is a bit smelly.  If you remove it,
273         -- try compiling        f x = do { x }
274         -- and you'll get a kind mis-match.  It smells, but
275         -- not enough to lose sleep over.
276 \end{code}
277
278
279 %************************************************************************
280 %*                                                                      *
281                 Subsumption checking
282 %*                                                                      *
283 %************************************************************************
284
285 All the tcSub calls have the form
286                 tcSub actual_ty expected_ty
287 which checks
288                 actual_ty <= expected_ty
289
290 That is, that a value of type actual_ty is acceptable in
291 a place expecting a value of type expected_ty.
292
293 It returns a coercion function
294         co_fn :: actual_ty ~ expected_ty
295 which takes an HsExpr of type actual_ty into one of type
296 expected_ty.
297
298 \begin{code}
299 tcSubType :: CtOrigin -> UserTypeCtxt -> TcSigmaType -> TcSigmaType -> TcM HsWrapper
300 -- Check that ty_actual is more polymorphic than ty_expected
301 -- Both arguments might be polytypes, so we must instantiate and skolemise
302 -- Returns a wrapper of shape   ty_actual ~ ty_expected
303 tcSubType origin ctxt ty_actual ty_expected
304   | isSigmaTy ty_actual
305   = do { (sk_wrap, inst_wrap) 
306             <- tcGen ctxt ty_expected $ \ _ sk_rho -> do
307             { (in_wrap, in_rho) <- deeplyInstantiate origin ty_actual
308             ; coi <- unifyType in_rho sk_rho
309             ; return (coiToHsWrapper coi <.> in_wrap) }
310        ; return (sk_wrap <.> inst_wrap) }
311
312   | otherwise   -- Urgh!  It seems deeply weird to have equality
313                 -- when actual is not a polytype, and it makes a big 
314                 -- difference e.g. tcfail104
315   = do { coi <- unifyType ty_actual ty_expected
316        ; return (coiToHsWrapper coi) }
317   
318 tcInfer :: (TcType -> TcM a) -> TcM (a, TcType)
319 tcInfer tc_infer = do { ty  <- newFlexiTyVarTy openTypeKind
320                       ; res <- tc_infer ty
321                       ; return (res, ty) }
322
323 -----------------
324 tcWrapResult :: HsExpr TcId -> TcRhoType -> TcRhoType -> TcM (HsExpr TcId)
325 tcWrapResult expr actual_ty res_ty
326   = do { coi <- unifyType actual_ty res_ty
327                 -- Both types are deeply skolemised
328        ; return (mkHsWrapCoI coi expr) }
329
330 -----------------------------------
331 wrapFunResCoercion
332         :: [TcType]     -- Type of args
333         -> HsWrapper    -- HsExpr a -> HsExpr b
334         -> TcM HsWrapper        -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
335 wrapFunResCoercion arg_tys co_fn_res
336   | isIdHsWrapper co_fn_res
337   = return idHsWrapper
338   | null arg_tys
339   = return co_fn_res
340   | otherwise
341   = do  { arg_ids <- newSysLocalIds (fsLit "sub") arg_tys
342         ; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpEvVarApps arg_ids) }
343 \end{code}
344
345
346
347 %************************************************************************
348 %*                                                                      *
349 \subsection{Generalisation}
350 %*                                                                      *
351 %************************************************************************
352
353 \begin{code}
354 tcGen :: UserTypeCtxt -> TcType
355       -> ([TcTyVar] -> TcRhoType -> TcM result)
356       -> TcM (HsWrapper, result)
357         -- The expression has type: spec_ty -> expected_ty
358
359 tcGen ctxt expected_ty thing_inside
360    -- We expect expected_ty to be a forall-type
361    -- If not, the call is a no-op
362   = do  { traceTc "tcGen" empty
363         ; (wrap, tvs', given, rho') <- deeplySkolemise expected_ty
364
365         ; when debugIsOn $
366               traceTc "tcGen" $ vcat [
367                            text "expected_ty" <+> ppr expected_ty,
368                            text "inst ty" <+> ppr tvs' <+> ppr rho' ]
369
370         -- Generally we must check that the "forall_tvs" havn't been constrained
371         -- The interesting bit here is that we must include the free variables
372         -- of the expected_ty.  Here's an example:
373         --       runST (newVar True)
374         -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
375         -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
376         -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
377         -- So now s' isn't unconstrained because it's linked to a.
378         -- 
379         -- However [Oct 10] now that the untouchables are a range of 
380         -- TcTyVars, all this is handled automatically with no need for
381         -- extra faffing around
382
383         -- Use the *instantiated* type in the SkolemInfo
384         -- so that the names of displayed type variables line up
385         ; let skol_info = SigSkol ctxt (mkPiTypes given rho')
386
387         ; (ev_binds, result) <- checkConstraints skol_info tvs' given $
388                                 thing_inside tvs' rho'
389
390         ; return (wrap <.> mkWpLet ev_binds, result) }
391           -- The ev_binds returned by checkConstraints is very
392           -- often empty, in which case mkWpLet is a no-op
393
394 checkConstraints :: SkolemInfo
395                  -> [TcTyVar]           -- Skolems
396                  -> [EvVar]             -- Given
397                  -> TcM result
398                  -> TcM (TcEvBinds, result)
399
400 checkConstraints skol_info skol_tvs given thing_inside
401   | null skol_tvs && null given
402   = do { res <- thing_inside; return (emptyTcEvBinds, res) }
403       -- Just for efficiency.  We check every function argument with
404       -- tcPolyExpr, which uses tcGen and hence checkConstraints.
405
406   | otherwise
407   = newImplication skol_info skol_tvs given thing_inside
408
409 newImplication :: SkolemInfo -> [TcTyVar]
410                -> [EvVar] -> TcM result
411                -> TcM (TcEvBinds, result)
412 newImplication skol_info skol_tvs given thing_inside
413   = ASSERT2( all isTcTyVar skol_tvs, ppr skol_tvs )
414     ASSERT2( all isSkolemTyVar skol_tvs, ppr skol_tvs )
415     do { ((result, untch), wanted) <- captureConstraints  $ 
416                                       captureUntouchables $
417                                       thing_inside
418
419        ; if isEmptyWC wanted && not (hasEqualities given)
420             -- Optimisation : if there are no wanteds, and the givens
421             -- are sufficiently simple, don't generate an implication
422             -- at all.  Reason for the hasEqualities test:
423             -- we don't want to lose the "inaccessible alternative"
424             -- error check
425          then 
426             return (emptyTcEvBinds, result)
427          else do
428        { ev_binds_var <- newTcEvBinds
429        ; lcl_env <- getLclTypeEnv
430        ; loc <- getCtLoc skol_info
431        ; emitImplication $ Implic { ic_untch = untch
432                                   , ic_env = lcl_env
433                                   , ic_skols = mkVarSet skol_tvs
434                                   , ic_given = given
435                                   , ic_wanted = wanted
436                                   , ic_insol  = insolubleWC wanted
437                                   , ic_binds = ev_binds_var
438                                   , ic_loc = loc }
439
440        ; return (TcEvBinds ev_binds_var, result) } }
441 \end{code}
442
443 %************************************************************************
444 %*                                                                      *
445                 Boxy unification
446 %*                                                                      *
447 %************************************************************************
448
449 The exported functions are all defined as versions of some
450 non-exported generic functions.
451
452 \begin{code}
453 ---------------
454 unifyType :: TcTauType -> TcTauType -> TcM CoercionI
455 -- Actual and expected types
456 -- Returns a coercion : ty1 ~ ty2
457 unifyType ty1 ty2 = uType [] ty1 ty2
458
459 ---------------
460 unifyPred :: PredType -> PredType -> TcM CoercionI
461 -- Actual and expected types
462 unifyPred p1 p2 = uPred [UnifyOrigin (mkPredTy p1) (mkPredTy p2)] p1 p2
463
464 ---------------
465 unifyTheta :: TcThetaType -> TcThetaType -> TcM [CoercionI]
466 -- Actual and expected types
467 unifyTheta theta1 theta2
468   = do  { checkTc (equalLength theta1 theta2)
469                   (vcat [ptext (sLit "Contexts differ in length"),
470                          nest 2 $ parens $ ptext (sLit "Use -XRelaxedPolyRec to allow this")])
471         ; zipWithM unifyPred theta1 theta2 }
472 \end{code}
473
474 @unifyTypeList@ takes a single list of @TauType@s and unifies them
475 all together.  It is used, for example, when typechecking explicit
476 lists, when all the elts should be of the same type.
477
478 \begin{code}
479 unifyTypeList :: [TcTauType] -> TcM ()
480 unifyTypeList []                 = return ()
481 unifyTypeList [_]                = return ()
482 unifyTypeList (ty1:tys@(ty2:_)) = do { _ <- unifyType ty1 ty2
483                                      ; unifyTypeList tys }
484 \end{code}
485
486 %************************************************************************
487 %*                                                                      *
488                  uType and friends                                                                      
489 %*                                                                      *
490 %************************************************************************
491
492 uType is the heart of the unifier.  Each arg occurs twice, because
493 we want to report errors in terms of synomyms if possible.  The first of
494 the pair is used in error messages only; it is always the same as the
495 second, except that if the first is a synonym then the second may be a
496 de-synonym'd version.  This way we get better error messages.
497
498 \begin{code}
499 data SwapFlag 
500   = NotSwapped  -- Args are: actual,   expected
501   | IsSwapped   -- Args are: expected, actual
502
503 instance Outputable SwapFlag where
504   ppr IsSwapped  = ptext (sLit "Is-swapped")
505   ppr NotSwapped = ptext (sLit "Not-swapped")
506
507 unSwap :: SwapFlag -> (a->a->b) -> a -> a -> b
508 unSwap NotSwapped f a b = f a b
509 unSwap IsSwapped  f a b = f b a
510
511 ------------
512 uType, uType_np, uType_defer
513   :: [EqOrigin]
514   -> TcType    -- ty1 is the *actual* type
515   -> TcType    -- ty2 is the *expected* type
516   -> TcM CoercionI
517
518 --------------
519 -- It is always safe to defer unification to the main constraint solver
520 -- See Note [Deferred unification]
521 uType_defer (item : origin) ty1 ty2
522   = wrapEqCtxt origin $
523     do { co_var <- newCoVar ty1 ty2
524        ; loc <- getCtLoc (TypeEqOrigin item)
525        ; emitFlat (mkEvVarX co_var loc)
526
527        -- Error trace only
528        ; ctxt <- getErrCtxt
529        ; doc <- mkErrInfo emptyTidyEnv ctxt
530        ; traceTc "utype_defer" (vcat [ppr co_var, ppr ty1, ppr ty2, ppr origin, doc])
531
532        ; return $ ACo $ mkTyVarTy co_var }
533 uType_defer [] _ _
534   = panic "uType_defer"
535
536 --------------
537 -- Push a new item on the origin stack (the most common case)
538 uType origin ty1 ty2  -- Push a new item on the origin stack
539   = uType_np (pushOrigin ty1 ty2 origin) ty1 ty2
540
541 --------------
542 -- unify_np (short for "no push" on the origin stack) does the work
543 uType_np origin orig_ty1 orig_ty2
544   = do { traceTc "u_tys " $ vcat 
545               [ sep [ ppr orig_ty1, text "~", ppr orig_ty2]
546               , ppr origin]
547        ; coi <- go orig_ty1 orig_ty2
548        ; case coi of
549             ACo co -> traceTc "u_tys yields coercion:" (ppr co)
550             IdCo _ -> traceTc "u_tys yields no coercion" empty
551        ; return coi }
552   where
553     bale_out :: [EqOrigin] -> TcM a
554     bale_out origin = failWithMisMatch origin
555
556     go :: TcType -> TcType -> TcM CoercionI
557         -- The arguments to 'go' are always semantically identical 
558         -- to orig_ty{1,2} except for looking through type synonyms
559
560         -- Variables; go for uVar
561         -- Note that we pass in *original* (before synonym expansion), 
562         -- so that type variables tend to get filled in with 
563         -- the most informative version of the type
564     go (TyVarTy tyvar1) ty2 = uVar origin NotSwapped tyvar1 ty2
565     go ty1 (TyVarTy tyvar2) = uVar origin IsSwapped  tyvar2 ty1
566
567         -- Expand synonyms: 
568         --      see Note [Unification and synonyms]
569         -- Do this after the variable case so that we tend to unify
570         -- variables with un-expanded type synonym
571         --
572         -- Also NB that we recurse to 'go' so that we don't push a
573         -- new item on the origin stack. As a result if we have
574         --   type Foo = Int
575         -- and we try to unify  Foo ~ Bool
576         -- we'll end up saying "can't match Foo with Bool"
577         -- rather than "can't match "Int with Bool".  See Trac #4535.
578     go ty1 ty2
579       | Just ty1' <- tcView ty1 = go ty1' ty2
580       | Just ty2' <- tcView ty2 = go ty1  ty2'
581              
582
583         -- Predicates
584     go (PredTy p1) (PredTy p2) = uPred origin p1 p2
585
586         -- Coercion functions: (t1a ~ t1b) => t1c  ~  (t2a ~ t2b) => t2c
587     go ty1 ty2 
588       | Just (t1a,t1b,t1c) <- splitCoPredTy_maybe ty1, 
589         Just (t2a,t2b,t2c) <- splitCoPredTy_maybe ty2
590       = do { co1 <- uType origin t1a t2a 
591            ; co2 <- uType origin t1b t2b
592            ; co3 <- uType origin t1c t2c 
593            ; return $ mkCoPredCoI co1 co2 co3 }
594
595         -- Functions (or predicate functions) just check the two parts
596     go (FunTy fun1 arg1) (FunTy fun2 arg2)
597       = do { coi_l <- uType origin fun1 fun2
598            ; coi_r <- uType origin arg1 arg2
599            ; return $ mkFunTyCoI coi_l coi_r }
600
601         -- Always defer if a type synonym family (type function)
602         -- is involved.  (Data families behave rigidly.)
603     go ty1@(TyConApp tc1 _) ty2
604       | isSynFamilyTyCon tc1 = uType_defer origin ty1 ty2   
605     go ty1 ty2@(TyConApp tc2 _)
606       | isSynFamilyTyCon tc2 = uType_defer origin ty1 ty2   
607
608     go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
609       | tc1 == tc2         -- See Note [TyCon app]
610       = do { cois <- uList origin uType tys1 tys2
611            ; return $ mkTyConAppCoI tc1 cois }
612      
613         -- See Note [Care with type applications]
614     go (AppTy s1 t1) ty2
615       | Just (s2,t2) <- tcSplitAppTy_maybe ty2
616       = do { coi_s <- uType_np origin s1 s2  -- See Note [Unifying AppTy]
617            ; coi_t <- uType origin t1 t2        
618            ; return $ mkAppTyCoI coi_s coi_t }
619
620     go ty1 (AppTy s2 t2)
621       | Just (s1,t1) <- tcSplitAppTy_maybe ty1
622       = do { coi_s <- uType_np origin s1 s2
623            ; coi_t <- uType origin t1 t2
624            ; return $ mkAppTyCoI coi_s coi_t }
625
626     go ty1 ty2
627       | tcIsForAllTy ty1 || tcIsForAllTy ty2 
628       = unifySigmaTy origin ty1 ty2
629
630         -- Anything else fails
631     go _ _ = bale_out origin
632
633 unifySigmaTy :: [EqOrigin] -> TcType -> TcType -> TcM CoercionI
634 unifySigmaTy origin ty1 ty2
635   = do { let (tvs1, body1) = tcSplitForAllTys ty1
636              (tvs2, body2) = tcSplitForAllTys ty2
637        ; unless (equalLength tvs1 tvs2) (failWithMisMatch origin)
638        ; skol_tvs <- tcInstSkolTyVars tvs1
639                   -- Get location from monad, not from tvs1
640        ; let tys      = mkTyVarTys skol_tvs
641              in_scope = mkInScopeSet (mkVarSet skol_tvs)
642              phi1     = substTy (mkTvSubst in_scope (zipTyEnv tvs1 tys)) body1
643              phi2     = substTy (mkTvSubst in_scope (zipTyEnv tvs2 tys)) body2
644 --             untch = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
645
646        ; ((coi, _untch), lie) <- captureConstraints $ 
647                                  captureUntouchables $ 
648                                  uType origin phi1 phi2
649           -- Check for escape; e.g. (forall a. a->b) ~ (forall a. a->a)
650           -- VERY UNSATISFACTORY; the constraint might be fine, but
651           -- we fail eagerly because we don't have any place to put 
652           -- the bindings from an implication constraint
653           -- This only works because most constraints get solved on the fly
654           -- See Note [Avoid deferring]
655          ; when (any (`elemVarSet` tyVarsOfWC lie) skol_tvs)
656               (failWithMisMatch origin) -- ToDo: give details from bad_lie
657
658        ; emitConstraints lie
659        ; return (foldr mkForAllTyCoI coi skol_tvs) }
660
661 ----------
662 uPred :: [EqOrigin] -> PredType -> PredType -> TcM CoercionI
663 uPred origin (IParam n1 t1) (IParam n2 t2)
664   | n1 == n2
665   = do { coi <- uType origin t1 t2
666        ; return $ mkIParamPredCoI n1 coi }
667 uPred origin (ClassP c1 tys1) (ClassP c2 tys2)
668   | c1 == c2 
669   = do { cois <- uList origin uType tys1 tys2
670           -- Guaranteed equal lengths because the kinds check
671        ; return $ mkClassPPredCoI c1 cois }
672 uPred origin (EqPred ty1a ty1b) (EqPred ty2a ty2b)
673   = do { coia <- uType origin ty1a ty2a
674        ; coib <- uType origin ty1b ty2b
675        ; return $ mkEqPredCoI coia coib }
676
677 uPred origin _ _ = failWithMisMatch origin
678
679 ---------------
680 uList :: [EqOrigin] 
681       -> ([EqOrigin] -> a -> a -> TcM b)
682       -> [a] -> [a] -> TcM [b]
683 -- Unify corresponding elements of two lists of types, which
684 -- should be of equal length.  We charge down the list explicitly so that
685 -- we can complain if their lengths differ.
686 uList _       _     []         []        = return []
687 uList origin unify (ty1:tys1) (ty2:tys2) = do { x  <- unify origin ty1 ty2;
688                                               ; xs <- uList origin unify tys1 tys2
689                                               ; return (x:xs) }
690 uList origin _ _ _ = failWithMisMatch origin
691        -- See Note [Mismatched type lists and application decomposition]
692
693 \end{code}
694
695 Note [Care with type applications]
696 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
697 Note: type applications need a bit of care!
698 They can match FunTy and TyConApp, so use splitAppTy_maybe
699 NB: we've already dealt with type variables and Notes,
700 so if one type is an App the other one jolly well better be too
701
702 Note [Unifying AppTy]
703 ~~~~~~~~~~~~~~~~~~~~~
704 Considerm unifying  (m Int) ~ (IO Int) where m is a unification variable 
705 that is now bound to (say) (Bool ->).  Then we want to report 
706      "Can't unify (Bool -> Int) with (IO Int)
707 and not 
708      "Can't unify ((->) Bool) with IO"
709 That is why we use the "_np" variant of uType, which does not alter the error
710 message.
711
712 Note [TyCon app]
713 ~~~~~~~~~~~~~~~~
714 When we find two TyConApps, the argument lists are guaranteed equal
715 length.  Reason: intially the kinds of the two types to be unified is
716 the same. The only way it can become not the same is when unifying two
717 AppTys (f1 a1)~(f2 a2).  In that case there can't be a TyConApp in
718 the f1,f2 (because it'd absorb the app).  If we unify f1~f2 first,
719 which we do, that ensures that f1,f2 have the same kind; and that
720 means a1,a2 have the same kind.  And now the argument repeats.
721
722 Note [Mismatched type lists and application decomposition]
723 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
724 When we find two TyConApps, you might think that the argument lists 
725 are guaranteed equal length.  But they aren't. Consider matching
726         w (T x) ~ Foo (T x y)
727 We do match (w ~ Foo) first, but in some circumstances we simply create
728 a deferred constraint; and then go ahead and match (T x ~ T x y).
729 This came up in Trac #3950.
730
731 So either 
732    (a) either we must check for identical argument kinds 
733        when decomposing applications,
734   
735    (b) or we must be prepared for ill-kinded unification sub-problems
736
737 Currently we adopt (b) since it seems more robust -- no need to maintain
738 a global invariant.
739
740 Note [Unification and synonyms]
741 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
742 If you are tempted to make a short cut on synonyms, as in this
743 pseudocode...
744
745    uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
746      = if (con1 == con2) then
747    -- Good news!  Same synonym constructors, so we can shortcut
748    -- by unifying their arguments and ignoring their expansions.
749    unifyTypepeLists args1 args2
750     else
751    -- Never mind.  Just expand them and try again
752    uTys ty1 ty2
753
754 then THINK AGAIN.  Here is the whole story, as detected and reported
755 by Chris Okasaki:
756
757 Here's a test program that should detect the problem:
758
759         type Bogus a = Int
760         x = (1 :: Bogus Char) :: Bogus Bool
761
762 The problem with [the attempted shortcut code] is that
763
764         con1 == con2
765
766 is not a sufficient condition to be able to use the shortcut!
767 You also need to know that the type synonym actually USES all
768 its arguments.  For example, consider the following type synonym
769 which does not use all its arguments.
770
771         type Bogus a = Int
772
773 If you ever tried unifying, say, (Bogus Char) with )Bogus Bool), the
774 unifier would blithely try to unify Char with Bool and would fail,
775 even though the expanded forms (both Int) should match. Similarly,
776 unifying (Bogus Char) with (Bogus t) would unnecessarily bind t to
777 Char.
778
779 ... You could explicitly test for the problem synonyms and mark them
780 somehow as needing expansion, perhaps also issuing a warning to the
781 user.
782
783 Note [Deferred Unification]
784 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
785 We may encounter a unification ty1 ~ ty2 that cannot be performed syntactically,
786 and yet its consistency is undetermined. Previously, there was no way to still
787 make it consistent. So a mismatch error was issued.
788
789 Now these unfications are deferred until constraint simplification, where type
790 family instances and given equations may (or may not) establish the consistency.
791 Deferred unifications are of the form
792                 F ... ~ ...
793 or              x ~ ...
794 where F is a type function and x is a type variable.
795 E.g.
796         id :: x ~ y => x -> y
797         id e = e
798
799 involves the unfication x = y. It is deferred until we bring into account the
800 context x ~ y to establish that it holds.
801
802 If available, we defer original types (rather than those where closed type
803 synonyms have already been expanded via tcCoreView).  This is, as usual, to
804 improve error messages.
805
806
807 %************************************************************************
808 %*                                                                      *
809                  uVar and friends
810 %*                                                                      *
811 %************************************************************************
812
813 @uVar@ is called when at least one of the types being unified is a
814 variable.  It does {\em not} assume that the variable is a fixed point
815 of the substitution; rather, notice that @uVar@ (defined below) nips
816 back into @uTys@ if it turns out that the variable is already bound.
817
818 \begin{code}
819 uVar :: [EqOrigin] -> SwapFlag -> TcTyVar -> TcTauType -> TcM CoercionI
820 uVar origin swapped tv1 ty2
821   = do  { traceTc "uVar" (vcat [ ppr origin
822                                 , ppr swapped
823                                 , ppr tv1 <+> dcolon <+> ppr (tyVarKind tv1)
824                                 , nest 2 (ptext (sLit " ~ "))
825                                 , ppr ty2 <+> dcolon <+> ppr (typeKind ty2)])
826         ; details <- lookupTcTyVar tv1
827         ; case details of
828             Filled ty1  -> unSwap swapped (uType_np origin) ty1 ty2
829             Unfilled details1 -> uUnfilledVar origin swapped tv1 details1 ty2
830         }
831
832 ----------------
833 uUnfilledVar :: [EqOrigin]
834              -> SwapFlag
835              -> TcTyVar -> TcTyVarDetails       -- Tyvar 1
836              -> TcTauType                       -- Type 2
837              -> TcM CoercionI
838 -- "Unfilled" means that the variable is definitely not a filled-in meta tyvar
839 --            It might be a skolem, or untouchable, or meta
840
841 uUnfilledVar origin swapped tv1 details1 (TyVarTy tv2)
842   | tv1 == tv2  -- Same type variable => no-op
843   = return (IdCo (mkTyVarTy tv1))
844
845   | otherwise  -- Distinct type variables
846   = do  { lookup2 <- lookupTcTyVar tv2
847         ; case lookup2 of
848             Filled ty2'       -> uUnfilledVar origin swapped tv1 details1 ty2' 
849             Unfilled details2 -> uUnfilledVars origin swapped tv1 details1 tv2 details2
850         }
851
852 uUnfilledVar origin swapped tv1 details1 non_var_ty2  -- ty2 is not a type variable
853   = case details1 of
854       MetaTv TauTv ref1 
855         -> do { mb_ty2' <- checkTauTvUpdate tv1 non_var_ty2
856               ; case mb_ty2' of
857                   Nothing   -> do { traceTc "Occ/kind defer" (ppr tv1); defer }
858                   Just ty2' -> updateMeta tv1 ref1 ty2'
859               }
860
861       _other -> do { traceTc "Skolem defer" (ppr tv1); defer }  -- Skolems of all sorts
862   where
863     defer | Just ty2' <- tcView non_var_ty2     -- Note [Avoid deferring]
864                                                 -- non_var_ty2 isn't expanded yet
865           = uUnfilledVar origin swapped tv1 details1 ty2'
866           | otherwise
867           = unSwap swapped (uType_defer origin) (mkTyVarTy tv1) non_var_ty2
868           -- Occurs check or an untouchable: just defer
869           -- NB: occurs check isn't necessarily fatal: 
870           --     eg tv1 occured in type family parameter
871
872 ----------------
873 uUnfilledVars :: [EqOrigin]
874               -> SwapFlag
875               -> TcTyVar -> TcTyVarDetails      -- Tyvar 1
876               -> TcTyVar -> TcTyVarDetails      -- Tyvar 2
877               -> TcM CoercionI
878 -- Invarant: The type variables are distinct,
879 --           Neither is filled in yet
880
881 uUnfilledVars origin swapped tv1 details1 tv2 details2
882   = case (details1, details2) of
883       (MetaTv i1 ref1, MetaTv i2 ref2)
884           | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1 i1 i2
885                          then updateMeta tv1 ref1 ty2
886                          else updateMeta tv2 ref2 ty1
887           | k2_sub_k1 -> updateMeta tv1 ref1 ty2
888
889       (_, MetaTv _ ref2) | k1_sub_k2 -> updateMeta tv2 ref2 ty1
890       (MetaTv _ ref1, _) | k2_sub_k1 -> updateMeta tv1 ref1 ty2
891
892       (_, _) -> unSwap swapped (uType_defer origin) ty1 ty2
893                 -- Defer for skolems of all sorts
894   where
895     k1        = tyVarKind tv1
896     k2        = tyVarKind tv2
897     k1_sub_k2 = k1 `isSubKind` k2
898     k2_sub_k1 = k2 `isSubKind` k1
899     ty1       = mkTyVarTy tv1
900     ty2       = mkTyVarTy tv2
901
902     nicer_to_update_tv1 _         (SigTv _) = True
903     nicer_to_update_tv1 (SigTv _) _         = False
904     nicer_to_update_tv1 _         _         = isSystemName (Var.varName tv1)
905         -- Try not to update SigTvs; and try to update sys-y type
906         -- variables in preference to ones gotten (say) by
907         -- instantiating a polymorphic function with a user-written
908         -- type sig
909
910 ----------------
911 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
912 --    (checkTauTvUpdate tv ty)
913 -- We are about to update the TauTv tv with ty.
914 -- Check (a) that tv doesn't occur in ty (occurs check)
915 --       (b) that kind(ty) is a sub-kind of kind(tv)
916 --       (c) that ty does not contain any type families, see Note [Type family sharing]
917 -- 
918 -- We have two possible outcomes:
919 -- (1) Return the type to update the type variable with, 
920 --        [we know the update is ok]
921 -- (2) Return Nothing,
922 --        [the update might be dodgy]
923 --
924 -- Note that "Nothing" does not mean "definite error".  For example
925 --   type family F a
926 --   type instance F Int = Int
927 -- consider
928 --   a ~ F a
929 -- This is perfectly reasonable, if we later get a ~ Int.  For now, though,
930 -- we return Nothing, leaving it to the later constraint simplifier to
931 -- sort matters out.
932
933 checkTauTvUpdate tv ty
934   = do { ty' <- zonkTcType ty
935        ; if typeKind ty' `isSubKind` tyVarKind tv then
936            case ok ty' of 
937              Nothing -> return Nothing 
938              Just ty'' -> return (Just ty'')
939          else return Nothing }
940
941   where ok :: TcType -> Maybe TcType 
942         ok (TyVarTy tv') | not (tv == tv') = Just (TyVarTy tv') 
943         ok this_ty@(TyConApp tc tys) 
944           | not (isSynFamilyTyCon tc), Just tys' <- allMaybes (map ok tys) 
945           = Just (TyConApp tc tys') 
946           | isSynTyCon tc, Just ty_expanded <- tcView this_ty
947           = ok ty_expanded -- See Note [Type synonyms and the occur check] 
948         ok (PredTy sty) | Just sty' <- ok_pred sty = Just (PredTy sty') 
949         ok (FunTy arg res) | Just arg' <- ok arg, Just res' <- ok res
950                            = Just (FunTy arg' res') 
951         ok (AppTy fun arg) | Just fun' <- ok fun, Just arg' <- ok arg 
952                            = Just (AppTy fun' arg') 
953         ok (ForAllTy tv1 ty1) | Just ty1' <- ok ty1 = Just (ForAllTy tv1 ty1') 
954         -- Fall-through 
955         ok _ty = Nothing 
956        
957         ok_pred (IParam nm ty) | Just ty' <- ok ty = Just (IParam nm ty') 
958         ok_pred (ClassP cl tys) 
959           | Just tys' <- allMaybes (map ok tys) 
960           = Just (ClassP cl tys') 
961         ok_pred (EqPred ty1 ty2) 
962           | Just ty1' <- ok ty1, Just ty2' <- ok ty2 
963           = Just (EqPred ty1' ty2') 
964         -- Fall-through 
965         ok_pred _pty = Nothing 
966 \end{code}
967
968 Note [Avoid deferring]
969 ~~~~~~~~~~~~~~~~~~~~~~
970 We try to avoid creating deferred constraints for two reasons.  
971   * First, efficiency.  
972   * Second, currently we can only defer some constraints 
973     under a forall.  See unifySigmaTy.
974 So expanding synonyms here is a good thing to do.  Example (Trac #4917)
975        a ~ Const a b
976 where type Const a b = a.  We can solve this immediately, even when
977 'a' is a skolem, just by expanding the synonym; and we should do so
978  in case this unification happens inside unifySigmaTy (sigh).
979
980 Note [Type synonyms and the occur check]
981 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
982 Generally speaking we try to update a variable with type synonyms not
983 expanded, which improves later error messages, unless looking
984 inside a type synonym may help resolve a spurious occurs check
985 error. Consider:
986           type A a = ()
987
988           f :: (A a -> a -> ()) -> ()
989           f = \ _ -> ()
990
991           x :: ()
992           x = f (\ x p -> p x)
993
994 We will eventually get a constraint of the form t ~ A t. The ok function above will 
995 properly expand the type (A t) to just (), which is ok to be unified with t. If we had
996 unified with the original type A t, we would lead the type checker into an infinite loop. 
997
998 Hence, if the occurs check fails for a type synonym application, then (and *only* then), 
999 the ok function expands the synonym to detect opportunities for occurs check success using
1000 the underlying definition of the type synonym. 
1001
1002 The same applies later on in the constraint interaction code; see TcInteract, 
1003 function @occ_check_ok@. 
1004
1005
1006 Note [Type family sharing]
1007 ~~~~~~~~~~~~~~ 
1008 We must avoid eagerly unifying type variables to types that contain function symbols, 
1009 because this may lead to loss of sharing, and in turn, in very poor performance of the
1010 constraint simplifier. Assume that we have a wanted constraint: 
1011
1012   m1 ~ [F m2], 
1013   m2 ~ [F m3], 
1014   m3 ~ [F m4], 
1015   D m1, 
1016   D m2, 
1017   D m3 
1018
1019 where D is some type class. If we eagerly unify m1 := [F m2], m2 := [F m3], m3 := [F m2], 
1020 then, after zonking, our constraint simplifier will be faced with the following wanted 
1021 constraint: 
1022
1023   D [F [F [F m4]]], 
1024   D [F [F m4]], 
1025   D [F m4] 
1026
1027 which has to be flattened by the constraint solver. However, because the sharing is lost, 
1028 an polynomially larger number of flatten skolems will be created and the constraint sets 
1029 we are working with will be polynomially larger. 
1030
1031 Instead, if we defer the unifications m1 := [F m2], etc. we will only be generating three 
1032 flatten skolems, which is the maximum possible sharing arising from the original constraint. 
1033
1034 \begin{code}
1035 data LookupTyVarResult  -- The result of a lookupTcTyVar call
1036   = Unfilled TcTyVarDetails     -- SkolemTv or virgin MetaTv
1037   | Filled   TcType
1038
1039 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
1040 lookupTcTyVar tyvar 
1041   | MetaTv _ ref <- details
1042   = do { meta_details <- readMutVar ref
1043        ; case meta_details of
1044            Indirect ty -> return (Filled ty)
1045            Flexi -> do { is_untch <- isUntouchable tyvar
1046                        ; let    -- Note [Unifying untouchables]
1047                              ret_details | is_untch  = vanillaSkolemTv
1048                                          | otherwise = details
1049                        ; return (Unfilled ret_details) } }
1050   | otherwise
1051   = return (Unfilled details)
1052   where
1053     details = ASSERT2( isTcTyVar tyvar, ppr tyvar )
1054               tcTyVarDetails tyvar
1055
1056 updateMeta :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM CoercionI
1057 updateMeta tv1 ref1 ty2
1058   = do { writeMetaTyVarRef tv1 ref1 ty2
1059        ; return (IdCo ty2) }
1060 \end{code}
1061
1062 Note [Unifying untouchables]
1063 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1064 We treat an untouchable type variable as if it was a skolem.  That
1065 ensures it won't unify with anything.  It's a slight had, because
1066 we return a made-up TcTyVarDetails, but I think it works smoothly.
1067
1068
1069 %************************************************************************
1070 %*                                                                      *
1071         Errors and contexts
1072 %*                                                                      *
1073 %************************************************************************
1074
1075 \begin{code}
1076 pushOrigin :: TcType -> TcType -> [EqOrigin] -> [EqOrigin]
1077 pushOrigin ty_act ty_exp origin
1078   = UnifyOrigin { uo_actual = ty_act, uo_expected = ty_exp } : origin
1079
1080 ---------------
1081 wrapEqCtxt :: [EqOrigin] -> TcM a -> TcM a
1082 -- Build a suitable error context from the origin and do the thing inside
1083 -- The "couldn't match" error comes from the innermost item on the stack,
1084 -- and, if there is more than one item, the "Expected/inferred" part
1085 -- comes from the outermost item
1086 wrapEqCtxt []    thing_inside = thing_inside
1087 wrapEqCtxt items thing_inside = addErrCtxtM (unifyCtxt (last items)) thing_inside
1088
1089 ---------------
1090 failWithMisMatch :: [EqOrigin] -> TcM a
1091 -- Generate the message when two types fail to match,
1092 -- going to some trouble to make it helpful.
1093 -- We take the failing types from the top of the origin stack
1094 -- rather than reporting the particular ones we are looking 
1095 -- at right now
1096 failWithMisMatch (item:origin)
1097   = wrapEqCtxt origin $
1098     do  { ty_act <- zonkTcType (uo_actual item)
1099         ; ty_exp <- zonkTcType (uo_expected item)
1100         ; env0 <- tcInitTidyEnv
1101         ; let (env1, pp_exp) = tidyOpenType env0 ty_exp
1102               (env2, pp_act) = tidyOpenType env1 ty_act
1103         ; failWithTcM (env2, misMatchMsg pp_act pp_exp) }
1104 failWithMisMatch [] 
1105   = panic "failWithMisMatch"
1106
1107 misMatchMsg :: TcType -> TcType -> SDoc
1108 misMatchMsg ty_act ty_exp
1109   = sep [ ptext (sLit "Couldn't match expected type") <+> quotes (ppr ty_exp)
1110         , nest 12 $   ptext (sLit "with actual type") <+> quotes (ppr ty_act)]
1111 \end{code}
1112
1113
1114 -----------------------------------------
1115         UNUSED FOR NOW
1116 -----------------------------------------
1117
1118 ----------------
1119 ----------------
1120 -- If an error happens we try to figure out whether the function
1121 -- function has been given too many or too few arguments, and say so.
1122 addSubCtxt :: InstOrigin -> TcType -> TcType -> TcM a -> TcM a
1123 addSubCtxt orig actual_res_ty expected_res_ty thing_inside
1124   = addErrCtxtM mk_err thing_inside
1125   where
1126     mk_err tidy_env
1127       = do { exp_ty' <- zonkTcType expected_res_ty
1128            ; act_ty' <- zonkTcType actual_res_ty
1129            ; let (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
1130                  (env2, act_ty'') = tidyOpenType env1     act_ty'
1131                  (exp_args, _)    = tcSplitFunTys exp_ty''
1132                  (act_args, _)    = tcSplitFunTys act_ty''
1133
1134                  len_act_args     = length act_args
1135                  len_exp_args     = length exp_args
1136
1137                  message = case orig of
1138                              OccurrenceOf fun
1139                                   | len_exp_args < len_act_args -> wrongArgsCtxt "too few"  fun
1140                                   | len_exp_args > len_act_args -> wrongArgsCtxt "too many" fun
1141                              _ -> mkExpectedActualMsg act_ty'' exp_ty''
1142            ; return (env2, message) }
1143
1144
1145 %************************************************************************
1146 %*                                                                      *
1147                 Kind unification
1148 %*                                                                      *
1149 %************************************************************************
1150
1151 Unifying kinds is much, much simpler than unifying types.
1152
1153 \begin{code}
1154 matchExpectedFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1155 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1156
1157 matchExpectedFunKind (TyVarTy kvar) = do
1158     maybe_kind <- readKindVar kvar
1159     case maybe_kind of
1160       Indirect fun_kind -> matchExpectedFunKind fun_kind
1161       Flexi ->
1162           do { arg_kind <- newKindVar
1163              ; res_kind <- newKindVar
1164              ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1165              ; return (Just (arg_kind,res_kind)) }
1166
1167 matchExpectedFunKind (FunTy arg_kind res_kind) = return (Just (arg_kind,res_kind))
1168 matchExpectedFunKind _                         = return Nothing
1169
1170 -----------------
1171 unifyKind :: TcKind                 -- Expected
1172           -> TcKind                 -- Actual
1173           -> TcM ()
1174
1175 unifyKind (TyConApp kc1 []) (TyConApp kc2 [])
1176   | isSubKindCon kc2 kc1 = return ()
1177
1178 unifyKind (FunTy a1 r1) (FunTy a2 r2)
1179   = do { unifyKind a2 a1; unifyKind r1 r2 }
1180                 -- Notice the flip in the argument,
1181                 -- so that the sub-kinding works right
1182 unifyKind (TyVarTy kv1) k2 = uKVar False kv1 k2
1183 unifyKind k1 (TyVarTy kv2) = uKVar True kv2 k1
1184 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1185
1186 ----------------
1187 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1188 uKVar swapped kv1 k2
1189   = do  { mb_k1 <- readKindVar kv1
1190         ; case mb_k1 of
1191             Flexi -> uUnboundKVar swapped kv1 k2
1192             Indirect k1 | swapped   -> unifyKind k2 k1
1193                         | otherwise -> unifyKind k1 k2 }
1194
1195 ----------------
1196 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1197 uUnboundKVar swapped kv1 k2@(TyVarTy kv2)
1198   | kv1 == kv2 = return ()
1199   | otherwise   -- Distinct kind variables
1200   = do  { mb_k2 <- readKindVar kv2
1201         ; case mb_k2 of
1202             Indirect k2 -> uUnboundKVar swapped kv1 k2
1203             Flexi -> writeKindVar kv1 k2 }
1204
1205 uUnboundKVar swapped kv1 non_var_k2
1206   = do  { k2' <- zonkTcKind non_var_k2
1207         ; kindOccurCheck kv1 k2'
1208         ; k2'' <- kindSimpleKind swapped k2'
1209                 -- KindVars must be bound only to simple kinds
1210                 -- Polarities: (kindSimpleKind True ?) succeeds
1211                 -- returning *, corresponding to unifying
1212                 --      expected: ?
1213                 --      actual:   kind-ver
1214         ; writeKindVar kv1 k2'' }
1215
1216 ----------------
1217 kindOccurCheck :: TyVar -> Type -> TcM ()
1218 kindOccurCheck kv1 k2   -- k2 is zonked
1219   = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1220   where
1221     not_in (TyVarTy kv2) = kv1 /= kv2
1222     not_in (FunTy a2 r2) = not_in a2 && not_in r2
1223     not_in _             = True
1224
1225 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1226 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1227 -- If the flag is False, it requires k <: sk
1228 -- E.g.         kindSimpleKind False ?? = *
1229 -- What about (kv -> *) ~ ?? -> *
1230 kindSimpleKind orig_swapped orig_kind
1231   = go orig_swapped orig_kind
1232   where
1233     go sw (FunTy k1 k2) = do { k1' <- go (not sw) k1
1234                              ; k2' <- go sw k2
1235                              ; return (mkArrowKind k1' k2') }
1236     go True k
1237      | isOpenTypeKind k = return liftedTypeKind
1238      | isArgTypeKind k  = return liftedTypeKind
1239     go _ k
1240      | isLiftedTypeKind k   = return liftedTypeKind
1241      | isUnliftedTypeKind k = return unliftedTypeKind
1242     go _ k@(TyVarTy _) = return k -- KindVars are always simple
1243     go _ _ = failWithTc (ptext (sLit "Unexpected kind unification failure:")
1244                                   <+> ppr orig_swapped <+> ppr orig_kind)
1245         -- I think this can't actually happen
1246
1247 -- T v = MkT v           v must be a type
1248 -- T v w = MkT (v -> w)  v must not be an umboxed tuple
1249
1250 unifyKindMisMatch :: TcKind -> TcKind -> TcM ()
1251 unifyKindMisMatch ty1 ty2 = do
1252     ty1' <- zonkTcKind ty1
1253     ty2' <- zonkTcKind ty2
1254     let
1255         msg = hang (ptext (sLit "Couldn't match kind"))
1256                    2 (sep [quotes (ppr ty1'), 
1257                            ptext (sLit "against"), 
1258                            quotes (ppr ty2')])
1259     failWithTc msg
1260
1261 ----------------
1262 kindOccurCheckErr :: Var -> Type -> SDoc
1263 kindOccurCheckErr tyvar ty
1264   = hang (ptext (sLit "Occurs check: cannot construct the infinite kind:"))
1265        2 (sep [ppr tyvar, char '=', ppr ty])
1266 \end{code}
1267
1268 %************************************************************************
1269 %*                                                                      *
1270 \subsection{Checking signature type variables}
1271 %*                                                                      *
1272 %************************************************************************
1273
1274 @checkSigTyVars@ checks that a set of universally quantified type varaibles
1275 are not mentioned in the environment.  In particular:
1276
1277         (a) Not mentioned in the type of a variable in the envt
1278                 eg the signature for f in this:
1279
1280                         g x = ... where
1281                                         f :: a->[a]
1282                                         f y = [x,y]
1283
1284                 Here, f is forced to be monorphic by the free occurence of x.
1285
1286         (d) Not (unified with another type variable that is) in scope.
1287                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1288             when checking the expression type signature, we find that
1289             even though there is nothing in scope whose type mentions r,
1290             nevertheless the type signature for the expression isn't right.
1291
1292             Another example is in a class or instance declaration:
1293                 class C a where
1294                    op :: forall b. a -> b
1295                    op x = x
1296             Here, b gets unified with a
1297
1298 Before doing this, the substitution is applied to the signature type variable.
1299
1300 -- \begin{code}
1301 checkSigTyVars :: [TcTyVar] -> TcM ()
1302 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1303
1304 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1305 -- The extra_tvs can include boxy type variables;
1306 --      e.g. TcMatches.tcCheckExistentialPat
1307 checkSigTyVarsWrt extra_tvs sig_tvs
1308   = do  { extra_tvs' <- zonkTcTyVarsAndFV extra_tvs
1309         ; check_sig_tyvars extra_tvs' sig_tvs }
1310
1311 check_sig_tyvars
1312         :: TcTyVarSet   -- Global type variables. The universally quantified
1313                         --      tyvars should not mention any of these
1314                         --      Guaranteed already zonked.
1315         -> [TcTyVar]    -- Universally-quantified type variables in the signature
1316                         --      Guaranteed to be skolems
1317         -> TcM ()
1318 check_sig_tyvars _ []
1319   = return ()
1320 check_sig_tyvars extra_tvs sig_tvs
1321   = ASSERT( all isTcTyVar sig_tvs && all isSkolemTyVar sig_tvs )
1322     do  { gbl_tvs <- tcGetGlobalTyVars
1323         ; traceTc "check_sig_tyvars" $ vcat 
1324                [ text "sig_tys" <+> ppr sig_tvs
1325                , text "gbl_tvs" <+> ppr gbl_tvs
1326                , text "extra_tvs" <+> ppr extra_tvs]
1327
1328         ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1329         ; when (any (`elemVarSet` env_tvs) sig_tvs)
1330                (bleatEscapedTvs env_tvs sig_tvs sig_tvs)
1331         }
1332
1333 bleatEscapedTvs :: TcTyVarSet   -- The global tvs
1334                 -> [TcTyVar]    -- The possibly-escaping type variables
1335                 -> [TcTyVar]    -- The zonked versions thereof
1336                 -> TcM ()
1337 -- Complain about escaping type variables
1338 -- We pass a list of type variables, at least one of which
1339 -- escapes.  The first list contains the original signature type variable,
1340 -- while the second  contains the type variable it is unified to (usually itself)
1341 bleatEscapedTvs globals sig_tvs zonked_tvs
1342   = do  { env0 <- tcInitTidyEnv
1343         ; let (env1, tidy_tvs)        = tidyOpenTyVars env0 sig_tvs
1344               (env2, tidy_zonked_tvs) = tidyOpenTyVars env1 zonked_tvs
1345
1346         ; (env3, msgs) <- foldlM check (env2, []) (tidy_tvs `zip` tidy_zonked_tvs)
1347         ; failWithTcM (env3, main_msg $$ nest 2 (vcat msgs)) }
1348   where
1349     main_msg = ptext (sLit "Inferred type is less polymorphic than expected")
1350
1351     check (tidy_env, msgs) (sig_tv, zonked_tv)
1352       | not (zonked_tv `elemVarSet` globals) = return (tidy_env, msgs)
1353       | otherwise
1354       = do { lcl_env <- getLclTypeEnv
1355            ; (tidy_env1, globs) <- findGlobals (unitVarSet zonked_tv) lcl_env tidy_env
1356            ; return (tidy_env1, escape_msg sig_tv zonked_tv globs : msgs) }
1357
1358 -----------------------
1359 escape_msg :: Var -> Var -> [SDoc] -> SDoc
1360 escape_msg sig_tv zonked_tv globs
1361   | notNull globs
1362   = vcat [sep [msg, ptext (sLit "is mentioned in the environment:")],
1363           nest 2 (vcat globs)]
1364   | otherwise
1365   = msg <+> ptext (sLit "escapes")
1366         -- Sigh.  It's really hard to give a good error message
1367         -- all the time.   One bad case is an existential pattern match.
1368         -- We rely on the "When..." context to help.
1369   where
1370     msg = ptext (sLit "Quantified type variable") <+> quotes (ppr sig_tv) <+> is_bound_to
1371     is_bound_to
1372         | sig_tv == zonked_tv = empty
1373         | otherwise = ptext (sLit "is unified with") <+> quotes (ppr zonked_tv) <+> ptext (sLit "which")
1374 -- \end{code}
1375
1376 These two context are used with checkSigTyVars
1377
1378 \begin{code}
1379 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1380         -> TidyEnv -> TcM (TidyEnv, Message)
1381 sigCtxt id sig_tvs sig_theta sig_tau tidy_env = do
1382     actual_tau <- zonkTcType sig_tau
1383     let
1384         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
1385         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1386         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1387         sub_msg = vcat [ptext (sLit "Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1388                         ptext (sLit "Type to generalise:") <+> pprType tidy_actual_tau
1389                    ]
1390         msg = vcat [ptext (sLit "When trying to generalise the type inferred for") <+> quotes (ppr id),
1391                     nest 2 sub_msg]
1392
1393     return (env3, msg)
1394 \end{code}