[project @ 2004-10-25 09:23:08 by simonmar]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcUnify.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Type subsumption and unification}
5
6 \begin{code}
7 module TcUnify (
8         -- Full-blown subsumption
9   tcSubPat, tcSubExp, tcGen, 
10   checkSigTyVars, checkSigTyVarsWrt, sigCtxt, findGlobals,
11
12         -- Various unifications
13   unifyTauTy, unifyTauTyList, 
14   unifyKind, unifyKinds, unifyFunKind, 
15   checkExpectedKind,
16
17   --------------------------------
18   -- Holes
19   Expected(..), tcInfer, readExpectedType, 
20   zapExpectedType, zapExpectedTo, zapExpectedBranches,
21   subFunTys,     unifyFunTys, 
22   zapToListTy,   unifyListTy, 
23   zapToTyConApp, unifyTyConApp,
24   unifyAppTy
25   ) where
26
27 #include "HsVersions.h"
28
29 -- gaw 2004
30 import HsSyn            ( HsExpr(..) , MatchGroup(..), hsLMatchPats )
31 import TcHsSyn          ( mkHsLet, mkHsDictLam,
32                           ExprCoFn, idCoercion, isIdCoercion, mkCoercion, (<.>), (<$>) )
33 import TypeRep          ( Type(..), PredType(..), TyNote(..) )
34
35 import TcRnMonad         -- TcType, amongst others
36 import TcType           ( TcKind, TcType, TcSigmaType, TcRhoType, TcTyVar, TcTauType,
37                           TcTyVarSet, TcThetaType, 
38                           SkolemInfo( GenSkol ), MetaDetails(..), 
39                           pprSkolemTyVar, isTauTy, isSigmaTy, mkFunTys, mkTyConApp,
40                           tcSplitAppTy_maybe, tcSplitTyConApp_maybe, 
41                           tyVarsOfType, mkPhiTy, mkTyVarTy, 
42                           typeKind, tcSplitFunTy_maybe, mkForAllTys, mkAppTy,
43                           tidyOpenType, tidyOpenTypes, tidyOpenTyVar, tidyOpenTyVars,
44                           pprType, isSkolemTyVar )
45 import Kind             ( Kind(..), SimpleKind, KindVar, isArgTypeKind,
46                           openTypeKind, liftedTypeKind, mkArrowKind, kindFunResult,
47                           isOpenTypeKind, argTypeKind, isLiftedTypeKind, isUnliftedTypeKind,
48                           isSubKind, pprKind, splitKindFunTys )
49 import Inst             ( newDicts, instToId, tcInstCall )
50 import TcMType          ( condLookupTcTyVar, LookupTyVarResult(..),
51                           putMetaTyVar, tcSkolType, newKindVar, tcInstTyVars, newMetaTyVar,
52                           newTyFlexiVarTy, zonkTcKind, 
53                           zonkType, zonkTcType, zonkTcTyVars, zonkTcTyVarsAndFV, 
54                           readKindVar, writeKindVar )
55 import TcSimplify       ( tcSimplifyCheck )
56 import TcEnv            ( tcGetGlobalTyVars, findGlobals )
57 import TyCon            ( TyCon, tyConArity, tyConTyVars )
58 import TysWiredIn       ( listTyCon )
59 import Id               ( Id, mkSysLocal )
60 import Var              ( Var, varName, tyVarKind )
61 import VarSet           ( emptyVarSet, unitVarSet, unionVarSet, elemVarSet, 
62                           varSetElems, intersectsVarSet, mkVarSet )
63 import VarEnv
64 import Name             ( isSystemName, mkSysTvName )
65 import ErrUtils         ( Message )
66 import SrcLoc           ( noLoc )
67 import BasicTypes       ( Arity )
68 import Util             ( notNull )
69 import Outputable
70 \end{code}
71
72 Notes on holes
73 ~~~~~~~~~~~~~~
74 * A hole is always filled in with an ordinary type, not another hole.
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{'hole' type variables}
79 %*                                                                      *
80 %************************************************************************
81
82 \begin{code}
83 data Expected ty = Infer (TcRef ty)     -- The hole to fill in for type inference
84                  | Check ty             -- The type to check during type checking
85
86 newHole = newMutVar (error "Empty hole in typechecker")
87
88 tcInfer :: (Expected ty -> TcM a) -> TcM (a,ty)
89 tcInfer tc_infer
90   = do  { hole <- newHole
91         ; res <- tc_infer (Infer hole)
92         ; res_ty <- readMutVar hole
93         ; return (res, res_ty) }
94
95 readExpectedType :: Expected ty -> TcM ty
96 readExpectedType (Infer hole) = readMutVar hole
97 readExpectedType (Check ty)   = returnM ty
98
99 zapExpectedType :: Expected TcType -> Kind -> TcM TcTauType
100 -- In the inference case, ensure we have a monotype
101 -- (including an unboxed tuple)
102 zapExpectedType (Infer hole) kind
103   = do { ty <- newTyFlexiVarTy kind ;
104          writeMutVar hole ty ;
105          return ty }
106
107 zapExpectedType (Check ty) kind 
108   | typeKind ty `isSubKind` kind = return ty
109   | otherwise                    = do { ty1 <- newTyFlexiVarTy kind
110                                       ; unifyTauTy ty1 ty
111                                       ; return ty }
112         -- The unify is to ensure that 'ty' has the desired kind
113         -- For example, in (case e of r -> b) we push an OpenTypeKind
114         -- type variable 
115
116 zapExpectedBranches :: MatchGroup id -> Expected TcRhoType -> TcM (Expected TcRhoType)
117 -- If there is more than one branch in a case expression, 
118 -- and exp_ty is a 'hole', all branches must be types, not type schemes, 
119 -- otherwise the order in which we check them would affect the result.
120 zapExpectedBranches (MatchGroup [match] _) exp_ty
121    = return exp_ty      -- One branch
122 zapExpectedBranches matches (Check ty)
123   = return (Check ty)
124 zapExpectedBranches matches (Infer hole)
125   = do  {       -- Many branches, and inference mode, 
126                 -- so switch to checking mode with a monotype
127           ty <- newTyFlexiVarTy openTypeKind
128         ; writeMutVar hole ty
129         ; return (Check ty) }
130
131 zapExpectedTo :: Expected TcType -> TcTauType -> TcM ()
132 zapExpectedTo (Check ty1)  ty2 = unifyTauTy ty1 ty2
133 zapExpectedTo (Infer hole) ty2 = do { ty2' <- zonkTcType ty2; writeMutVar hole ty2' }
134         -- See Note [Zonk return type]
135
136 instance Outputable ty => Outputable (Expected ty) where
137   ppr (Check ty)   = ptext SLIT("Expected type") <+> ppr ty
138   ppr (Infer hole) = ptext SLIT("Inferring type")
139 \end{code}                 
140
141
142 %************************************************************************
143 %*                                                                      *
144 \subsection[Unify-fun]{@unifyFunTy@}
145 %*                                                                      *
146 %************************************************************************
147
148 @subFunTy@ and @unifyFunTy@ is used to avoid the fruitless 
149 creation of type variables.
150
151 * subFunTy is used when we might be faced with a "hole" type variable,
152   in which case we should create two new holes. 
153
154 * unifyFunTy is used when we expect to encounter only "ordinary" 
155   type variables, so we should create new ordinary type variables
156
157 \begin{code}
158 subFunTys :: MatchGroup name
159           -> Expected TcRhoType         -- Fail if ty isn't a function type
160           -> ([Expected TcRhoType] -> Expected TcRhoType -> TcM a)
161           -> TcM a
162
163 subFunTys (MatchGroup (match:null_matches) _) (Infer hole) thing_inside
164   =     -- This is the interesting case
165     ASSERT( null null_matches )
166     do  { pat_holes <- mapM (\ _ -> newHole) (hsLMatchPats match)
167         ; res_hole  <- newHole
168
169                 -- Do the business
170         ; res <- thing_inside (map Infer pat_holes) (Infer res_hole)
171
172                 -- Extract the answers
173         ; arg_tys <- mapM readMutVar pat_holes
174         ; res_ty  <- readMutVar res_hole
175
176                 -- Write the answer into the incoming hole
177         ; writeMutVar hole (mkFunTys arg_tys res_ty)
178
179                 -- And return the answer
180         ; return res }
181
182 subFunTys (MatchGroup (match:matches) _) (Check ty) thing_inside
183   = ASSERT( all ((== length (hsLMatchPats match)) . length . hsLMatchPats) matches )
184         -- Assertion just checks that all the matches have the same number of pats
185     do  { (pat_tys, res_ty) <- unifyFunTys (length (hsLMatchPats match)) ty
186         ; thing_inside (map Check pat_tys) (Check res_ty) }
187
188 unifyFunTys :: Arity -> TcRhoType -> TcM ([TcSigmaType], TcRhoType)                     
189 -- Fail if ty isn't a function type, otherwise return arg and result types
190 -- The result types are guaranteed wobbly if the argument is wobbly
191 --
192 -- Does not allocate unnecessary meta variables: if the input already is 
193 -- a function, we just take it apart.  Not only is this efficient, it's important
194 -- for  (a) higher rank: the argument might be of form
195 --              (forall a. ty) -> other
196 --          If allocated (fresh-meta-var1 -> fresh-meta-var2) and unified, we'd
197 --          blow up with the meta var meets the forall
198 --
199 --      (b) GADTs: if the argument is not wobbly we do not want the result to be
200
201 unifyFunTys arity ty = unify_fun_ty True arity ty
202
203 unify_fun_ty use_refinement arity ty
204   | arity == 0 
205   = do  { res_ty <- wobblify use_refinement ty
206         ; return ([], ty) }
207
208 unify_fun_ty use_refinement arity (NoteTy _ ty)
209   = unify_fun_ty use_refinement arity ty
210
211 unify_fun_ty use_refinement arity ty@(TyVarTy tv)
212   = do  { details <- condLookupTcTyVar use_refinement tv
213         ; case details of
214             IndirectTv use' ty' -> unify_fun_ty use' arity ty'
215             other               -> unify_fun_help arity ty
216         }
217
218 unify_fun_ty use_refinement arity ty
219   = case tcSplitFunTy_maybe ty of
220         Just (arg,res) -> do { arg'          <- wobblify use_refinement arg
221                              ; (args', res') <- unify_fun_ty use_refinement (arity-1) res
222                              ; return (arg':args', res') }
223
224         Nothing -> unify_fun_help arity ty
225         -- Usually an error, but ty could be (a Int Bool), which can match
226
227 unify_fun_help :: Arity -> TcRhoType -> TcM ([TcSigmaType], TcRhoType)                  
228 unify_fun_help arity ty
229   = do { args <- mappM newTyFlexiVarTy (replicate arity argTypeKind)
230        ; res <- newTyFlexiVarTy openTypeKind
231        ; unifyTauTy ty (mkFunTys args res)
232        ; return (args, res) }
233 \end{code}
234
235 \begin{code}
236 ----------------------
237 zapToTyConApp :: TyCon                  -- T :: k1 -> ... -> kn -> *
238               -> Expected TcSigmaType   -- Expected type (T a b c)
239               -> TcM [TcType]           -- Element types, a b c
240   -- Insists that the Expected type is not a forall-type
241
242 zapToTyConApp tc (Check ty)
243    = unifyTyConApp tc ty         -- NB: fails for a forall-type
244 zapToTyConApp tc (Infer hole) 
245   = do  { (tc_app, elt_tys) <- newTyConApp tc
246         ; writeMutVar hole tc_app
247         ; return elt_tys }
248
249 zapToListTy :: Expected TcType -> TcM TcType    -- Special case for lists
250 zapToListTy exp_ty = do { [elt_ty] <- zapToTyConApp listTyCon exp_ty
251                         ; return elt_ty }
252
253 ----------------------
254 unifyTyConApp :: TyCon -> TcType -> TcM [TcType]
255 unifyTyConApp tc ty = unify_tc_app True tc ty
256         -- Add a boolean flag to remember whether to use 
257         -- the type refinement or not
258
259 unifyListTy :: TcType -> TcM TcType     -- Special case for lists
260 unifyListTy exp_ty = do { [elt_ty] <- unifyTyConApp listTyCon exp_ty
261                         ; return elt_ty }
262
263 ----------
264 unify_tc_app use_refinement tc (NoteTy _ ty)
265   = unify_tc_app use_refinement tc ty
266
267 unify_tc_app use_refinement tc ty@(TyVarTy tyvar)
268   = do  { details <- condLookupTcTyVar use_refinement tyvar
269         ; case details of
270             IndirectTv use' ty' -> unify_tc_app use' tc ty'
271             other               -> unify_tc_app_help tc ty
272         }
273
274 unify_tc_app use_refinement tc ty
275   | Just (tycon, arg_tys) <- tcSplitTyConApp_maybe ty,
276     tycon == tc
277   = ASSERT( tyConArity tycon == length arg_tys )        -- ty::*
278     mapM (wobblify use_refinement) arg_tys              
279
280 unify_tc_app use_refinement tc ty = unify_tc_app_help tc ty
281
282 ----------
283 unify_tc_app_help tc ty         -- Revert to ordinary unification
284   = do  { (tc_app, arg_tys) <- newTyConApp tc
285         ; if not (isTauTy ty) then      -- Can happen if we call zapToTyConApp tc (forall a. ty)
286              unifyMisMatch ty tc_app
287           else do
288         { unifyTauTy ty tc_app
289         ; returnM arg_tys } }
290
291
292 ----------------------
293 unifyAppTy :: TcType            -- Expected type function: m
294            -> TcType            -- Type to split:          m a
295            -> TcM TcType        -- Type arg:               a
296 unifyAppTy tc ty = unify_app_ty True tc ty
297
298 unify_app_ty use tc (NoteTy _ ty) = unify_app_ty use tc ty
299
300 unify_app_ty use tc ty@(TyVarTy tyvar)
301   = do  { details <- condLookupTcTyVar use tyvar
302         ; case details of
303             IndirectTv use' ty' -> unify_app_ty use' tc ty'
304             other               -> unify_app_ty_help tc ty
305         }
306
307 unify_app_ty use tc ty
308   | Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
309   = do  { unifyTauTy tc fun_ty
310         ; wobblify use arg_ty }
311
312   | otherwise = unify_app_ty_help tc ty
313
314 unify_app_ty_help tc ty         -- Revert to ordinary unification
315   = do  { arg_ty <- newTyFlexiVarTy (kindFunResult (typeKind tc))
316         ; unifyTauTy (mkAppTy tc arg_ty) ty
317         ; return arg_ty }
318
319
320 ----------------------
321 wobblify :: Bool        -- True <=> don't wobblify
322          -> TcTauType
323          -> TcM TcTauType       
324 -- Return a wobbly type.  At the moment we do that by 
325 -- allocating a fresh meta type variable.
326 wobblify True  ty = return ty
327 wobblify False ty = do  { uniq <- newUnique
328                         ; tv <- newMetaTyVar (mkSysTvName uniq FSLIT("w")) 
329                                              (typeKind ty) 
330                                              (Indirect ty)
331                         ; return (mkTyVarTy tv) }
332
333 ----------------------
334 newTyConApp :: TyCon -> TcM (TcTauType, [TcTauType])
335 newTyConApp tc = do { (tvs, args, _) <- tcInstTyVars (tyConTyVars tc)
336                     ; return (mkTyConApp tc args, args) }
337 \end{code}
338
339
340 %************************************************************************
341 %*                                                                      *
342 \subsection{Subsumption}
343 %*                                                                      *
344 %************************************************************************
345
346 All the tcSub calls have the form
347         
348                 tcSub expected_ty offered_ty
349 which checks
350                 offered_ty <= expected_ty
351
352 That is, that a value of type offered_ty is acceptable in
353 a place expecting a value of type expected_ty.
354
355 It returns a coercion function 
356         co_fn :: offered_ty -> expected_ty
357 which takes an HsExpr of type offered_ty into one of type
358 expected_ty.
359
360 \begin{code}
361 -----------------------
362 -- tcSubExp is used for expressions
363 tcSubExp :: Expected TcRhoType -> TcRhoType  -> TcM ExprCoFn
364
365 tcSubExp (Infer hole) offered_ty
366   = do { offered' <- zonkTcType offered_ty
367         -- Note [Zonk return type]
368         -- zonk to take advantage of the current GADT type refinement.
369         -- If we don't we get spurious "existential type variable escapes":
370         --      case (x::Maybe a) of
371         --        Just b (y::b) -> y
372         -- We need the refinement [b->a] to be applied to the result type
373         ; writeMutVar hole offered'
374         ; return idCoercion }
375
376 tcSubExp (Check expected_ty) offered_ty
377   = tcSub expected_ty offered_ty
378
379 -----------------------
380 -- tcSubPat is used for patterns
381 tcSubPat :: TcSigmaType                 -- Pattern type signature
382          -> Expected TcSigmaType        -- Type from context
383          -> TcM ()
384 -- In patterns we insist on an exact match; hence no CoFn returned
385 --      See Note [Pattern coercions] in TcPat
386
387 tcSubPat sig_ty (Infer hole) 
388   = do { sig_ty' <- zonkTcType sig_ty
389         ; writeMutVar hole sig_ty'      -- See notes with tcSubExp above
390         ; return () }
391
392 tcSubPat sig_ty (Check exp_ty) 
393   = do  { co_fn <- tcSub sig_ty exp_ty
394
395         ; if isIdCoercion co_fn then
396                 return ()
397           else
398                 unifyMisMatch sig_ty exp_ty }
399 \end{code}
400
401
402
403 %************************************************************************
404 %*                                                                      *
405         tcSub: main subsumption-check code
406 %*                                                                      *
407 %************************************************************************
408
409 No holes expected now.  Add some error-check context info.
410
411 \begin{code}
412 -----------------
413 tcSub :: TcSigmaType -> TcSigmaType -> TcM ExprCoFn     -- Locally used only
414         -- tcSub exp act checks that 
415         --      act <= exp
416 tcSub expected_ty actual_ty
417   = traceTc (text "tcSub" <+> details)          `thenM_`
418     addErrCtxtM (unifyCtxt "type" expected_ty actual_ty)
419                 (tc_sub expected_ty expected_ty actual_ty actual_ty)
420   where
421     details = vcat [text "Expected:" <+> ppr expected_ty,
422                     text "Actual:  " <+> ppr actual_ty]
423
424 -----------------
425 tc_sub :: TcSigmaType           -- expected_ty, before expanding synonyms
426        -> TcSigmaType           --              ..and after
427        -> TcSigmaType           -- actual_ty, before
428        -> TcSigmaType           --              ..and after
429        -> TcM ExprCoFn
430
431 -----------------------------------
432 -- Expand synonyms
433 tc_sub exp_sty (NoteTy _ exp_ty) act_sty act_ty = tc_sub exp_sty exp_ty act_sty act_ty
434 tc_sub exp_sty exp_ty act_sty (NoteTy _ act_ty) = tc_sub exp_sty exp_ty act_sty act_ty
435
436 -----------------------------------
437 -- Generalisation case
438 --      actual_ty:   d:Eq b => b->b
439 --      expected_ty: forall a. Ord a => a->a
440 --      co_fn e      /\a. \d2:Ord a. let d = eqFromOrd d2 in e
441
442 -- It is essential to do this *before* the specialisation case
443 -- Example:  f :: (Eq a => a->a) -> ...
444 --           g :: Ord b => b->b
445 -- Consider  f g !
446
447 tc_sub exp_sty expected_ty act_sty actual_ty
448   | isSigmaTy expected_ty
449   = tcGen expected_ty (tyVarsOfType actual_ty) (
450         -- It's really important to check for escape wrt the free vars of
451         -- both expected_ty *and* actual_ty
452         \ body_exp_ty -> tc_sub body_exp_ty body_exp_ty act_sty actual_ty
453     )                           `thenM` \ (gen_fn, co_fn) ->
454     returnM (gen_fn <.> co_fn)
455
456 -----------------------------------
457 -- Specialisation case:
458 --      actual_ty:   forall a. Ord a => a->a
459 --      expected_ty: Int -> Int
460 --      co_fn e =    e Int dOrdInt
461
462 tc_sub exp_sty expected_ty act_sty actual_ty
463   | isSigmaTy actual_ty
464   = tcInstCall InstSigOrigin actual_ty          `thenM` \ (inst_fn, _, body_ty) ->
465     tc_sub exp_sty expected_ty body_ty body_ty  `thenM` \ co_fn ->
466     returnM (co_fn <.> inst_fn)
467
468 -----------------------------------
469 -- Function case
470
471 tc_sub _ (FunTy exp_arg exp_res) _ (FunTy act_arg act_res)
472   = tcSub_fun exp_arg exp_res act_arg act_res
473
474 -----------------------------------
475 -- Type variable meets function: imitate
476 --
477 -- NB 1: we can't just unify the type variable with the type
478 --       because the type might not be a tau-type, and we aren't
479 --       allowed to instantiate an ordinary type variable with
480 --       a sigma-type
481 --
482 -- NB 2: can we short-cut to an error case?
483 --       when the arg/res is not a tau-type?
484 -- NO!  e.g.   f :: ((forall a. a->a) -> Int) -> Int
485 --      then   x = (f,f)
486 --      is perfectly fine, because we can instantiate f's type to a monotype
487 --
488 -- However, we get can get jolly unhelpful error messages.  
489 --      e.g.    foo = id runST
490 --
491 --    Inferred type is less polymorphic than expected
492 --      Quantified type variable `s' escapes
493 --      Expected type: ST s a -> t
494 --      Inferred type: (forall s1. ST s1 a) -> a
495 --    In the first argument of `id', namely `runST'
496 --    In a right-hand side of function `foo': id runST
497 --
498 -- I'm not quite sure what to do about this!
499
500 tc_sub exp_sty exp_ty@(FunTy exp_arg exp_res) _ act_ty
501   = do  { ([act_arg], act_res) <- unifyFunTys 1 act_ty
502         ; tcSub_fun exp_arg exp_res act_arg act_res }
503
504 tc_sub _ exp_ty act_sty act_ty@(FunTy act_arg act_res)
505   = do  { ([exp_arg], exp_res) <- unifyFunTys 1 exp_ty
506         ; tcSub_fun exp_arg exp_res act_arg act_res }
507
508 -----------------------------------
509 -- Unification case
510 -- If none of the above match, we revert to the plain unifier
511 tc_sub exp_sty expected_ty act_sty actual_ty
512   = uTys True exp_sty expected_ty True act_sty actual_ty        `thenM_`
513     returnM idCoercion
514 \end{code}    
515     
516 \begin{code}
517 tcSub_fun exp_arg exp_res act_arg act_res
518   = tc_sub act_arg act_arg exp_arg exp_arg      `thenM` \ co_fn_arg ->
519     tc_sub exp_res exp_res act_res act_res      `thenM` \ co_fn_res ->
520     newUnique                                   `thenM` \ uniq ->
521     let
522         -- co_fn_arg :: HsExpr exp_arg -> HsExpr act_arg
523         -- co_fn_res :: HsExpr act_res -> HsExpr exp_res
524         -- co_fn     :: HsExpr (act_arg -> act_res) -> HsExpr (exp_arg -> exp_res)
525         arg_id = mkSysLocal FSLIT("sub") uniq exp_arg
526         coercion | isIdCoercion co_fn_arg,
527                    isIdCoercion co_fn_res = idCoercion
528                  | otherwise              = mkCoercion co_fn
529
530         co_fn e = DictLam [arg_id] 
531                      (noLoc (co_fn_res <$> (HsApp (noLoc e) (noLoc (co_fn_arg <$> HsVar arg_id)))))
532                 -- Slight hack; using a "DictLam" to get an ordinary simple lambda
533                 --      HsVar arg_id :: HsExpr exp_arg
534                 --      co_fn_arg $it :: HsExpr act_arg
535                 --      HsApp e $it   :: HsExpr act_res
536                 --      co_fn_res $it :: HsExpr exp_res
537     in
538     returnM coercion
539 \end{code}
540
541
542 %************************************************************************
543 %*                                                                      *
544 \subsection{Generalisation}
545 %*                                                                      *
546 %************************************************************************
547
548 \begin{code}
549 tcGen :: TcSigmaType                            -- expected_ty
550       -> TcTyVarSet                             -- Extra tyvars that the universally
551                                                 --      quantified tyvars of expected_ty
552                                                 --      must not be unified
553       -> (TcRhoType -> TcM result)              -- spec_ty
554       -> TcM (ExprCoFn, result)
555         -- The expression has type: spec_ty -> expected_ty
556
557 tcGen expected_ty extra_tvs thing_inside        -- We expect expected_ty to be a forall-type
558                                                 -- If not, the call is a no-op
559   = do  { span <- getSrcSpanM
560         ; let rigid_info = GenSkol expected_ty span
561         ; (forall_tvs, theta, phi_ty) <- tcSkolType rigid_info expected_ty
562
563         -- Type-check the arg and unify with poly type
564         ; (result, lie) <- getLIE (thing_inside phi_ty)
565
566         -- Check that the "forall_tvs" havn't been constrained
567         -- The interesting bit here is that we must include the free variables
568         -- of the expected_ty.  Here's an example:
569         --       runST (newVar True)
570         -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
571         -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
572         -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
573         -- So now s' isn't unconstrained because it's linked to a.
574         -- Conclusion: include the free vars of the expected_ty in the
575         -- list of "free vars" for the signature check.
576
577         ; dicts <- newDicts (SigOrigin rigid_info) theta
578         ; inst_binds <- tcSimplifyCheck sig_msg forall_tvs dicts lie
579
580 #ifdef DEBUG
581         ; forall_tys <- zonkTcTyVars forall_tvs
582         ; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
583                                     text "expected_ty" <+> ppr expected_ty,
584                                     text "inst ty" <+> ppr forall_tvs <+> ppr theta <+> ppr phi_ty,
585                                     text "free_tvs" <+> ppr free_tvs,
586                                     text "forall_tys" <+> ppr forall_tys])
587 #endif
588
589         ; checkSigTyVarsWrt free_tvs forall_tvs
590         ; traceTc (text "tcGen:done")
591
592         ; let
593             -- This HsLet binds any Insts which came out of the simplification.
594             -- It's a bit out of place here, but using AbsBind involves inventing
595             -- a couple of new names which seems worse.
596                 dict_ids = map instToId dicts
597                 co_fn e  = TyLam forall_tvs (mkHsDictLam dict_ids (mkHsLet inst_binds (noLoc e)))
598         ; returnM (mkCoercion co_fn, result) }
599   where
600     free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
601     sig_msg  = ptext SLIT("expected type of an expression")
602 \end{code}    
603
604     
605
606 %************************************************************************
607 %*                                                                      *
608 \subsection[Unify-exported]{Exported unification functions}
609 %*                                                                      *
610 %************************************************************************
611
612 The exported functions are all defined as versions of some
613 non-exported generic functions.
614
615 Unify two @TauType@s.  Dead straightforward.
616
617 \begin{code}
618 unifyTauTy :: TcTauType -> TcTauType -> TcM ()
619 unifyTauTy ty1 ty2      -- ty1 expected, ty2 inferred
620   =     -- The unifier should only ever see tau-types 
621         -- (no quantification whatsoever)
622     ASSERT2( isTauTy ty1, ppr ty1 )
623     ASSERT2( isTauTy ty2, ppr ty2 )
624     addErrCtxtM (unifyCtxt "type" ty1 ty2) $
625     uTys True ty1 ty1 True ty2 ty2
626 \end{code}
627
628 @unifyTauTyList@ unifies corresponding elements of two lists of
629 @TauType@s.  It uses @uTys@ to do the real work.  The lists should be
630 of equal length.  We charge down the list explicitly so that we can
631 complain if their lengths differ.
632
633 \begin{code}
634 unifyTauTyLists :: Bool ->  -- Allow refinements on tys1
635                    [TcTauType] ->
636                    Bool ->  -- Allow refinements on tys2
637                    [TcTauType] ->  TcM ()
638 -- Precondition: lists must be same length
639 -- Having the caller check gives better error messages
640 -- Actually the caller neve does  need to check; see Note [Tycon app]
641 unifyTauTyLists r1 []         r2 []             = returnM ()
642 unifyTauTyLists r1 (ty1:tys1) r2 (ty2:tys2)     = uTys r1 ty1 ty1 r2 ty2 ty2   `thenM_`
643                                         unifyTauTyLists r1 tys1 r2 tys2
644 unifyTauTyLists r1 ty1s r2 ty2s = panic "Unify.unifyTauTyLists: mismatched type lists!"
645 \end{code}
646
647 @unifyTauTyList@ takes a single list of @TauType@s and unifies them
648 all together.  It is used, for example, when typechecking explicit
649 lists, when all the elts should be of the same type.
650
651 \begin{code}
652 unifyTauTyList :: [TcTauType] -> TcM ()
653 unifyTauTyList []                = returnM ()
654 unifyTauTyList [ty]              = returnM ()
655 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2   `thenM_`
656                                    unifyTauTyList tys
657 \end{code}
658
659 %************************************************************************
660 %*                                                                      *
661 \subsection[Unify-uTys]{@uTys@: getting down to business}
662 %*                                                                      *
663 %************************************************************************
664
665 @uTys@ is the heart of the unifier.  Each arg happens twice, because
666 we want to report errors in terms of synomyms if poss.  The first of
667 the pair is used in error messages only; it is always the same as the
668 second, except that if the first is a synonym then the second may be a
669 de-synonym'd version.  This way we get better error messages.
670
671 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
672
673 \begin{code}
674 uTys :: Bool                    -- Allow refinements to ty1
675      -> TcTauType -> TcTauType  -- Error reporting ty1 and real ty1
676                                 -- ty1 is the *expected* type
677      -> Bool                    -- Allow refinements to ty2 
678      -> TcTauType -> TcTauType  -- Error reporting ty2 and real ty2
679                                 -- ty2 is the *actual* type
680      -> TcM ()
681
682         -- Always expand synonyms (see notes at end)
683         -- (this also throws away FTVs)
684 uTys r1 ps_ty1 (NoteTy n1 ty1) r2 ps_ty2 ty2 = uTys r1 ps_ty1 ty1 r2 ps_ty2 ty2
685 uTys r1 ps_ty1 ty1 r2 ps_ty2 (NoteTy n2 ty2) = uTys r1 ps_ty1 ty1 r2 ps_ty2 ty2
686
687         -- Variables; go for uVar
688 uTys r1 ps_ty1 (TyVarTy tyvar1) r2 ps_ty2 ty2 = uVar False r1 tyvar1 r2 ps_ty2 ty2
689 uTys r1 ps_ty1 ty1 r2 ps_ty2 (TyVarTy tyvar2) = uVar True  r2 tyvar2 r1 ps_ty1 ty1
690                                         -- "True" means args swapped
691
692         -- Predicates
693 uTys r1 _ (PredTy (IParam n1 t1)) r2 _ (PredTy (IParam n2 t2))
694   | n1 == n2 = uTys r1 t1 t1 r2 t2 t2
695 uTys r1 _ (PredTy (ClassP c1 tys1)) r2 _ (PredTy (ClassP c2 tys2))
696   | c1 == c2 = unifyTauTyLists r1 tys1 r2 tys2
697         -- Guaranteed equal lengths because the kinds check
698
699         -- Functions; just check the two parts
700 uTys r1 _ (FunTy fun1 arg1) r2 _ (FunTy fun2 arg2)
701   = uTys r1 fun1 fun1 r2 fun2 fun2      `thenM_`    uTys r1 arg1 arg1 r2 arg2 arg2
702
703         -- Type constructors must match
704 uTys r1 ps_ty1 (TyConApp con1 tys1) r2 ps_ty2 (TyConApp con2 tys2)
705   | con1 == con2 = unifyTauTyLists r1 tys1 r2 tys2
706         -- See Note [TyCon app]
707
708         -- Applications need a bit of care!
709         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
710         -- NB: we've already dealt with type variables and Notes,
711         -- so if one type is an App the other one jolly well better be too
712 uTys r1 ps_ty1 (AppTy s1 t1) r2 ps_ty2 ty2
713   = case tcSplitAppTy_maybe ty2 of
714         Just (s2,t2) -> uTys r1 s1 s1 r2 s2 s2  `thenM_`    uTys r1 t1 t1 r2 t2 t2
715         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
716
717         -- Now the same, but the other way round
718         -- Don't swap the types, because the error messages get worse
719 uTys r1 ps_ty1 ty1 r2 ps_ty2 (AppTy s2 t2)
720   = case tcSplitAppTy_maybe ty1 of
721         Just (s1,t1) -> uTys r1 s1 s1 r2 s2 s2  `thenM_`    uTys r1 t1 t1 r2 t2 t2
722         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
723
724         -- Not expecting for-alls in unification
725         -- ... but the error message from the unifyMisMatch more informative
726         -- than a panic message!
727
728         -- Anything else fails
729 uTys r1 ps_ty1 ty1 r2 ps_ty2 ty2  = unifyMisMatch ps_ty1 ps_ty2
730 \end{code}
731
732 Note [Tycon app]
733 ~~~~~~~~~~~~~~~~
734 When we find two TyConApps, the argument lists are guaranteed equal
735 length.  Reason: intially the kinds of the two types to be unified is
736 the same. The only way it can become not the same is when unifying two
737 AppTys (f1 a1):=:(f2 a2).  In that case there can't be a TyConApp in
738 the f1,f2 (because it'd absorb the app).  If we unify f1:=:f2 first,
739 which we do, that ensures that f1,f2 have the same kind; and that
740 means a1,a2 have the same kind.  And now the argument repeats.
741
742
743 Notes on synonyms
744 ~~~~~~~~~~~~~~~~~
745 If you are tempted to make a short cut on synonyms, as in this
746 pseudocode...
747
748 \begin{verbatim}
749 -- NO   uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
750 -- NO     = if (con1 == con2) then
751 -- NO   -- Good news!  Same synonym constructors, so we can shortcut
752 -- NO   -- by unifying their arguments and ignoring their expansions.
753 -- NO   unifyTauTypeLists args1 args2
754 -- NO    else
755 -- NO   -- Never mind.  Just expand them and try again
756 -- NO   uTys ty1 ty2
757 \end{verbatim}
758
759 then THINK AGAIN.  Here is the whole story, as detected and reported
760 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
761 \begin{quotation}
762 Here's a test program that should detect the problem:
763
764 \begin{verbatim}
765         type Bogus a = Int
766         x = (1 :: Bogus Char) :: Bogus Bool
767 \end{verbatim}
768
769 The problem with [the attempted shortcut code] is that
770 \begin{verbatim}
771         con1 == con2
772 \end{verbatim}
773 is not a sufficient condition to be able to use the shortcut!
774 You also need to know that the type synonym actually USES all
775 its arguments.  For example, consider the following type synonym
776 which does not use all its arguments.
777 \begin{verbatim}
778         type Bogus a = Int
779 \end{verbatim}
780
781 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
782 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
783 would fail, even though the expanded forms (both \tr{Int}) should
784 match.
785
786 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
787 unnecessarily bind \tr{t} to \tr{Char}.
788
789 ... You could explicitly test for the problem synonyms and mark them
790 somehow as needing expansion, perhaps also issuing a warning to the
791 user.
792 \end{quotation}
793
794
795 %************************************************************************
796 %*                                                                      *
797 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
798 %*                                                                      *
799 %************************************************************************
800
801 @uVar@ is called when at least one of the types being unified is a
802 variable.  It does {\em not} assume that the variable is a fixed point
803 of the substitution; rather, notice that @uVar@ (defined below) nips
804 back into @uTys@ if it turns out that the variable is already bound.
805
806 \begin{code}
807 uVar :: Bool            -- False => tyvar is the "expected"
808                         -- True  => ty    is the "expected" thing
809      -> Bool            -- True, allow refinements to tv1, False don't
810      -> TcTyVar
811      -> Bool            -- Allow refinements to ty2? 
812      -> TcTauType -> TcTauType  -- printing and real versions
813      -> TcM ()
814
815 uVar swapped r1 tv1 r2 ps_ty2 ty2
816   = traceTc (text "uVar" <+> ppr swapped <+> ppr tv1 <+> (ppr ps_ty2 $$ ppr ty2))       `thenM_`
817     condLookupTcTyVar r1 tv1    `thenM` \ details ->
818     case details of
819         IndirectTv r1' ty1 | swapped   -> uTys r2   ps_ty2 ty2 r1' ty1    ty1   -- Swap back
820                            | otherwise -> uTys r1' ty1     ty1 r2  ps_ty2 ty2   -- Same order
821         FlexiTv -> uFlexiVar swapped tv1 r2 ps_ty2 ty2
822         RigidTv -> uRigidVar swapped tv1 r2 ps_ty2 ty2
823
824         -- Expand synonyms; ignore FTVs
825 uFlexiVar :: Bool -> TcTyVar -> 
826              Bool ->   -- Allow refinements to ty2
827              TcTauType -> TcTauType -> TcM ()
828 -- Invariant: tv1 is Flexi
829 uFlexiVar swapped tv1 r2 ps_ty2 (NoteTy n2 ty2)
830   = uFlexiVar swapped tv1 r2 ps_ty2 ty2
831
832 uFlexiVar swapped tv1 r2 ps_ty2 ty2@(TyVarTy tv2)
833         -- Same type variable => no-op
834   | tv1 == tv2
835   = returnM ()
836
837         -- Distinct type variables
838   | otherwise
839   = condLookupTcTyVar r2 tv2    `thenM` \ details ->
840     case details of
841         IndirectTv b ty2'    -> uFlexiVar swapped tv1 b ty2' ty2'
842         FlexiTv | update_tv2 -> putMetaTyVar tv2 (TyVarTy tv1)
843                 | otherwise  -> updateFlexi swapped tv1 ty2
844         RigidTv              -> updateFlexi swapped tv1 ty2
845         -- Note that updateFlexi does a sub-kind check
846         -- We might unify (a b) with (c d) where b::*->* and d::*; this should fail
847   where
848     k1 = tyVarKind tv1
849     k2 = tyVarKind tv2
850     update_tv2 = k1 `isSubKind` k2 && (k1 /= k2 || nicer_to_update_tv2)
851         -- Update the variable with least kind info
852         -- See notes on type inference in Kind.lhs
853         -- The "nicer to" part only applies if the two kinds are the same,
854         -- so we can choose which to do.
855
856     nicer_to_update_tv2 = isSystemName (varName tv2)
857         -- Try to update sys-y type variables in preference to sig-y ones
858
859   -- First one is flexi, second one isn't a type variable
860 uFlexiVar swapped tv1 r2 ps_ty2 non_var_ty2
861   =     -- Do the occurs check, and check that we are not
862         -- unifying a type variable with a polytype
863         -- Returns a zonked type ready for the update
864     do  { ty2 <- checkValue tv1 r2 ps_ty2 non_var_ty2
865         ; updateFlexi swapped tv1 ty2 }
866
867 -- Ready to update tv1, which is flexi; occurs check is done
868 updateFlexi swapped tv1 ty2
869   = do  { checkKinds swapped tv1 ty2
870         ; putMetaTyVar tv1 ty2 }
871
872
873 uRigidVar :: Bool -> TcTyVar
874           -> Bool -> -- Allow refinements to ty2
875              TcTauType -> TcTauType -> TcM ()
876 -- Invariant: tv1 is Rigid
877 uRigidVar swapped tv1 r2 ps_ty2 (NoteTy n2 ty2)
878   = uRigidVar swapped tv1 r2 ps_ty2 ty2
879
880         -- The both-type-variable case
881 uRigidVar swapped tv1 r2 ps_ty2 ty2@(TyVarTy tv2)
882         -- Same type variable => no-op
883   | tv1 == tv2
884   = returnM ()
885
886         -- Distinct type variables
887   | otherwise
888   = condLookupTcTyVar r2 tv2    `thenM` \ details ->
889     case details of
890         IndirectTv b ty2' -> uRigidVar swapped tv1 b ty2' ty2'
891         FlexiTv -> updateFlexi swapped tv2 (TyVarTy tv1)
892         RigidTv -> unifyMisMatch (TyVarTy tv1) (TyVarTy tv2) 
893
894         -- Second one isn't a type variable
895 uRigidVar swapped tv1 r2 ps_ty2 non_var_ty2
896   = unifyMisMatch (TyVarTy tv1) ps_ty2
897 \end{code}
898
899 \begin{code}
900 checkKinds swapped tv1 ty2
901 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
902 -- ty2 has been zonked at this stage, which ensures that
903 -- its kind has as much boxity information visible as possible.
904   | tk2 `isSubKind` tk1 = returnM ()
905
906   | otherwise
907         -- Either the kinds aren't compatible
908         --      (can happen if we unify (a b) with (c d))
909         -- or we are unifying a lifted type variable with an
910         --      unlifted type: e.g.  (id 3#) is illegal
911   = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
912     unifyKindMisMatch k1 k2
913
914   where
915     (k1,k2) | swapped   = (tk2,tk1)
916             | otherwise = (tk1,tk2)
917     tk1 = tyVarKind tv1
918     tk2 = typeKind ty2
919 \end{code}
920
921 \begin{code}
922 checkValue tv1 r2 ps_ty2 non_var_ty2
923 -- Do the occurs check, and check that we are not
924 -- unifying a type variable with a polytype
925 -- Return the type to update the type variable with, or fail
926
927 -- Basically we want to update     tv1 := ps_ty2
928 -- because ps_ty2 has type-synonym info, which improves later error messages
929 -- 
930 -- But consider 
931 --      type A a = ()
932 --
933 --      f :: (A a -> a -> ()) -> ()
934 --      f = \ _ -> ()
935 --
936 --      x :: ()
937 --      x = f (\ x p -> p x)
938 --
939 -- In the application (p x), we try to match "t" with "A t".  If we go
940 -- ahead and bind t to A t (= ps_ty2), we'll lead the type checker into 
941 -- an infinite loop later.
942 -- But we should not reject the program, because A t = ().
943 -- Rather, we should bind t to () (= non_var_ty2).
944 -- 
945 -- That's why we have this two-state occurs-check
946   = zonk_tc_type r2 ps_ty2                      `thenM` \ ps_ty2' ->
947     case okToUnifyWith tv1 ps_ty2' of {
948         Nothing -> returnM ps_ty2' ;    -- Success
949         other ->
950
951     zonk_tc_type r2 non_var_ty2         `thenM` \ non_var_ty2' ->
952     case okToUnifyWith tv1 non_var_ty2' of
953         Nothing ->      -- This branch rarely succeeds, except in strange cases
954                         -- like that in the example above
955                     returnM non_var_ty2'
956
957         Just problem -> failWithTcM (unifyCheck problem tv1 ps_ty2')
958     }
959   where
960     zonk_tc_type refine ty
961       = zonkType (\tv -> return (TyVarTy tv)) refine ty
962         -- We may already be inside a wobbly type t2, and
963         -- should take that into account here
964
965 data Problem = OccurCheck | NotMonoType
966
967 okToUnifyWith :: TcTyVar -> TcType -> Maybe Problem
968 -- (okToUnifyWith tv ty) checks whether it's ok to unify
969 --      tv :=: ty
970 -- Nothing => ok
971 -- Just p  => not ok, problem p
972
973 okToUnifyWith tv ty
974   = ok ty
975   where
976     ok (TyVarTy tv') | tv == tv' = Just OccurCheck
977                      | otherwise = Nothing
978     ok (AppTy t1 t2)            = ok t1 `and` ok t2
979     ok (FunTy t1 t2)            = ok t1 `and` ok t2
980     ok (TyConApp _ ts)          = oks ts
981     ok (ForAllTy _ _)           = Just NotMonoType
982     ok (PredTy st)              = ok_st st
983     ok (NoteTy (FTVNote _) t)   = ok t
984     ok (NoteTy (SynNote t1) t2) = ok t1 `and` ok t2
985                 -- Type variables may be free in t1 but not t2
986                 -- A forall may be in t2 but not t1
987
988     oks ts = foldr (and . ok) Nothing ts
989
990     ok_st (ClassP _ ts) = oks ts
991     ok_st (IParam _ t)  = ok t
992
993     Nothing `and` m = m
994     Just p  `and` m = Just p
995 \end{code}
996
997
998 %************************************************************************
999 %*                                                                      *
1000                 Kind unification
1001 %*                                                                      *
1002 %************************************************************************
1003
1004 Unifying kinds is much, much simpler than unifying types.
1005
1006 \begin{code}
1007 unifyKind :: TcKind                 -- Expected
1008           -> TcKind                 -- Actual
1009           -> TcM ()
1010 unifyKind LiftedTypeKind   LiftedTypeKind   = returnM ()
1011 unifyKind UnliftedTypeKind UnliftedTypeKind = returnM ()
1012
1013 unifyKind OpenTypeKind k2 | isOpenTypeKind k2 = returnM ()
1014 unifyKind ArgTypeKind  k2 | isArgTypeKind k2    = returnM ()
1015   -- Respect sub-kinding
1016
1017 unifyKind (FunKind a1 r1) (FunKind a2 r2)
1018  = do { unifyKind a2 a1; unifyKind r1 r2 }
1019                 -- Notice the flip in the argument,
1020                 -- so that the sub-kinding works right
1021
1022 unifyKind (KindVar kv1) k2 = uKVar False kv1 k2
1023 unifyKind k1 (KindVar kv2) = uKVar True kv2 k1
1024 unifyKind k1 k2 = unifyKindMisMatch k1 k2
1025
1026 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1027 unifyKinds []       []       = returnM ()
1028 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2  `thenM_`
1029                                unifyKinds ks1 ks2
1030 unifyKinds _ _               = panic "unifyKinds: length mis-match"
1031
1032 ----------------
1033 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1034 uKVar swapped kv1 k2
1035   = do  { mb_k1 <- readKindVar kv1
1036         ; case mb_k1 of
1037             Nothing -> uUnboundKVar swapped kv1 k2
1038             Just k1 | swapped   -> unifyKind k2 k1
1039                     | otherwise -> unifyKind k1 k2 }
1040
1041 ----------------
1042 uUnboundKVar :: Bool -> KindVar -> TcKind -> TcM ()
1043 uUnboundKVar swapped kv1 k2@(KindVar kv2)
1044   | kv1 == kv2 = returnM ()
1045   | otherwise   -- Distinct kind variables
1046   = do  { mb_k2 <- readKindVar kv2
1047         ; case mb_k2 of
1048             Just k2 -> uUnboundKVar swapped kv1 k2
1049             Nothing -> writeKindVar kv1 k2 }
1050
1051 uUnboundKVar swapped kv1 non_var_k2
1052   = do  { k2' <- zonkTcKind non_var_k2
1053         ; kindOccurCheck kv1 k2'
1054         ; k2'' <- kindSimpleKind swapped k2'
1055                 -- KindVars must be bound only to simple kinds
1056                 -- Polarities: (kindSimpleKind True ?) succeeds 
1057                 -- returning *, corresponding to unifying
1058                 --      expected: ?
1059                 --      actual:   kind-ver
1060         ; writeKindVar kv1 k2'' }
1061
1062 ----------------
1063 kindOccurCheck kv1 k2   -- k2 is zonked
1064   = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1065   where
1066     not_in (KindVar kv2)   = kv1 /= kv2
1067     not_in (FunKind a2 r2) = not_in a2 && not_in r2
1068     not_in other           = True
1069
1070 kindSimpleKind :: Bool -> Kind -> TcM SimpleKind
1071 -- (kindSimpleKind True k) returns a simple kind sk such that sk <: k
1072 -- If the flag is False, it requires k <: sk
1073 -- E.g.         kindSimpleKind False ?? = *
1074 -- What about (kv -> *) :=: ?? -> *
1075 kindSimpleKind orig_swapped orig_kind
1076   = go orig_swapped orig_kind
1077   where
1078     go sw (FunKind k1 k2) = do { k1' <- go (not sw) k1
1079                                ; k2' <- go sw k2
1080                                ; return (FunKind k1' k2') }
1081     go True OpenTypeKind = return liftedTypeKind
1082     go True ArgTypeKind  = return liftedTypeKind
1083     go sw LiftedTypeKind  = return liftedTypeKind
1084     go sw k@(KindVar _)   = return k    -- KindVars are always simple
1085     go swapped kind = failWithTc (ptext SLIT("Unexpected kind unification failure:")
1086                                   <+> ppr orig_swapped <+> ppr orig_kind)
1087         -- I think this can't actually happen
1088
1089 -- T v = MkT v           v must be a type 
1090 -- T v w = MkT (v -> w)  v must not be an umboxed tuple
1091
1092 ----------------
1093 kindOccurCheckErr tyvar ty
1094   = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1095        2 (sep [ppr tyvar, char '=', ppr ty])
1096
1097 unifyKindMisMatch ty1 ty2
1098   = zonkTcKind ty1      `thenM` \ ty1' ->
1099     zonkTcKind ty2      `thenM` \ ty2' ->
1100     let
1101         msg = hang (ptext SLIT("Couldn't match kind"))
1102                    2 (sep [quotes (ppr ty1'), 
1103                            ptext SLIT("against"), 
1104                            quotes (ppr ty2')])
1105     in
1106     failWithTc msg
1107 \end{code}
1108
1109 \begin{code}
1110 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1111 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1112
1113 unifyFunKind (KindVar kvar)
1114   = readKindVar kvar    `thenM` \ maybe_kind ->
1115     case maybe_kind of
1116         Just fun_kind -> unifyFunKind fun_kind
1117         Nothing       -> do { arg_kind <- newKindVar
1118                             ; res_kind <- newKindVar
1119                             ; writeKindVar kvar (mkArrowKind arg_kind res_kind)
1120                             ; returnM (Just (arg_kind,res_kind)) }
1121     
1122 unifyFunKind (FunKind arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1123 unifyFunKind other                       = returnM Nothing
1124 \end{code}
1125
1126 %************************************************************************
1127 %*                                                                      *
1128 \subsection[Unify-context]{Errors and contexts}
1129 %*                                                                      *
1130 %************************************************************************
1131
1132 Errors
1133 ~~~~~~
1134
1135 \begin{code}
1136 unifyCtxt s ty1 ty2 tidy_env    -- ty1 expected, ty2 inferred
1137   = zonkTcType ty1      `thenM` \ ty1' ->
1138     zonkTcType ty2      `thenM` \ ty2' ->
1139     returnM (err ty1' ty2')
1140   where
1141     err ty1 ty2 = (env1, 
1142                    nest 2 
1143                         (vcat [
1144                            text "Expected" <+> text s <> colon <+> ppr tidy_ty1,
1145                            text "Inferred" <+> text s <> colon <+> ppr tidy_ty2
1146                         ]))
1147                   where
1148                     (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
1149
1150 unifyKindCtxt swapped tv1 ty2 tidy_env  -- not swapped => tv1 expected, ty2 inferred
1151         -- tv1 and ty2 are zonked already
1152   = returnM msg
1153   where
1154     msg = (env2, ptext SLIT("When matching the kinds of") <+> 
1155                  sep [quotes pp_expected <+> ptext SLIT("and"), quotes pp_actual])
1156
1157     (pp_expected, pp_actual) | swapped   = (pp2, pp1)
1158                              | otherwise = (pp1, pp2)
1159     (env1, tv1') = tidyOpenTyVar tidy_env tv1
1160     (env2, ty2') = tidyOpenType  env1 ty2
1161     pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
1162     pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
1163
1164 unifyMisMatch ty1 ty2
1165   = do  { (env1, pp1, extra1) <- ppr_ty emptyTidyEnv ty1
1166         ; (env2, pp2, extra2) <- ppr_ty env1 ty2
1167         ; let msg = sep [sep [ptext SLIT("Couldn't match") <+> pp1, nest 7 (ptext SLIT("against") <+> pp2)],
1168                          nest 2 extra1, nest 2 extra2]
1169     in
1170     failWithTcM (env2, msg) }
1171
1172 ppr_ty :: TidyEnv -> TcType -> TcM (TidyEnv, SDoc, SDoc)
1173 ppr_ty env ty
1174   = do { ty' <- zonkTcType ty
1175        ; let (env1,tidy_ty) = tidyOpenType env ty'
1176              simple_result  = (env1, quotes (ppr tidy_ty), empty)
1177        ; case tidy_ty of
1178            TyVarTy tv 
1179                 | isSkolemTyVar tv -> return (env1, pp_rigid tv,
1180                                               pprSkolemTyVar tv)
1181                 | otherwise -> return simple_result
1182            other -> return simple_result }
1183   where
1184     pp_rigid tv = ptext SLIT("the rigid variable") <+> quotes (ppr tv)
1185
1186 unifyCheck problem tyvar ty
1187   = (env2, hang msg
1188               2 (sep [ppr tidy_tyvar, char '=', ppr tidy_ty]))
1189   where
1190     (env1, tidy_tyvar) = tidyOpenTyVar emptyTidyEnv tyvar
1191     (env2, tidy_ty)    = tidyOpenType  env1         ty
1192
1193     msg = case problem of
1194             OccurCheck  -> ptext SLIT("Occurs check: cannot construct the infinite type:")
1195             NotMonoType -> ptext SLIT("Cannot unify a type variable with a type scheme:")
1196 \end{code}
1197
1198
1199 %************************************************************************
1200 %*                                                                      *
1201         Checking kinds
1202 %*                                                                      *
1203 %************************************************************************
1204
1205 ---------------------------
1206 -- We would like to get a decent error message from
1207 --   (a) Under-applied type constructors
1208 --              f :: (Maybe, Maybe)
1209 --   (b) Over-applied type constructors
1210 --              f :: Int x -> Int x
1211 --
1212
1213 \begin{code}
1214 checkExpectedKind :: Outputable a => a -> TcKind -> TcKind -> TcM ()
1215 -- A fancy wrapper for 'unifyKind', which tries 
1216 -- to give decent error messages.
1217 checkExpectedKind ty act_kind exp_kind
1218   | act_kind `isSubKind` exp_kind -- Short cut for a very common case
1219   = returnM ()
1220   | otherwise
1221   = tryTc (unifyKind exp_kind act_kind) `thenM` \ (errs, mb_r) ->
1222     case mb_r of {
1223         Just _  -> returnM () ; -- Unification succeeded
1224         Nothing ->
1225
1226         -- So there's definitely an error
1227         -- Now to find out what sort
1228     zonkTcKind exp_kind         `thenM` \ exp_kind ->
1229     zonkTcKind act_kind         `thenM` \ act_kind ->
1230
1231     let (exp_as, _) = splitKindFunTys exp_kind
1232         (act_as, _) = splitKindFunTys act_kind
1233         n_exp_as = length exp_as
1234         n_act_as = length act_as
1235
1236         err | n_exp_as < n_act_as       -- E.g. [Maybe]
1237             = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
1238
1239                 -- Now n_exp_as >= n_act_as. In the next two cases, 
1240                 -- n_exp_as == 0, and hence so is n_act_as
1241             | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1242             = ptext SLIT("Expecting a lifted type, but") <+> quotes (ppr ty)
1243                 <+> ptext SLIT("is unlifted")
1244
1245             | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1246             = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1247                 <+> ptext SLIT("is lifted")
1248
1249             | otherwise                 -- E.g. Monad [Int]
1250             = sep [ ptext SLIT("Expecting kind") <+> quotes (pprKind exp_kind) <> comma,
1251                     ptext SLIT("but") <+> quotes (ppr ty) <+> 
1252                     ptext SLIT("has kind") <+> quotes (pprKind act_kind)]
1253    in
1254    failWithTc (ptext SLIT("Kind error:") <+> err) 
1255    }
1256 \end{code}
1257
1258 %************************************************************************
1259 %*                                                                      *
1260 \subsection{Checking signature type variables}
1261 %*                                                                      *
1262 %************************************************************************
1263
1264 @checkSigTyVars@ is used after the type in a type signature has been unified with
1265 the actual type found.  It then checks that the type variables of the type signature
1266 are
1267         (a) Still all type variables
1268                 eg matching signature [a] against inferred type [(p,q)]
1269                 [then a will be unified to a non-type variable]
1270
1271         (b) Still all distinct
1272                 eg matching signature [(a,b)] against inferred type [(p,p)]
1273                 [then a and b will be unified together]
1274
1275         (c) Not mentioned in the environment
1276                 eg the signature for f in this:
1277
1278                         g x = ... where
1279                                         f :: a->[a]
1280                                         f y = [x,y]
1281
1282                 Here, f is forced to be monorphic by the free occurence of x.
1283
1284         (d) Not (unified with another type variable that is) in scope.
1285                 eg f x :: (r->r) = (\y->y) :: forall a. a->r
1286             when checking the expression type signature, we find that
1287             even though there is nothing in scope whose type mentions r,
1288             nevertheless the type signature for the expression isn't right.
1289
1290             Another example is in a class or instance declaration:
1291                 class C a where
1292                    op :: forall b. a -> b
1293                    op x = x
1294             Here, b gets unified with a
1295
1296 Before doing this, the substitution is applied to the signature type variable.
1297
1298 We used to have the notion of a "DontBind" type variable, which would
1299 only be bound to itself or nothing.  Then points (a) and (b) were 
1300 self-checking.  But it gave rise to bogus consequential error messages.
1301 For example:
1302
1303    f = (*)      -- Monomorphic
1304
1305    g :: Num a => a -> a
1306    g x = f x x
1307
1308 Here, we get a complaint when checking the type signature for g,
1309 that g isn't polymorphic enough; but then we get another one when
1310 dealing with the (Num x) context arising from f's definition;
1311 we try to unify x with Int (to default it), but find that x has already
1312 been unified with the DontBind variable "a" from g's signature.
1313 This is really a problem with side-effecting unification; we'd like to
1314 undo g's effects when its type signature fails, but unification is done
1315 by side effect, so we can't (easily).
1316
1317 So we revert to ordinary type variables for signatures, and try to
1318 give a helpful message in checkSigTyVars.
1319
1320 \begin{code}
1321 checkSigTyVars :: [TcTyVar] -> TcM ()
1322 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
1323
1324 checkSigTyVarsWrt :: TcTyVarSet -> [TcTyVar] -> TcM ()
1325 checkSigTyVarsWrt extra_tvs sig_tvs
1326   = zonkTcTyVarsAndFV (varSetElems extra_tvs)   `thenM` \ extra_tvs' ->
1327     check_sig_tyvars extra_tvs' sig_tvs
1328
1329 check_sig_tyvars
1330         :: TcTyVarSet   -- Global type variables. The universally quantified
1331                         --      tyvars should not mention any of these
1332                         --      Guaranteed already zonked.
1333         -> [TcTyVar]    -- Universally-quantified type variables in the signature
1334                         --      Not guaranteed zonked.
1335         -> TcM ()
1336
1337 check_sig_tyvars extra_tvs []
1338   = returnM ()
1339 check_sig_tyvars extra_tvs sig_tvs 
1340   = do  { gbl_tvs <- tcGetGlobalTyVars
1341         ; traceTc (text "check_sig_tyvars" <+> (vcat [text "sig_tys" <+> ppr sig_tvs,
1342                                       text "gbl_tvs" <+> ppr gbl_tvs,
1343                                       text "extra_tvs" <+> ppr extra_tvs]))
1344
1345         -- Check that that the signature type vars are not free in the envt
1346         ; let env_tvs = gbl_tvs `unionVarSet` extra_tvs
1347         ; checkM (not (mkVarSet sig_tvs `intersectsVarSet` env_tvs))
1348                  (complain sig_tvs env_tvs)
1349
1350         ; ASSERT( all isSkolemTyVar sig_tvs )
1351           return () }
1352   where
1353     complain sig_tvs globals
1354       = -- "check" checks each sig tyvar in turn
1355         foldlM check
1356                (env, emptyVarEnv, [])
1357                tidy_tvs `thenM` \ (env2, _, msgs) ->
1358
1359         failWithTcM (env2, main_msg $$ nest 2 (vcat msgs))
1360       where
1361         (env, tidy_tvs) = tidyOpenTyVars emptyTidyEnv sig_tvs
1362
1363         main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
1364
1365         check (tidy_env, acc, msgs) tv
1366                 -- sig_tyvar is from the signature;
1367                 -- ty is what you get if you zonk sig_tyvar and then tidy it
1368                 --
1369                 -- acc maps a zonked type variable back to a signature type variable
1370           = case lookupVarEnv acc tv of {
1371                 Just sig_tyvar' ->      -- Error (b)!
1372                         returnM (tidy_env, acc, unify_msg tv thing : msgs)
1373                     where
1374                         thing = ptext SLIT("another quantified type variable") <+> quotes (ppr sig_tyvar')
1375
1376               ; Nothing ->
1377
1378             if tv `elemVarSet` globals  -- Error (c) or (d)! Type variable escapes
1379                                         -- The least comprehensible, so put it last
1380                         -- Game plan: 
1381                         --       get the local TcIds and TyVars from the environment,
1382                         --       and pass them to find_globals (they might have tv free)
1383             then   
1384                    findGlobals (unitVarSet tv) tidy_env         `thenM` \ (tidy_env1, globs) ->
1385                         -- This rigid type variable has escaped into the envt
1386                         -- We make it flexi so that subequent uses of these 
1387                         -- variables don't give rise to a cascade of further errors
1388                    returnM (tidy_env1, acc, escape_msg tv globs : msgs)
1389
1390             else        -- All OK
1391             returnM (tidy_env, extendVarEnv acc tv tv, msgs)
1392             }
1393 \end{code}
1394
1395
1396 \begin{code}
1397 -----------------------
1398 escape_msg sig_tv globs
1399   = mk_msg sig_tv <+> ptext SLIT("escapes") $$
1400     if notNull globs then
1401         vcat [ptext SLIT("It is mentioned in the environment:"), 
1402               nest 2 (vcat globs)]
1403      else
1404         empty   -- Sigh.  It's really hard to give a good error message
1405                 -- all the time.   One bad case is an existential pattern match.
1406                 -- We rely on the "When..." context to help.
1407
1408 unify_msg tv thing = mk_msg tv <+> ptext SLIT("is unified with") <+> thing
1409 mk_msg tv          = ptext SLIT("Quantified type variable") <+> quotes (ppr tv)
1410 \end{code}
1411
1412 These two context are used with checkSigTyVars
1413     
1414 \begin{code}
1415 sigCtxt :: Id -> [TcTyVar] -> TcThetaType -> TcTauType
1416         -> TidyEnv -> TcM (TidyEnv, Message)
1417 sigCtxt id sig_tvs sig_theta sig_tau tidy_env
1418   = zonkTcType sig_tau          `thenM` \ actual_tau ->
1419     let
1420         (env1, tidy_sig_tvs)    = tidyOpenTyVars tidy_env sig_tvs
1421         (env2, tidy_sig_rho)    = tidyOpenType env1 (mkPhiTy sig_theta sig_tau)
1422         (env3, tidy_actual_tau) = tidyOpenType env2 actual_tau
1423         sub_msg = vcat [ptext SLIT("Signature type:    ") <+> pprType (mkForAllTys tidy_sig_tvs tidy_sig_rho),
1424                         ptext SLIT("Type to generalise:") <+> pprType tidy_actual_tau
1425                    ]
1426         msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),
1427                     nest 2 sub_msg]
1428     in
1429     returnM (env3, msg)
1430 \end{code}