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