2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcMonoType]{Typechecking user-specified @MonoTypes@}
9 tcHsSigType, tcHsSigTypeNC, tcHsDeriv,
10 tcHsInstHead, tcHsQuantifiedType,
14 kcHsTyVars, kcHsSigType, kcHsLiftedSigType,
15 kcLHsType, kcCheckLHsType, kcHsContext,
17 -- Typechecking kinded types
18 tcHsKindedContext, tcHsKindedType, tcHsBangType,
19 tcTyVarBndrs, dsHsType,
20 tcDataKindSig, ExpKind(..), EkCtxt(..),
22 -- Pattern type signatures
23 tcHsPatSigType, tcPatSig
26 #include "HsVersions.h"
28 #ifdef GHCI /* Only if bootstrapped */
29 import {-# SOURCE #-} TcSplice( kcSpliceType )
40 import {- Kind parts of -} Type
59 ----------------------------
61 ----------------------------
63 Generally speaking we now type-check types in three phases
65 1. kcHsType: kind check the HsType
66 *includes* performing any TH type splices;
67 so it returns a translated, and kind-annotated, type
69 2. dsHsType: convert from HsType to Type:
71 expand type synonyms [mkGenTyApps]
72 hoist the foralls [tcHsType]
74 3. checkValidType: check the validity of the resulting type
76 Often these steps are done one after the other (tcHsSigType).
77 But in mutually recursive groups of type and class decls we do
78 1 kind-check the whole group
79 2 build TyCons/Classes in a knot-tied way
80 3 check the validity of types in the now-unknotted TyCons/Classes
82 For example, when we find
83 (forall a m. m a -> m a)
84 we bind a,m to kind varibles and kind-check (m a -> m a). This makes
85 a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
86 an environment that binds a and m suitably.
88 The kind checker passed to tcHsTyVars needs to look at enough to
89 establish the kind of the tyvar:
90 * For a group of type and class decls, it's just the group, not
91 the rest of the program
92 * For a tyvar bound in a pattern type signature, its the types
93 mentioned in the other type signatures in that bunch of patterns
94 * For a tyvar bound in a RULE, it's the type signatures on other
95 universally quantified variables in the rule
97 Note that this may occasionally give surprising results. For example:
99 data T a b = MkT (a b)
101 Here we deduce a::*->*, b::*
102 But equally valid would be a::(*->*)-> *, b::*->*
107 Some of the validity check could in principle be done by the kind checker,
110 - During desugaring, we normalise by expanding type synonyms. Only
111 after this step can we check things like type-synonym saturation
112 e.g. type T k = k Int
114 Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
115 and then S is saturated. This is a GHC extension.
117 - Similarly, also a GHC extension, we look through synonyms before complaining
118 about the form of a class or instance declaration
120 - Ambiguity checks involve functional dependencies, and it's easier to wait
121 until knots have been resolved before poking into them
123 Also, in a mutually recursive group of types, we can't look at the TyCon until we've
124 finished building the loop. So to keep things simple, we postpone most validity
125 checking until step (3).
129 During step (1) we might fault in a TyCon defined in another module, and it might
130 (via a loop) refer back to a TyCon defined in this module. So when we tie a big
131 knot around type declarations with ARecThing, so that the fault-in code can get
132 the TyCon being defined.
135 %************************************************************************
137 \subsection{Checking types}
139 %************************************************************************
142 tcHsSigType, tcHsSigTypeNC :: UserTypeCtxt -> LHsType Name -> TcM Type
143 -- Do kind checking, and hoist for-alls to the top
144 -- NB: it's important that the foralls that come from the top-level
145 -- HsForAllTy in hs_ty occur *first* in the returned type.
146 -- See Note [Scoped] with TcSigInfo
147 tcHsSigType ctxt hs_ty
148 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
149 tcHsSigTypeNC ctxt hs_ty
151 tcHsSigTypeNC ctxt hs_ty
152 = do { (kinded_ty, _kind) <- kc_lhs_type hs_ty
153 -- The kind is checked by checkValidType, and isn't necessarily
154 -- of kind * in a Template Haskell quote eg [t| Maybe |]
155 ; ty <- tcHsKindedType kinded_ty
156 ; checkValidType ctxt ty
159 tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Type)
160 -- Typecheck an instance head. We can't use
161 -- tcHsSigType, because it's not a valid user type.
162 tcHsInstHead (L loc ty)
163 = setSrcSpan loc $ -- No need for an "In the type..." context
164 tc_inst_head ty -- because that comes from the caller
166 -- tc_inst_head expects HsPredTy, which isn't usually even allowed
167 tc_inst_head (HsPredTy pred)
168 = do { pred' <- kcHsPred pred
169 ; pred'' <- dsHsPred pred'
170 ; return ([], [], mkPredTy pred'') }
172 tc_inst_head (HsForAllTy _ tvs ctxt (L _ (HsPredTy pred)))
173 = kcHsTyVars tvs $ \ tvs' ->
174 do { ctxt' <- kcHsContext ctxt
175 ; pred' <- kcHsPred pred
176 ; tcTyVarBndrs tvs' $ \ tvs'' ->
177 do { ctxt'' <- mapM dsHsLPred (unLoc ctxt')
178 ; pred'' <- dsHsPred pred'
179 ; return (tvs'', ctxt'', mkPredTy pred'') } }
181 tc_inst_head _ = failWithTc (ptext (sLit "Malformed instance type"))
183 tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
184 -- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
185 -- except that we want to keep the tvs separate
186 tcHsQuantifiedType tv_names hs_ty
187 = kcHsTyVars tv_names $ \ tv_names' ->
188 do { kc_ty <- kcHsSigType hs_ty
189 ; tcTyVarBndrs tv_names' $ \ tvs ->
190 do { ty <- dsHsType kc_ty
191 ; return (tvs, ty) } }
193 -- Used for the deriving(...) items
194 tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
195 tcHsDeriv = tc_hs_deriv []
197 tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
198 -> TcM ([TyVar], Class, [Type])
199 tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
200 = kcHsTyVars tv_names $ \ tv_names' ->
201 do { cls_kind <- kcClass cls_name
202 ; (tys, _res_kind) <- kcApps cls_name cls_kind hs_tys
203 ; tcTyVarBndrs tv_names' $ \ tyvars ->
204 do { arg_tys <- dsHsTypes tys
205 ; cls <- tcLookupClass cls_name
206 ; return (tyvars, cls, arg_tys) }}
208 tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
209 = -- Funny newtype deriving form
211 -- where C has arity 2. Hence can't use regular functions
212 tc_hs_deriv (tv_names1 ++ tv_names2) ty
215 = failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
218 These functions are used during knot-tying in
219 type and class declarations, when we have to
220 separate kind-checking, desugaring, and validity checking
223 kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
224 -- Used for type signatures
225 kcHsSigType ty = addKcTypeCtxt ty $ kcTypeType ty
226 kcHsLiftedSigType ty = addKcTypeCtxt ty $ kcLiftedType ty
228 tcHsKindedType :: LHsType Name -> TcM Type
229 -- Don't do kind checking, nor validity checking.
230 -- This is used in type and class decls, where kinding is
231 -- done in advance, and validity checking is done later
232 -- [Validity checking done later because of knot-tying issues.]
233 tcHsKindedType hs_ty = dsHsType hs_ty
235 tcHsBangType :: LHsType Name -> TcM Type
236 -- Permit a bang, but discard it
237 tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
238 tcHsBangType ty = tcHsKindedType ty
240 tcHsKindedContext :: LHsContext Name -> TcM ThetaType
241 -- Used when we are expecting a ClassContext (i.e. no implicit params)
242 -- Does not do validity checking, like tcHsKindedType
243 tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
247 %************************************************************************
249 The main kind checker: kcHsType
251 %************************************************************************
253 First a couple of simple wrappers for kcHsType
256 ---------------------------
257 kcLiftedType :: LHsType Name -> TcM (LHsType Name)
258 -- The type ty must be a *lifted* *type*
259 kcLiftedType ty = kc_check_lhs_type ty ekLifted
261 ---------------------------
262 kcTypeType :: LHsType Name -> TcM (LHsType Name)
263 -- The type ty must be a *type*, but it can be lifted or
264 -- unlifted or an unboxed tuple.
265 kcTypeType ty = kc_check_lhs_type ty ekOpen
267 ---------------------------
268 kcCheckLHsType :: LHsType Name -> ExpKind -> TcM (LHsType Name)
269 kcCheckLHsType ty kind = addKcTypeCtxt ty $ kc_check_lhs_type ty kind
272 kc_check_lhs_type :: LHsType Name -> ExpKind -> TcM (LHsType Name)
273 -- Check that the type has the specified kind
274 -- Be sure to use checkExpectedKind, rather than simply unifying
275 -- with OpenTypeKind, because it gives better error messages
276 kc_check_lhs_type (L span ty) exp_kind
278 do { ty' <- kc_check_hs_type ty exp_kind
279 ; return (L span ty') }
281 kc_check_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [LHsType Name]
282 kc_check_lhs_types tys_w_kinds
283 = mapM kc_arg tys_w_kinds
285 kc_arg (arg, arg_kind) = kc_check_lhs_type arg arg_kind
288 ---------------------------
289 kc_check_hs_type :: HsType Name -> ExpKind -> TcM (HsType Name)
291 -- First some special cases for better error messages
292 -- when we know the expected kind
293 kc_check_hs_type (HsParTy ty) exp_kind
294 = do { ty' <- kc_check_lhs_type ty exp_kind; return (HsParTy ty') }
296 kc_check_hs_type ty@(HsAppTy ty1 ty2) exp_kind
297 = do { let (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
298 ; (fun_ty', fun_kind) <- kc_lhs_type fun_ty
299 ; arg_tys' <- kcCheckApps fun_ty fun_kind arg_tys ty exp_kind
300 ; return (mkHsAppTys fun_ty' arg_tys') }
302 -- This is the general case: infer the kind and compare
303 kc_check_hs_type ty exp_kind
304 = do { (ty', act_kind) <- kc_hs_type ty
305 -- Add the context round the inner check only
306 -- because checkExpectedKind already mentions
307 -- 'ty' by name in any error message
309 ; checkExpectedKind (strip ty) act_kind exp_kind
312 -- We infer the kind of the type, and then complain if it's
313 -- not right. But we don't want to complain about
314 -- (ty) or !(ty) or forall a. ty
315 -- when the real difficulty is with the 'ty' part.
316 strip (HsParTy (L _ ty)) = strip ty
317 strip (HsBangTy _ (L _ ty)) = strip ty
318 strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
322 Here comes the main function
325 kcLHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
326 -- Called from outside: set the context
327 kcLHsType ty = addKcTypeCtxt ty (kc_lhs_type ty)
329 kc_lhs_type :: LHsType Name -> TcM (LHsType Name, TcKind)
330 kc_lhs_type (L span ty)
332 do { (ty', kind) <- kc_hs_type ty
333 ; return (L span ty', kind) }
335 -- kc_hs_type *returns* the kind of the type, rather than taking an expected
336 -- kind as argument as tcExpr does.
338 -- (a) the kind of (->) is
339 -- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
340 -- so we'd need to generate huge numbers of bx variables.
341 -- (b) kinds are so simple that the error messages are fine
343 -- The translated type has explicitly-kinded type-variable binders
345 kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
346 kc_hs_type (HsParTy ty) = do
347 (ty', kind) <- kc_lhs_type ty
348 return (HsParTy ty', kind)
350 kc_hs_type (HsTyVar name) = do
352 return (HsTyVar name, kind)
354 kc_hs_type (HsListTy ty) = do
355 ty' <- kcLiftedType ty
356 return (HsListTy ty', liftedTypeKind)
358 kc_hs_type (HsPArrTy ty) = do
359 ty' <- kcLiftedType ty
360 return (HsPArrTy ty', liftedTypeKind)
362 kc_hs_type (HsNumTy n)
363 = return (HsNumTy n, liftedTypeKind)
365 kc_hs_type (HsKindSig ty k) = do
366 ty' <- kc_check_lhs_type ty (EK k EkKindSig)
367 return (HsKindSig ty' k, k)
369 kc_hs_type (HsTupleTy Boxed tys) = do
370 tys' <- mapM kcLiftedType tys
371 return (HsTupleTy Boxed tys', liftedTypeKind)
373 kc_hs_type (HsTupleTy Unboxed tys) = do
374 tys' <- mapM kcTypeType tys
375 return (HsTupleTy Unboxed tys', ubxTupleKind)
377 kc_hs_type (HsFunTy ty1 ty2) = do
378 ty1' <- kc_check_lhs_type ty1 (EK argTypeKind EkUnk)
379 ty2' <- kcTypeType ty2
380 return (HsFunTy ty1' ty2', liftedTypeKind)
382 kc_hs_type (HsOpTy ty1 op ty2) = do
383 op_kind <- addLocM kcTyVar op
384 ([ty1',ty2'], res_kind) <- kcApps op op_kind [ty1,ty2]
385 return (HsOpTy ty1' op ty2', res_kind)
387 kc_hs_type (HsAppTy ty1 ty2) = do
388 (fun_ty', fun_kind) <- kc_lhs_type fun_ty
389 (arg_tys', res_kind) <- kcApps fun_ty fun_kind arg_tys
390 return (mkHsAppTys fun_ty' arg_tys', res_kind)
392 (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
394 kc_hs_type (HsPredTy pred)
397 kc_hs_type (HsForAllTy exp tv_names context ty)
398 = kcHsTyVars tv_names $ \ tv_names' ->
399 do { ctxt' <- kcHsContext context
400 ; ty' <- kcLiftedType ty
401 -- The body of a forall is usually a type, but in principle
402 -- there's no reason to prohibit *unlifted* types.
403 -- In fact, GHC can itself construct a function with an
404 -- unboxed tuple inside a for-all (via CPR analyis; see
405 -- typecheck/should_compile/tc170)
407 -- Still, that's only for internal interfaces, which aren't
408 -- kind-checked, so we only allow liftedTypeKind here
410 ; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
412 kc_hs_type (HsBangTy b ty)
413 = do { (ty', kind) <- kc_lhs_type ty
414 ; return (HsBangTy b ty', kind) }
416 kc_hs_type ty@(HsRecTy _)
417 = failWithTc (ptext (sLit "Unexpected record type") <+> ppr ty)
418 -- Record types (which only show up temporarily in constructor signatures)
419 -- should have been removed by now
421 #ifdef GHCI /* Only if bootstrapped */
422 kc_hs_type (HsSpliceTy sp fvs _) = kcSpliceType sp fvs
424 kc_hs_type ty@(HsSpliceTy {}) = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
427 kc_hs_type (HsQuasiQuoteTy {}) = panic "kc_hs_type" -- Eliminated by renamer
429 -- remove the doc nodes here, no need to worry about the location since
430 -- its the same for a doc node and it's child type node
431 kc_hs_type (HsDocTy ty _)
432 = kc_hs_type (unLoc ty)
434 ---------------------------
435 kcApps :: Outputable a
437 -> TcKind -- Function kind
438 -> [LHsType Name] -- Arg types
439 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
440 kcApps the_fun fun_kind args
441 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
442 ; args' <- kc_check_lhs_types args_w_kinds
443 ; return (args', res_kind) }
445 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
446 -> HsType Name -- The type being checked (for err messages only)
447 -> ExpKind -- Expected kind
448 -> TcM [LHsType Name]
449 kcCheckApps the_fun fun_kind args ty exp_kind
450 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
451 ; checkExpectedKind ty res_kind exp_kind
452 -- Check the result kind *before* checking argument kinds
453 -- This improves error message; Trac #2994
454 ; kc_check_lhs_types args_w_kinds }
456 splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
457 splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
459 split (L _ (HsAppTy f a)) as = split f (a:as)
462 mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
463 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
464 mkHsAppTys fun_ty (arg_ty:arg_tys)
465 = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
467 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
468 -- the application; they are
471 ---------------------------
472 splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
473 splitFunKind _ _ fk [] = return ([], fk)
474 splitFunKind the_fun arg_no fk (arg:args)
475 = do { mb_fk <- unifyFunKind fk
477 Nothing -> failWithTc too_many_args
478 Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
479 ; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
481 too_many_args = quotes the_fun <+>
482 ptext (sLit "is applied to too many type arguments")
484 ---------------------------
485 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
486 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
488 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
489 kcHsLPred = wrapLocM kcHsPred
491 kcHsPred :: HsPred Name -> TcM (HsPred Name)
492 kcHsPred pred = do -- Checks that the result is of kind liftedType
493 (pred', kind) <- kc_pred pred
494 checkExpectedKind pred kind ekLifted
497 ---------------------------
498 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
499 -- Does *not* check for a saturated
500 -- application (reason: used from TcDeriv)
501 kc_pred (HsIParam name ty)
502 = do { (ty', kind) <- kc_lhs_type ty
503 ; return (HsIParam name ty', kind)
505 kc_pred (HsClassP cls tys)
506 = do { kind <- kcClass cls
507 ; (tys', res_kind) <- kcApps cls kind tys
508 ; return (HsClassP cls tys', res_kind)
510 kc_pred (HsEqualP ty1 ty2)
511 = do { (ty1', kind1) <- kc_lhs_type ty1
512 -- ; checkExpectedKind ty1 kind1 liftedTypeKind
513 ; (ty2', kind2) <- kc_lhs_type ty2
514 -- ; checkExpectedKind ty2 kind2 liftedTypeKind
515 ; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
516 ; return (HsEqualP ty1' ty2', liftedTypeKind)
519 ---------------------------
520 kcTyVar :: Name -> TcM TcKind
521 kcTyVar name = do -- Could be a tyvar or a tycon
522 traceTc (text "lk1" <+> ppr name)
523 thing <- tcLookup name
524 traceTc (text "lk2" <+> ppr name <+> ppr thing)
526 ATyVar _ ty -> return (typeKind ty)
527 AThing kind -> return kind
528 AGlobal (ATyCon tc) -> return (tyConKind tc)
529 _ -> wrongThingErr "type" thing name
531 kcClass :: Name -> TcM TcKind
532 kcClass cls = do -- Must be a class
533 thing <- tcLookup cls
535 AThing kind -> return kind
536 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
537 _ -> wrongThingErr "class" thing cls
541 %************************************************************************
545 %************************************************************************
549 * Transforms from HsType to Type
552 It cannot fail, and does no validity checking, except for
553 structural matters, such as
554 (a) spurious ! annotations.
555 (b) a class used as a type
558 dsHsType :: LHsType Name -> TcM Type
559 -- All HsTyVarBndrs in the intput type are kind-annotated
560 dsHsType ty = ds_type (unLoc ty)
562 ds_type :: HsType Name -> TcM Type
563 ds_type ty@(HsTyVar _)
566 ds_type (HsParTy ty) -- Remove the parentheses markers
569 ds_type ty@(HsBangTy {}) -- No bangs should be here
570 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
572 ds_type ty@(HsRecTy {}) -- No bangs should be here
573 = failWithTc (ptext (sLit "Unexpected record type:") <+> ppr ty)
575 ds_type (HsKindSig ty _)
576 = dsHsType ty -- Kind checking done already
578 ds_type (HsListTy ty) = do
579 tau_ty <- dsHsType ty
580 checkWiredInTyCon listTyCon
581 return (mkListTy tau_ty)
583 ds_type (HsPArrTy ty) = do
584 tau_ty <- dsHsType ty
585 checkWiredInTyCon parrTyCon
586 return (mkPArrTy tau_ty)
588 ds_type (HsTupleTy boxity tys) = do
589 tau_tys <- dsHsTypes tys
590 checkWiredInTyCon tycon
591 return (mkTyConApp tycon tau_tys)
593 tycon = tupleTyCon boxity (length tys)
595 ds_type (HsFunTy ty1 ty2) = do
596 tau_ty1 <- dsHsType ty1
597 tau_ty2 <- dsHsType ty2
598 return (mkFunTy tau_ty1 tau_ty2)
600 ds_type (HsOpTy ty1 (L span op) ty2) = do
601 tau_ty1 <- dsHsType ty1
602 tau_ty2 <- dsHsType ty2
603 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
607 tc <- tcLookupTyCon genUnitTyConName
608 return (mkTyConApp tc [])
610 ds_type ty@(HsAppTy _ _)
613 ds_type (HsPredTy pred) = do
614 pred' <- dsHsPred pred
615 return (mkPredTy pred')
617 ds_type (HsForAllTy _ tv_names ctxt ty)
618 = tcTyVarBndrs tv_names $ \ tyvars -> do
619 theta <- mapM dsHsLPred (unLoc ctxt)
621 return (mkSigmaTy tyvars theta tau)
623 ds_type (HsDocTy ty _) -- Remove the doc comment
626 ds_type (HsSpliceTy _ _ kind)
627 = do { kind' <- zonkTcKindToKind kind
628 ; newFlexiTyVarTy kind' }
630 ds_type (HsQuasiQuoteTy {}) = panic "ds_type" -- Eliminated by renamer
632 dsHsTypes :: [LHsType Name] -> TcM [Type]
633 dsHsTypes arg_tys = mapM dsHsType arg_tys
636 Help functions for type applications
637 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
640 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
641 ds_app (HsAppTy ty1 ty2) tys
642 = ds_app (unLoc ty1) (ty2:tys)
645 arg_tys <- dsHsTypes tys
647 HsTyVar fun -> ds_var_app fun arg_tys
648 _ -> do fun_ty <- ds_type ty
649 return (mkAppTys fun_ty arg_tys)
651 ds_var_app :: Name -> [Type] -> TcM Type
652 ds_var_app name arg_tys = do
653 thing <- tcLookup name
655 ATyVar _ ty -> return (mkAppTys ty arg_tys)
656 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
657 _ -> wrongThingErr "type" thing name
665 dsHsLPred :: LHsPred Name -> TcM PredType
666 dsHsLPred pred = dsHsPred (unLoc pred)
668 dsHsPred :: HsPred Name -> TcM PredType
669 dsHsPred (HsClassP class_name tys)
670 = do { arg_tys <- dsHsTypes tys
671 ; clas <- tcLookupClass class_name
672 ; return (ClassP clas arg_tys)
674 dsHsPred (HsEqualP ty1 ty2)
675 = do { arg_ty1 <- dsHsType ty1
676 ; arg_ty2 <- dsHsType ty2
677 ; return (EqPred arg_ty1 arg_ty2)
679 dsHsPred (HsIParam name ty)
680 = do { arg_ty <- dsHsType ty
681 ; return (IParam name arg_ty)
686 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
687 -- Wrap a context around only if we want to show that contexts.
688 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
689 -- Omit invisble ones and ones user's won't grok (HsPred p).
690 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
692 typeCtxt :: HsType Name -> SDoc
693 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
696 %************************************************************************
698 Type-variable binders
700 %************************************************************************
704 kcHsTyVars :: [LHsTyVarBndr Name]
705 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
706 -- They scope over the thing inside
708 kcHsTyVars tvs thing_inside
709 = do { kinded_tvs <- mapM (wrapLocM kcHsTyVar) tvs
710 ; tcExtendKindEnvTvs kinded_tvs thing_inside }
712 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
713 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
714 kcHsTyVar (UserTyVar name _) = UserTyVar name <$> newKindVar
715 kcHsTyVar tv@(KindedTyVar {}) = return tv
718 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
719 -> ([TyVar] -> TcM r)
721 -- Used when type-checking types/classes/type-decls
722 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
723 tcTyVarBndrs bndrs thing_inside = do
724 tyvars <- mapM (zonk . unLoc) bndrs
725 tcExtendTyVarEnv tyvars (thing_inside tyvars)
727 zonk (UserTyVar name kind) = do { kind' <- zonkTcKindToKind kind
728 ; return (mkTyVar name kind') }
729 zonk (KindedTyVar name kind) = return (mkTyVar name kind)
731 -----------------------------------
732 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
733 -- GADT decls can have a (perhaps partial) kind signature
734 -- e.g. data T :: * -> * -> * where ...
735 -- This function makes up suitable (kinded) type variables for
736 -- the argument kinds, and checks that the result kind is indeed *.
737 -- We use it also to make up argument type variables for for data instances.
738 tcDataKindSig Nothing = return []
739 tcDataKindSig (Just kind)
740 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
741 ; span <- getSrcSpanM
742 ; us <- newUniqueSupply
743 ; let uniqs = uniqsFromSupply us
744 ; return [ mk_tv span uniq str kind
745 | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
747 (arg_kinds, res_kind) = splitKindFunTys kind
748 mk_tv loc uniq str kind = mkTyVar name kind
750 name = mkInternalName uniq occ loc
751 occ = mkOccName tvName str
753 dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
756 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
758 badKindSig :: Kind -> SDoc
760 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
764 Note [Avoid name clashes for associated data types]
765 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
766 Consider class C a b where
768 When typechecking the decl for D, we'll invent an extra type variable for D,
769 to fill out its kind. We *don't* want this type variable to be 'a', because
770 in an .hi file we'd get
773 which makes it look as if there are *two* type indices. But there aren't!
774 So we use $a instead, which cannot clash with a user-written type variable.
775 Remember that type variable binders in interface files are just FastStrings,
778 (The tidying phase can't help here because we don't tidy TyCons. Another
779 alternative would be to record the number of indexing parameters in the
783 %************************************************************************
785 Scoped type variables
787 %************************************************************************
790 tcAddScopedTyVars is used for scoped type variables added by pattern
792 e.g. \ ((x::a), (y::a)) -> x+y
793 They never have explicit kinds (because this is source-code only)
794 They are mutable (because they can get bound to a more specific type).
796 Usually we kind-infer and expand type splices, and then
797 tupecheck/desugar the type. That doesn't work well for scoped type
798 variables, because they scope left-right in patterns. (e.g. in the
799 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
801 The current not-very-good plan is to
802 * find all the types in the patterns
803 * find their free tyvars
805 * bring the kinded type vars into scope
806 * BUT throw away the kind-checked type
807 (we'll kind-check it again when we type-check the pattern)
809 This is bad because throwing away the kind checked type throws away
810 its splices. But too bad for now. [July 03]
813 We no longer specify that these type variables must be univerally
814 quantified (lots of email on the subject). If you want to put that
816 a) Do a checkSigTyVars after thing_inside
817 b) More insidiously, don't pass in expected_ty, else
818 we unify with it too early and checkSigTyVars barfs
819 Instead you have to pass in a fresh ty var, and unify
820 it with expected_ty afterwards
823 tcHsPatSigType :: UserTypeCtxt
824 -> LHsType Name -- The type signature
825 -> TcM ([TyVar], -- Newly in-scope type variables
826 Type) -- The signature
827 -- Used for type-checking type signatures in
828 -- (a) patterns e.g f (x::Int) = e
829 -- (b) result signatures e.g. g x :: Int = e
830 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
832 tcHsPatSigType ctxt hs_ty
833 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
834 do { -- Find the type variables that are mentioned in the type
835 -- but not already in scope. These are the ones that
836 -- should be bound by the pattern signature
837 in_scope <- getInLocalScope
838 ; let span = getLoc hs_ty
839 sig_tvs = userHsTyVarBndrs $ map (L span) $
841 nameSetToList (extractHsTyVars hs_ty)
843 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
844 ; checkValidType ctxt sig_ty
845 ; return (tyvars, sig_ty)
848 tcPatSig :: UserTypeCtxt
851 -> TcM (TcType, -- The type to use for "inside" the signature
852 [(Name, TcType)], -- The new bit of type environment, binding
853 -- the scoped type variables
854 CoercionI) -- Coercion due to unification with actual ty
855 tcPatSig ctxt sig res_ty
856 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
858 ; if null sig_tvs then do {
859 -- The type signature binds no type variables,
860 -- and hence is rigid, so use it to zap the res_ty
861 coi <- boxyUnify sig_ty res_ty
862 ; return (sig_ty, [], coi)
865 -- Type signature binds at least one scoped type variable
867 -- A pattern binding cannot bind scoped type variables
868 -- The renamer fails with a name-out-of-scope error
869 -- if a pattern binding tries to bind a type variable,
870 -- So we just have an ASSERT here
871 ; let in_pat_bind = case ctxt of
872 BindPatSigCtxt -> True
874 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
876 -- Check that pat_ty is rigid
877 ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
879 -- Check that all newly-in-scope tyvars are in fact
880 -- constrained by the pattern. This catches tiresome
884 -- f (x :: T a) = ...
885 -- Here 'a' doesn't get a binding. Sigh
886 ; let bad_tvs = filterOut (`elemVarSet` exactTyVarsOfType sig_ty) sig_tvs
887 ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
889 -- Now match the pattern signature against res_ty
890 -- For convenience, and uniform-looking error messages
891 -- we do the matching by allocating meta type variables,
892 -- unifying, and reading out the results.
893 -- This is a strictly local operation.
894 ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
895 ; coi <- boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty)
897 ; sig_tv_tys <- mapM readFilledBox box_tvs
899 -- Check that each is bound to a distinct type variable,
900 -- and one that is not already in scope
901 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
902 ; binds_in_scope <- getScopedTyVarBinds
903 ; check binds_in_scope tv_binds
906 ; return (res_ty, tv_binds, coi)
909 check _ [] = return ()
910 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
911 ; check ((n,ty):in_scope) rest }
913 check_one in_scope n ty
914 = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
915 -- Must bind to a type variable
917 ; checkTc (null dups) (dupInScope n (head dups) ty)
918 -- Must not bind to the same type variable
919 -- as some other in-scope type variable
923 dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
927 %************************************************************************
931 %************************************************************************
933 We would like to get a decent error message from
934 (a) Under-applied type constructors
936 (b) Over-applied type constructors
940 -- The ExpKind datatype means "expected kind" and contains
941 -- some info about just why that kind is expected, to improve
942 -- the error message on a mis-match
943 data ExpKind = EK TcKind EkCtxt
944 data EkCtxt = EkUnk -- Unknown context
945 | EkEqPred -- Second argument of an equality predicate
946 | EkKindSig -- Kind signature
947 | EkArg SDoc Int -- Function, arg posn, expected kind
950 ekLifted, ekOpen :: ExpKind
951 ekLifted = EK liftedTypeKind EkUnk
952 ekOpen = EK openTypeKind EkUnk
954 checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
955 -- A fancy wrapper for 'unifyKind', which tries
956 -- to give decent error messages.
957 -- (checkExpectedKind ty act_kind exp_kind)
958 -- checks that the actual kind act_kind is compatible
959 -- with the expected kind exp_kind
960 -- The first argument, ty, is used only in the error message generation
961 checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
962 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
965 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
967 Just _ -> return () -- Unification succeeded
970 -- So there's definitely an error
971 -- Now to find out what sort
972 exp_kind <- zonkTcKind exp_kind
973 act_kind <- zonkTcKind act_kind
975 env0 <- tcInitTidyEnv
976 let (exp_as, _) = splitKindFunTys exp_kind
977 (act_as, _) = splitKindFunTys act_kind
978 n_exp_as = length exp_as
979 n_act_as = length act_as
981 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
982 (env2, tidy_act_kind) = tidyKind env1 act_kind
984 err | n_exp_as < n_act_as -- E.g. [Maybe]
985 = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
987 -- Now n_exp_as >= n_act_as. In the next two cases,
988 -- n_exp_as == 0, and hence so is n_act_as
989 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
990 = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
991 <+> ptext (sLit "is unlifted")
993 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
994 = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
995 <+> ptext (sLit "is lifted")
997 | otherwise -- E.g. Monad [Int]
998 = ptext (sLit "Kind mis-match")
1000 more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind")
1001 <+> quotes (pprKind tidy_exp_kind) <> comma,
1002 ptext (sLit "but") <+> quotes (ppr ty) <+>
1003 ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
1005 expected_herald EkUnk = ptext (sLit "Expected")
1006 expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
1007 expected_herald EkEqPred = ptext (sLit "The left argument of the equality predicate had")
1008 expected_herald (EkArg fun arg_no)
1009 = ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
1010 <+> quotes fun <+> ptext (sLit ("should have"))
1012 failWithTcM (env2, err $$ more_info)
1015 %************************************************************************
1017 Scoped type variables
1019 %************************************************************************
1022 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1023 pprHsSigCtxt ctxt hs_ty = sep [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
1024 nest 2 (pp_sig ctxt) ]
1026 pp_sig (FunSigCtxt n) = pp_n_colon n
1027 pp_sig (ConArgCtxt n) = pp_n_colon n
1028 pp_sig (ForSigCtxt n) = pp_n_colon n
1029 pp_sig _ = ppr (unLoc hs_ty)
1031 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1033 wobblyPatSig :: [Var] -> SDoc
1034 wobblyPatSig sig_tvs
1035 = hang (ptext (sLit "A pattern type signature cannot bind scoped type variables")
1036 <+> pprQuotedList sig_tvs)
1037 2 (ptext (sLit "unless the pattern has a rigid type context"))
1039 badPatSigTvs :: TcType -> [TyVar] -> SDoc
1040 badPatSigTvs sig_ty bad_tvs
1041 = vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs,
1042 quotes (pprWithCommas ppr bad_tvs),
1043 ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty),
1044 ptext (sLit "but are actually discarded by a type synonym") ]
1045 , ptext (sLit "To fix this, expand the type synonym")
1046 , ptext (sLit "[Note: I hope to lift this restriction in due course]") ]
1048 scopedNonVar :: Name -> Type -> SDoc
1050 = vcat [sep [ptext (sLit "The scoped type variable") <+> quotes (ppr n),
1051 nest 2 (ptext (sLit "is bound to the type") <+> quotes (ppr ty))],
1052 nest 2 (ptext (sLit "You can only bind scoped type variables to type variables"))]
1054 dupInScope :: Name -> Name -> Type -> SDoc
1056 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1057 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1058 ptext (sLit "Distinct scoped type variables must be distinct")])
1060 wrongPredErr :: HsPred Name -> TcM (HsType Name, TcKind)
1061 wrongPredErr pred = failWithTc (text "Predicate used as a type:" <+> ppr pred)