2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Type subsumption and unification}
8 -- Full-blown subsumption
9 tcSubPat, tcSubExp, tcGen,
10 checkSigTyVars, checkSigTyVarsWrt, sigCtxt, findGlobals,
12 -- Various unifications
13 unifyTauTy, unifyTauTyList,
14 unifyKind, unifyKinds, unifyFunKind,
17 --------------------------------
19 Expected(..), tcInfer, readExpectedType,
20 zapExpectedType, zapExpectedTo, zapExpectedBranches,
21 subFunTys, unifyFunTys,
22 zapToListTy, unifyListTy,
23 zapToTyConApp, unifyTyConApp,
27 #include "HsVersions.h"
30 import HsSyn ( HsExpr(..) , MatchGroup(..), hsLMatchPats )
31 import TcHsSyn ( mkHsLet, mkHsDictLam,
32 ExprCoFn, idCoercion, isIdCoercion, mkCoercion, (<.>), (<$>) )
33 import TypeRep ( Type(..), PredType(..), TyNote(..) )
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 )
64 import Name ( isSystemName, mkSysTvName )
65 import ErrUtils ( Message )
66 import SrcLoc ( noLoc )
67 import BasicTypes ( Arity )
68 import Util ( notNull )
74 * A hole is always filled in with an ordinary type, not another hole.
76 %************************************************************************
78 \subsection{'hole' type variables}
80 %************************************************************************
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
86 newHole = newMutVar (error "Empty hole in typechecker")
88 tcInfer :: (Expected ty -> TcM a) -> TcM (a,ty)
90 = do { hole <- newHole
91 ; res <- tc_infer (Infer hole)
92 ; res_ty <- readMutVar hole
93 ; return (res, res_ty) }
95 readExpectedType :: Expected ty -> TcM ty
96 readExpectedType (Infer hole) = readMutVar hole
97 readExpectedType (Check ty) = returnM ty
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 ;
107 zapExpectedType (Check ty) kind
108 | typeKind ty `isSubKind` kind = return ty
109 | otherwise = do { ty1 <- newTyFlexiVarTy kind
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
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)
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) }
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]
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")
142 %************************************************************************
144 \subsection[Unify-fun]{@unifyFunTy@}
146 %************************************************************************
148 @subFunTy@ and @unifyFunTy@ is used to avoid the fruitless
149 creation of type variables.
151 * subFunTy is used when we might be faced with a "hole" type variable,
152 in which case we should create two new holes.
154 * unifyFunTy is used when we expect to encounter only "ordinary"
155 type variables, so we should create new ordinary type variables
158 subFunTys :: MatchGroup name
159 -> Expected TcRhoType -- Fail if ty isn't a function type
160 -> ([Expected TcRhoType] -> Expected TcRhoType -> TcM a)
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
170 ; res <- thing_inside (map Infer pat_holes) (Infer res_hole)
172 -- Extract the answers
173 ; arg_tys <- mapM readMutVar pat_holes
174 ; res_ty <- readMutVar res_hole
176 -- Write the answer into the incoming hole
177 ; writeMutVar hole (mkFunTys arg_tys res_ty)
179 -- And return the answer
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) }
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
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
199 -- (b) GADTs: if the argument is not wobbly we do not want the result to be
201 unifyFunTys arity ty = unify_fun_ty True arity ty
203 unify_fun_ty use_refinement arity ty
205 = do { res_ty <- wobblify use_refinement ty
208 unify_fun_ty use_refinement arity (NoteTy _ ty)
209 = unify_fun_ty use_refinement arity ty
211 unify_fun_ty use_refinement arity ty@(TyVarTy tv)
212 = do { details <- condLookupTcTyVar use_refinement tv
214 IndirectTv use' ty' -> unify_fun_ty use' arity ty'
215 other -> unify_fun_help arity ty
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') }
224 Nothing -> unify_fun_help arity ty
225 -- Usually an error, but ty could be (a Int Bool), which can match
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) }
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
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
249 zapToListTy :: Expected TcType -> TcM TcType -- Special case for lists
250 zapToListTy exp_ty = do { [elt_ty] <- zapToTyConApp listTyCon exp_ty
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
259 unifyListTy :: TcType -> TcM TcType -- Special case for lists
260 unifyListTy exp_ty = do { [elt_ty] <- unifyTyConApp listTyCon exp_ty
264 unify_tc_app use_refinement tc (NoteTy _ ty)
265 = unify_tc_app use_refinement tc ty
267 unify_tc_app use_refinement tc ty@(TyVarTy tyvar)
268 = do { details <- condLookupTcTyVar use_refinement tyvar
270 IndirectTv use' ty' -> unify_tc_app use' tc ty'
271 other -> unify_tc_app_help tc ty
274 unify_tc_app use_refinement tc ty
275 | Just (tycon, arg_tys) <- tcSplitTyConApp_maybe ty,
277 = ASSERT( tyConArity tycon == length arg_tys ) -- ty::*
278 mapM (wobblify use_refinement) arg_tys
280 unify_tc_app use_refinement tc ty = unify_tc_app_help tc ty
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
288 { unifyTauTy ty tc_app
289 ; returnM arg_tys } }
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
298 unify_app_ty use tc (NoteTy _ ty) = unify_app_ty use tc ty
300 unify_app_ty use tc ty@(TyVarTy tyvar)
301 = do { details <- condLookupTcTyVar use tyvar
303 IndirectTv use' ty' -> unify_app_ty use' tc ty'
304 other -> unify_app_ty_help tc ty
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 }
312 | otherwise = unify_app_ty_help tc ty
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
320 ----------------------
321 wobblify :: Bool -- True <=> don't wobblify
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"))
331 ; return (mkTyVarTy tv) }
333 ----------------------
334 newTyConApp :: TyCon -> TcM (TcTauType, [TcTauType])
335 newTyConApp tc = do { (tvs, args, _) <- tcInstTyVars (tyConTyVars tc)
336 ; return (mkTyConApp tc args, args) }
340 %************************************************************************
342 \subsection{Subsumption}
344 %************************************************************************
346 All the tcSub calls have the form
348 tcSub expected_ty offered_ty
350 offered_ty <= expected_ty
352 That is, that a value of type offered_ty is acceptable in
353 a place expecting a value of type expected_ty.
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
361 -----------------------
362 -- tcSubExp is used for expressions
363 tcSubExp :: Expected TcRhoType -> TcRhoType -> TcM ExprCoFn
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 }
376 tcSubExp (Check expected_ty) offered_ty
377 = tcSub expected_ty offered_ty
379 -----------------------
380 -- tcSubPat is used for patterns
381 tcSubPat :: TcSigmaType -- Pattern type signature
382 -> Expected TcSigmaType -- Type from context
384 -- In patterns we insist on an exact match; hence no CoFn returned
385 -- See Note [Pattern coercions] in TcPat
387 tcSubPat sig_ty (Infer hole)
388 = do { sig_ty' <- zonkTcType sig_ty
389 ; writeMutVar hole sig_ty' -- See notes with tcSubExp above
392 tcSubPat sig_ty (Check exp_ty)
393 = do { co_fn <- tcSub sig_ty exp_ty
395 ; if isIdCoercion co_fn then
398 unifyMisMatch sig_ty exp_ty }
403 %************************************************************************
405 tcSub: main subsumption-check code
407 %************************************************************************
409 No holes expected now. Add some error-check context info.
413 tcSub :: TcSigmaType -> TcSigmaType -> TcM ExprCoFn -- Locally used only
414 -- tcSub exp act checks that
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)
421 details = vcat [text "Expected:" <+> ppr expected_ty,
422 text "Actual: " <+> ppr actual_ty]
425 tc_sub :: TcSigmaType -- expected_ty, before expanding synonyms
426 -> TcSigmaType -- ..and after
427 -> TcSigmaType -- actual_ty, before
428 -> TcSigmaType -- ..and after
431 -----------------------------------
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
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
442 -- It is essential to do this *before* the specialisation case
443 -- Example: f :: (Eq a => a->a) -> ...
444 -- g :: Ord b => b->b
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)
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
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)
468 -----------------------------------
471 tc_sub _ (FunTy exp_arg exp_res) _ (FunTy act_arg act_res)
472 = tcSub_fun exp_arg exp_res act_arg act_res
474 -----------------------------------
475 -- Type variable meets function: imitate
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
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
486 -- is perfectly fine, because we can instantiate f's type to a monotype
488 -- However, we get can get jolly unhelpful error messages.
489 -- e.g. foo = id runST
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
498 -- I'm not quite sure what to do about this!
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 }
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 }
508 -----------------------------------
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_`
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 ->
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
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
542 %************************************************************************
544 \subsection{Generalisation}
546 %************************************************************************
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
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
563 -- Type-check the arg and unify with poly type
564 ; (result, lie) <- getLIE (thing_inside phi_ty)
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.
577 ; dicts <- newDicts (SigOrigin rigid_info) theta
578 ; inst_binds <- tcSimplifyCheck sig_msg forall_tvs dicts lie
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])
589 ; checkSigTyVarsWrt free_tvs forall_tvs
590 ; traceTc (text "tcGen:done")
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) }
600 free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
601 sig_msg = ptext SLIT("expected type of an expression")
606 %************************************************************************
608 \subsection[Unify-exported]{Exported unification functions}
610 %************************************************************************
612 The exported functions are all defined as versions of some
613 non-exported generic functions.
615 Unify two @TauType@s. Dead straightforward.
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
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.
634 unifyTauTyLists :: Bool -> -- Allow refinements on tys1
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!"
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.
652 unifyTauTyList :: [TcTauType] -> TcM ()
653 unifyTauTyList [] = returnM ()
654 unifyTauTyList [ty] = returnM ()
655 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2 `thenM_`
659 %************************************************************************
661 \subsection[Unify-uTys]{@uTys@: getting down to business}
663 %************************************************************************
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.
671 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
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
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
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
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
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
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]
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
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
724 -- Not expecting for-alls in unification
725 -- ... but the error message from the unifyMisMatch more informative
726 -- than a panic message!
728 -- Anything else fails
729 uTys r1 ps_ty1 ty1 r2 ps_ty2 ty2 = unifyMisMatch ps_ty1 ps_ty2
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.
745 If you are tempted to make a short cut on synonyms, as in this
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
755 -- NO -- Never mind. Just expand them and try again
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>}:
762 Here's a test program that should detect the problem:
766 x = (1 :: Bogus Char) :: Bogus Bool
769 The problem with [the attempted shortcut code] is that
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.
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
786 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
787 unnecessarily bind \tr{t} to \tr{Char}.
789 ... You could explicitly test for the problem synonyms and mark them
790 somehow as needing expansion, perhaps also issuing a warning to the
795 %************************************************************************
797 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
799 %************************************************************************
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.
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
811 -> Bool -- Allow refinements to ty2?
812 -> TcTauType -> TcTauType -- printing and real versions
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 ->
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
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
832 uFlexiVar swapped tv1 r2 ps_ty2 ty2@(TyVarTy tv2)
833 -- Same type variable => no-op
837 -- Distinct type variables
839 = condLookupTcTyVar r2 tv2 `thenM` \ details ->
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
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.
856 nicer_to_update_tv2 = isSystemName (varName tv2)
857 -- Try to update sys-y type variables in preference to sig-y ones
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 }
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 }
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
880 -- The both-type-variable case
881 uRigidVar swapped tv1 r2 ps_ty2 ty2@(TyVarTy tv2)
882 -- Same type variable => no-op
886 -- Distinct type variables
888 = condLookupTcTyVar r2 tv2 `thenM` \ details ->
890 IndirectTv b ty2' -> uRigidVar swapped tv1 b ty2' ty2'
891 FlexiTv -> updateFlexi swapped tv2 (TyVarTy tv1)
892 RigidTv -> unifyMisMatch (TyVarTy tv1) (TyVarTy tv2)
894 -- Second one isn't a type variable
895 uRigidVar swapped tv1 r2 ps_ty2 non_var_ty2
896 = unifyMisMatch (TyVarTy tv1) ps_ty2
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 ()
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
915 (k1,k2) | swapped = (tk2,tk1)
916 | otherwise = (tk1,tk2)
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
927 -- Basically we want to update tv1 := ps_ty2
928 -- because ps_ty2 has type-synonym info, which improves later error messages
933 -- f :: (A a -> a -> ()) -> ()
937 -- x = f (\ x p -> p x)
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).
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
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
957 Just problem -> failWithTcM (unifyCheck problem tv1 ps_ty2')
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
965 data Problem = OccurCheck | NotMonoType
967 okToUnifyWith :: TcTyVar -> TcType -> Maybe Problem
968 -- (okToUnifyWith tv ty) checks whether it's ok to unify
971 -- Just p => not ok, problem p
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
988 oks ts = foldr (and . ok) Nothing ts
990 ok_st (ClassP _ ts) = oks ts
991 ok_st (IParam _ t) = ok t
994 Just p `and` m = Just p
998 %************************************************************************
1002 %************************************************************************
1004 Unifying kinds is much, much simpler than unifying types.
1007 unifyKind :: TcKind -- Expected
1010 unifyKind LiftedTypeKind LiftedTypeKind = returnM ()
1011 unifyKind UnliftedTypeKind UnliftedTypeKind = returnM ()
1013 unifyKind OpenTypeKind k2 | isOpenTypeKind k2 = returnM ()
1014 unifyKind ArgTypeKind k2 | isArgTypeKind k2 = returnM ()
1015 -- Respect sub-kinding
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
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
1026 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
1027 unifyKinds [] [] = returnM ()
1028 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenM_`
1030 unifyKinds _ _ = panic "unifyKinds: length mis-match"
1033 uKVar :: Bool -> KindVar -> TcKind -> TcM ()
1034 uKVar swapped kv1 k2
1035 = do { mb_k1 <- readKindVar kv1
1037 Nothing -> uUnboundKVar swapped kv1 k2
1038 Just k1 | swapped -> unifyKind k2 k1
1039 | otherwise -> unifyKind k1 k2 }
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
1048 Just k2 -> uUnboundKVar swapped kv1 k2
1049 Nothing -> writeKindVar kv1 k2 }
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
1060 ; writeKindVar kv1 k2'' }
1063 kindOccurCheck kv1 k2 -- k2 is zonked
1064 = checkTc (not_in k2) (kindOccurCheckErr kv1 k2)
1066 not_in (KindVar kv2) = kv1 /= kv2
1067 not_in (FunKind a2 r2) = not_in a2 && not_in r2
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
1078 go sw (FunKind k1 k2) = do { k1' <- go (not sw) k1
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
1089 -- T v = MkT v v must be a type
1090 -- T v w = MkT (v -> w) v must not be an umboxed tuple
1093 kindOccurCheckErr tyvar ty
1094 = hang (ptext SLIT("Occurs check: cannot construct the infinite kind:"))
1095 2 (sep [ppr tyvar, char '=', ppr ty])
1097 unifyKindMisMatch ty1 ty2
1098 = zonkTcKind ty1 `thenM` \ ty1' ->
1099 zonkTcKind ty2 `thenM` \ ty2' ->
1101 msg = hang (ptext SLIT("Couldn't match kind"))
1102 2 (sep [quotes (ppr ty1'),
1103 ptext SLIT("against"),
1110 unifyFunKind :: TcKind -> TcM (Maybe (TcKind, TcKind))
1111 -- Like unifyFunTy, but does not fail; instead just returns Nothing
1113 unifyFunKind (KindVar kvar)
1114 = readKindVar kvar `thenM` \ maybe_kind ->
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)) }
1122 unifyFunKind (FunKind arg_kind res_kind) = returnM (Just (arg_kind,res_kind))
1123 unifyFunKind other = returnM Nothing
1126 %************************************************************************
1128 \subsection[Unify-context]{Errors and contexts}
1130 %************************************************************************
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')
1141 err ty1 ty2 = (env1,
1144 text "Expected" <+> text s <> colon <+> ppr tidy_ty1,
1145 text "Inferred" <+> text s <> colon <+> ppr tidy_ty2
1148 (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
1150 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
1151 -- tv1 and ty2 are zonked already
1154 msg = (env2, ptext SLIT("When matching the kinds of") <+>
1155 sep [quotes pp_expected <+> ptext SLIT("and"), quotes pp_actual])
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)
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]
1170 failWithTcM (env2, msg) }
1172 ppr_ty :: TidyEnv -> TcType -> TcM (TidyEnv, SDoc, SDoc)
1174 = do { ty' <- zonkTcType ty
1175 ; let (env1,tidy_ty) = tidyOpenType env ty'
1176 simple_result = (env1, quotes (ppr tidy_ty), empty)
1179 | isSkolemTyVar tv -> return (env1, pp_rigid tv,
1181 | otherwise -> return simple_result
1182 other -> return simple_result }
1184 pp_rigid tv = ptext SLIT("the rigid variable") <+> quotes (ppr tv)
1186 unifyCheck problem tyvar ty
1188 2 (sep [ppr tidy_tyvar, char '=', ppr tidy_ty]))
1190 (env1, tidy_tyvar) = tidyOpenTyVar emptyTidyEnv tyvar
1191 (env2, tidy_ty) = tidyOpenType env1 ty
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:")
1199 %************************************************************************
1203 %************************************************************************
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
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
1221 = tryTc (unifyKind exp_kind act_kind) `thenM` \ (errs, mb_r) ->
1223 Just _ -> returnM () ; -- Unification succeeded
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 ->
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
1236 err | n_exp_as < n_act_as -- E.g. [Maybe]
1237 = quotes (ppr ty) <+> ptext SLIT("is not applied to enough type arguments")
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")
1245 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1246 = ptext SLIT("Expecting an unlifted type, but") <+> quotes (ppr ty)
1247 <+> ptext SLIT("is lifted")
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)]
1254 failWithTc (ptext SLIT("Kind error:") <+> err)
1258 %************************************************************************
1260 \subsection{Checking signature type variables}
1262 %************************************************************************
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
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]
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]
1275 (c) Not mentioned in the environment
1276 eg the signature for f in this:
1282 Here, f is forced to be monorphic by the free occurence of x.
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.
1290 Another example is in a class or instance declaration:
1292 op :: forall b. a -> b
1294 Here, b gets unified with a
1296 Before doing this, the substitution is applied to the signature type variable.
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.
1303 f = (*) -- Monomorphic
1305 g :: Num a => a -> a
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).
1317 So we revert to ordinary type variables for signatures, and try to
1318 give a helpful message in checkSigTyVars.
1321 checkSigTyVars :: [TcTyVar] -> TcM ()
1322 checkSigTyVars sig_tvs = check_sig_tyvars emptyVarSet sig_tvs
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
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.
1337 check_sig_tyvars extra_tvs []
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]))
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)
1350 ; ASSERT( all isSkolemTyVar sig_tvs )
1353 complain sig_tvs globals
1354 = -- "check" checks each sig tyvar in turn
1356 (env, emptyVarEnv, [])
1357 tidy_tvs `thenM` \ (env2, _, msgs) ->
1359 failWithTcM (env2, main_msg $$ nest 2 (vcat msgs))
1361 (env, tidy_tvs) = tidyOpenTyVars emptyTidyEnv sig_tvs
1363 main_msg = ptext SLIT("Inferred type is less polymorphic than expected")
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
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)
1374 thing = ptext SLIT("another quantified type variable") <+> quotes (ppr sig_tyvar')
1378 if tv `elemVarSet` globals -- Error (c) or (d)! Type variable escapes
1379 -- The least comprehensible, so put it last
1381 -- get the local TcIds and TyVars from the environment,
1382 -- and pass them to find_globals (they might have tv free)
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)
1391 returnM (tidy_env, extendVarEnv acc tv tv, msgs)
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)]
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.
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)
1412 These two context are used with checkSigTyVars
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 ->
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
1426 msg = vcat [ptext SLIT("When trying to generalise the type inferred for") <+> quotes (ppr id),