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, tcLHsConResTy,
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) = kcSpliceType sp
424 kc_hs_type ty@(HsSpliceTy {}) = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
427 kc_hs_type (HsSpliceTyOut {}) = panic "kc_hs_type" -- Should not happen at all
428 kc_hs_type (HsQuasiQuoteTy {}) = panic "kc_hs_type" -- Eliminated by renamer
430 -- remove the doc nodes here, no need to worry about the location since
431 -- its the same for a doc node and it's child type node
432 kc_hs_type (HsDocTy ty _)
433 = kc_hs_type (unLoc ty)
435 ---------------------------
436 kcApps :: Outputable a
438 -> TcKind -- Function kind
439 -> [LHsType Name] -- Arg types
440 -> TcM ([LHsType Name], TcKind) -- Kind-checked args
441 kcApps the_fun fun_kind args
442 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
443 ; args' <- kc_check_lhs_types args_w_kinds
444 ; return (args', res_kind) }
446 kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
447 -> HsType Name -- The type being checked (for err messages only)
448 -> ExpKind -- Expected kind
449 -> TcM [LHsType Name]
450 kcCheckApps the_fun fun_kind args ty exp_kind
451 = do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
452 ; checkExpectedKind ty res_kind exp_kind
453 -- Check the result kind *before* checking argument kinds
454 -- This improves error message; Trac #2994
455 ; kc_check_lhs_types args_w_kinds }
457 splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
458 splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
460 split (L _ (HsAppTy f a)) as = split f (a:as)
463 mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
464 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
465 mkHsAppTys fun_ty (arg_ty:arg_tys)
466 = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
468 mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
469 -- the application; they are
472 ---------------------------
473 splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
474 splitFunKind _ _ fk [] = return ([], fk)
475 splitFunKind the_fun arg_no fk (arg:args)
476 = do { mb_fk <- unifyFunKind fk
478 Nothing -> failWithTc too_many_args
479 Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
480 ; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
482 too_many_args = quotes the_fun <+>
483 ptext (sLit "is applied to too many type arguments")
485 ---------------------------
486 kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
487 kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
489 kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
490 kcHsLPred = wrapLocM kcHsPred
492 kcHsPred :: HsPred Name -> TcM (HsPred Name)
493 kcHsPred pred = do -- Checks that the result is of kind liftedType
494 (pred', kind) <- kc_pred pred
495 checkExpectedKind pred kind ekLifted
498 ---------------------------
499 kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
500 -- Does *not* check for a saturated
501 -- application (reason: used from TcDeriv)
502 kc_pred (HsIParam name ty)
503 = do { (ty', kind) <- kc_lhs_type ty
504 ; return (HsIParam name ty', kind)
506 kc_pred (HsClassP cls tys)
507 = do { kind <- kcClass cls
508 ; (tys', res_kind) <- kcApps cls kind tys
509 ; return (HsClassP cls tys', res_kind)
511 kc_pred (HsEqualP ty1 ty2)
512 = do { (ty1', kind1) <- kc_lhs_type ty1
513 -- ; checkExpectedKind ty1 kind1 liftedTypeKind
514 ; (ty2', kind2) <- kc_lhs_type ty2
515 -- ; checkExpectedKind ty2 kind2 liftedTypeKind
516 ; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
517 ; return (HsEqualP ty1' ty2', liftedTypeKind)
520 ---------------------------
521 kcTyVar :: Name -> TcM TcKind
522 kcTyVar name = do -- Could be a tyvar or a tycon
523 traceTc (text "lk1" <+> ppr name)
524 thing <- tcLookup name
525 traceTc (text "lk2" <+> ppr name <+> ppr thing)
527 ATyVar _ ty -> return (typeKind ty)
528 AThing kind -> return kind
529 AGlobal (ATyCon tc) -> return (tyConKind tc)
530 _ -> wrongThingErr "type" thing name
532 kcClass :: Name -> TcM TcKind
533 kcClass cls = do -- Must be a class
534 thing <- tcLookup cls
536 AThing kind -> return kind
537 AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
538 _ -> wrongThingErr "class" thing cls
542 %************************************************************************
546 %************************************************************************
550 * Transforms from HsType to Type
553 It cannot fail, and does no validity checking, except for
554 structural matters, such as
555 (a) spurious ! annotations.
556 (b) a class used as a type
559 dsHsType :: LHsType Name -> TcM Type
560 -- All HsTyVarBndrs in the intput type are kind-annotated
561 dsHsType ty = ds_type (unLoc ty)
563 ds_type :: HsType Name -> TcM Type
564 ds_type ty@(HsTyVar _)
567 ds_type (HsParTy ty) -- Remove the parentheses markers
570 ds_type ty@(HsBangTy {}) -- No bangs should be here
571 = failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
573 ds_type ty@(HsRecTy {}) -- No bangs should be here
574 = failWithTc (ptext (sLit "Unexpected record type:") <+> ppr ty)
576 ds_type (HsKindSig ty _)
577 = dsHsType ty -- Kind checking done already
579 ds_type (HsListTy ty) = do
580 tau_ty <- dsHsType ty
581 checkWiredInTyCon listTyCon
582 return (mkListTy tau_ty)
584 ds_type (HsPArrTy ty) = do
585 tau_ty <- dsHsType ty
586 checkWiredInTyCon parrTyCon
587 return (mkPArrTy tau_ty)
589 ds_type (HsTupleTy boxity tys) = do
590 tau_tys <- dsHsTypes tys
591 checkWiredInTyCon tycon
592 return (mkTyConApp tycon tau_tys)
594 tycon = tupleTyCon boxity (length tys)
596 ds_type (HsFunTy ty1 ty2) = do
597 tau_ty1 <- dsHsType ty1
598 tau_ty2 <- dsHsType ty2
599 return (mkFunTy tau_ty1 tau_ty2)
601 ds_type (HsOpTy ty1 (L span op) ty2) = do
602 tau_ty1 <- dsHsType ty1
603 tau_ty2 <- dsHsType ty2
604 setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
608 tc <- tcLookupTyCon genUnitTyConName
609 return (mkTyConApp tc [])
611 ds_type ty@(HsAppTy _ _)
614 ds_type (HsPredTy pred) = do
615 pred' <- dsHsPred pred
616 return (mkPredTy pred')
618 ds_type (HsForAllTy _ tv_names ctxt ty)
619 = tcTyVarBndrs tv_names $ \ tyvars -> do
620 theta <- mapM dsHsLPred (unLoc ctxt)
622 return (mkSigmaTy tyvars theta tau)
624 ds_type (HsDocTy ty _) -- Remove the doc comment
627 ds_type (HsSpliceTyOut kind)
628 = do { kind' <- zonkTcKindToKind kind
629 ; newFlexiTyVarTy kind' }
631 ds_type (HsSpliceTy {}) = panic "ds_type"
632 ds_type (HsQuasiQuoteTy {}) = panic "ds_type" -- Eliminated by renamer
634 dsHsTypes :: [LHsType Name] -> TcM [Type]
635 dsHsTypes arg_tys = mapM dsHsType arg_tys
638 Help functions for type applications
639 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
642 ds_app :: HsType Name -> [LHsType Name] -> TcM Type
643 ds_app (HsAppTy ty1 ty2) tys
644 = ds_app (unLoc ty1) (ty2:tys)
647 arg_tys <- dsHsTypes tys
649 HsTyVar fun -> ds_var_app fun arg_tys
650 _ -> do fun_ty <- ds_type ty
651 return (mkAppTys fun_ty arg_tys)
653 ds_var_app :: Name -> [Type] -> TcM Type
654 ds_var_app name arg_tys = do
655 thing <- tcLookup name
657 ATyVar _ ty -> return (mkAppTys ty arg_tys)
658 AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
659 _ -> wrongThingErr "type" thing name
667 dsHsLPred :: LHsPred Name -> TcM PredType
668 dsHsLPred pred = dsHsPred (unLoc pred)
670 dsHsPred :: HsPred Name -> TcM PredType
671 dsHsPred (HsClassP class_name tys)
672 = do { arg_tys <- dsHsTypes tys
673 ; clas <- tcLookupClass class_name
674 ; return (ClassP clas arg_tys)
676 dsHsPred (HsEqualP ty1 ty2)
677 = do { arg_ty1 <- dsHsType ty1
678 ; arg_ty2 <- dsHsType ty2
679 ; return (EqPred arg_ty1 arg_ty2)
681 dsHsPred (HsIParam name ty)
682 = do { arg_ty <- dsHsType ty
683 ; return (IParam name arg_ty)
687 GADT constructor signatures
690 tcLHsConResTy :: LHsType Name -> TcM (TyCon, [TcType])
691 tcLHsConResTy (L span res_ty)
693 case get_args res_ty [] of
694 (HsTyVar tc_name, args)
695 -> do { args' <- mapM dsHsType args
696 ; thing <- tcLookup tc_name
698 AGlobal (ATyCon tc) -> return (tc, args')
699 _ -> failWithTc (badGadtDecl res_ty) }
700 _ -> failWithTc (badGadtDecl res_ty)
702 -- We can't call dsHsType on res_ty, and then do tcSplitTyConApp_maybe
703 -- because that causes a black hole, and for good reason. Building
704 -- the type means expanding type synonyms, and we can't do that
705 -- inside the "knot". So we have to work by steam.
706 get_args (HsAppTy (L _ fun) arg) args = get_args fun (arg:args)
707 get_args (HsParTy (L _ ty)) args = get_args ty args
708 get_args (HsOpTy ty1 (L _ tc) ty2) args = (HsTyVar tc, ty1:ty2:args)
709 get_args ty args = (ty, args)
711 badGadtDecl :: HsType Name -> SDoc
713 = hang (ptext (sLit "Malformed constructor result type:"))
716 addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
717 -- Wrap a context around only if we want to show that contexts.
718 addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
719 -- Omit invisble ones and ones user's won't grok (HsPred p).
720 addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
722 typeCtxt :: HsType Name -> SDoc
723 typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
726 %************************************************************************
728 Type-variable binders
730 %************************************************************************
734 kcHsTyVars :: [LHsTyVarBndr Name]
735 -> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
736 -- They scope over the thing inside
738 kcHsTyVars tvs thing_inside = do
739 bndrs <- mapM (wrapLocM kcHsTyVar) tvs
740 tcExtendKindEnvTvs bndrs (thing_inside bndrs)
742 kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
743 -- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
744 kcHsTyVar (UserTyVar name) = KindedTyVar name <$> newKindVar
745 kcHsTyVar (KindedTyVar name kind) = return (KindedTyVar name kind)
748 tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
749 -> ([TyVar] -> TcM r)
751 -- Used when type-checking types/classes/type-decls
752 -- Brings into scope immutable TyVars, not mutable ones that require later zonking
753 tcTyVarBndrs bndrs thing_inside = do
754 tyvars <- mapM (zonk . unLoc) bndrs
755 tcExtendTyVarEnv tyvars (thing_inside tyvars)
757 zonk (KindedTyVar name kind) = do { kind' <- zonkTcKindToKind kind
758 ; return (mkTyVar name kind') }
759 zonk (UserTyVar name) = WARN( True, ptext (sLit "Un-kinded tyvar") <+> ppr name )
760 return (mkTyVar name liftedTypeKind)
762 -----------------------------------
763 tcDataKindSig :: Maybe Kind -> TcM [TyVar]
764 -- GADT decls can have a (perhaps partial) kind signature
765 -- e.g. data T :: * -> * -> * where ...
766 -- This function makes up suitable (kinded) type variables for
767 -- the argument kinds, and checks that the result kind is indeed *.
768 -- We use it also to make up argument type variables for for data instances.
769 tcDataKindSig Nothing = return []
770 tcDataKindSig (Just kind)
771 = do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
772 ; span <- getSrcSpanM
773 ; us <- newUniqueSupply
774 ; let uniqs = uniqsFromSupply us
775 ; return [ mk_tv span uniq str kind
776 | ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
778 (arg_kinds, res_kind) = splitKindFunTys kind
779 mk_tv loc uniq str kind = mkTyVar name kind
781 name = mkInternalName uniq occ loc
782 occ = mkOccName tvName str
784 dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
787 names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
789 badKindSig :: Kind -> SDoc
791 = hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
795 Note [Avoid name clashes for associated data types]
796 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
797 Consider class C a b where
799 When typechecking the decl for D, we'll invent an extra type variable for D,
800 to fill out its kind. We *don't* want this type variable to be 'a', because
801 in an .hi file we'd get
804 which makes it look as if there are *two* type indices. But there aren't!
805 So we use $a instead, which cannot clash with a user-written type variable.
806 Remember that type variable binders in interface files are just FastStrings,
809 (The tidying phase can't help here because we don't tidy TyCons. Another
810 alternative would be to record the number of indexing parameters in the
814 %************************************************************************
816 Scoped type variables
818 %************************************************************************
821 tcAddScopedTyVars is used for scoped type variables added by pattern
823 e.g. \ ((x::a), (y::a)) -> x+y
824 They never have explicit kinds (because this is source-code only)
825 They are mutable (because they can get bound to a more specific type).
827 Usually we kind-infer and expand type splices, and then
828 tupecheck/desugar the type. That doesn't work well for scoped type
829 variables, because they scope left-right in patterns. (e.g. in the
830 example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
832 The current not-very-good plan is to
833 * find all the types in the patterns
834 * find their free tyvars
836 * bring the kinded type vars into scope
837 * BUT throw away the kind-checked type
838 (we'll kind-check it again when we type-check the pattern)
840 This is bad because throwing away the kind checked type throws away
841 its splices. But too bad for now. [July 03]
844 We no longer specify that these type variables must be univerally
845 quantified (lots of email on the subject). If you want to put that
847 a) Do a checkSigTyVars after thing_inside
848 b) More insidiously, don't pass in expected_ty, else
849 we unify with it too early and checkSigTyVars barfs
850 Instead you have to pass in a fresh ty var, and unify
851 it with expected_ty afterwards
854 tcHsPatSigType :: UserTypeCtxt
855 -> LHsType Name -- The type signature
856 -> TcM ([TyVar], -- Newly in-scope type variables
857 Type) -- The signature
858 -- Used for type-checking type signatures in
859 -- (a) patterns e.g f (x::Int) = e
860 -- (b) result signatures e.g. g x :: Int = e
861 -- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
863 tcHsPatSigType ctxt hs_ty
864 = addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
865 do { -- Find the type variables that are mentioned in the type
866 -- but not already in scope. These are the ones that
867 -- should be bound by the pattern signature
868 in_scope <- getInLocalScope
869 ; let span = getLoc hs_ty
870 sig_tvs = [ L span (UserTyVar n)
871 | n <- nameSetToList (extractHsTyVars hs_ty),
874 ; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
875 ; checkValidType ctxt sig_ty
876 ; return (tyvars, sig_ty)
879 tcPatSig :: UserTypeCtxt
882 -> TcM (TcType, -- The type to use for "inside" the signature
883 [(Name, TcType)], -- The new bit of type environment, binding
884 -- the scoped type variables
885 CoercionI) -- Coercion due to unification with actual ty
886 tcPatSig ctxt sig res_ty
887 = do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
889 ; if null sig_tvs then do {
890 -- The type signature binds no type variables,
891 -- and hence is rigid, so use it to zap the res_ty
892 coi <- boxyUnify sig_ty res_ty
893 ; return (sig_ty, [], coi)
896 -- Type signature binds at least one scoped type variable
898 -- A pattern binding cannot bind scoped type variables
899 -- The renamer fails with a name-out-of-scope error
900 -- if a pattern binding tries to bind a type variable,
901 -- So we just have an ASSERT here
902 ; let in_pat_bind = case ctxt of
903 BindPatSigCtxt -> True
905 ; ASSERT( not in_pat_bind || null sig_tvs ) return ()
907 -- Check that pat_ty is rigid
908 ; checkTc (isRigidTy res_ty) (wobblyPatSig sig_tvs)
910 -- Check that all newly-in-scope tyvars are in fact
911 -- constrained by the pattern. This catches tiresome
915 -- f (x :: T a) = ...
916 -- Here 'a' doesn't get a binding. Sigh
917 ; let bad_tvs = filterOut (`elemVarSet` exactTyVarsOfType sig_ty) sig_tvs
918 ; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
920 -- Now match the pattern signature against res_ty
921 -- For convenience, and uniform-looking error messages
922 -- we do the matching by allocating meta type variables,
923 -- unifying, and reading out the results.
924 -- This is a strictly local operation.
925 ; box_tvs <- mapM tcInstBoxyTyVar sig_tvs
926 ; coi <- boxyUnify (substTyWith sig_tvs (mkTyVarTys box_tvs) sig_ty)
928 ; sig_tv_tys <- mapM readFilledBox box_tvs
930 -- Check that each is bound to a distinct type variable,
931 -- and one that is not already in scope
932 ; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys
933 ; binds_in_scope <- getScopedTyVarBinds
934 ; check binds_in_scope tv_binds
937 ; return (res_ty, tv_binds, coi)
940 check _ [] = return ()
941 check in_scope ((n,ty):rest) = do { check_one in_scope n ty
942 ; check ((n,ty):in_scope) rest }
944 check_one in_scope n ty
945 = do { checkTc (tcIsTyVarTy ty) (scopedNonVar n ty)
946 -- Must bind to a type variable
948 ; checkTc (null dups) (dupInScope n (head dups) ty)
949 -- Must not bind to the same type variable
950 -- as some other in-scope type variable
954 dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
958 %************************************************************************
962 %************************************************************************
964 We would like to get a decent error message from
965 (a) Under-applied type constructors
967 (b) Over-applied type constructors
971 -- The ExpKind datatype means "expected kind" and contains
972 -- some info about just why that kind is expected, to improve
973 -- the error message on a mis-match
974 data ExpKind = EK TcKind EkCtxt
975 data EkCtxt = EkUnk -- Unknown context
976 | EkEqPred -- Second argument of an equality predicate
977 | EkKindSig -- Kind signature
978 | EkArg SDoc Int -- Function, arg posn, expected kind
981 ekLifted, ekOpen :: ExpKind
982 ekLifted = EK liftedTypeKind EkUnk
983 ekOpen = EK openTypeKind EkUnk
985 checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
986 -- A fancy wrapper for 'unifyKind', which tries
987 -- to give decent error messages.
988 -- (checkExpectedKind ty act_kind exp_kind)
989 -- checks that the actual kind act_kind is compatible
990 -- with the expected kind exp_kind
991 -- The first argument, ty, is used only in the error message generation
992 checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
993 | act_kind `isSubKind` exp_kind -- Short cut for a very common case
996 (_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
998 Just _ -> return () -- Unification succeeded
1001 -- So there's definitely an error
1002 -- Now to find out what sort
1003 exp_kind <- zonkTcKind exp_kind
1004 act_kind <- zonkTcKind act_kind
1006 env0 <- tcInitTidyEnv
1007 let (exp_as, _) = splitKindFunTys exp_kind
1008 (act_as, _) = splitKindFunTys act_kind
1009 n_exp_as = length exp_as
1010 n_act_as = length act_as
1012 (env1, tidy_exp_kind) = tidyKind env0 exp_kind
1013 (env2, tidy_act_kind) = tidyKind env1 act_kind
1015 err | n_exp_as < n_act_as -- E.g. [Maybe]
1016 = quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
1018 -- Now n_exp_as >= n_act_as. In the next two cases,
1019 -- n_exp_as == 0, and hence so is n_act_as
1020 | isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
1021 = ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
1022 <+> ptext (sLit "is unlifted")
1024 | isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
1025 = ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
1026 <+> ptext (sLit "is lifted")
1028 | otherwise -- E.g. Monad [Int]
1029 = ptext (sLit "Kind mis-match")
1031 more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind")
1032 <+> quotes (pprKind tidy_exp_kind) <> comma,
1033 ptext (sLit "but") <+> quotes (ppr ty) <+>
1034 ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
1036 expected_herald EkUnk = ptext (sLit "Expected")
1037 expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
1038 expected_herald EkEqPred = ptext (sLit "The left argument of the equality predicate had")
1039 expected_herald (EkArg fun arg_no)
1040 = ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
1041 <+> quotes fun <+> ptext (sLit ("should have"))
1043 failWithTcM (env2, err $$ more_info)
1046 %************************************************************************
1048 Scoped type variables
1050 %************************************************************************
1053 pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1054 pprHsSigCtxt ctxt hs_ty = sep [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
1055 nest 2 (pp_sig ctxt) ]
1057 pp_sig (FunSigCtxt n) = pp_n_colon n
1058 pp_sig (ConArgCtxt n) = pp_n_colon n
1059 pp_sig (ForSigCtxt n) = pp_n_colon n
1060 pp_sig _ = ppr (unLoc hs_ty)
1062 pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1064 wobblyPatSig :: [Var] -> SDoc
1065 wobblyPatSig sig_tvs
1066 = hang (ptext (sLit "A pattern type signature cannot bind scoped type variables")
1067 <+> pprQuotedList sig_tvs)
1068 2 (ptext (sLit "unless the pattern has a rigid type context"))
1070 badPatSigTvs :: TcType -> [TyVar] -> SDoc
1071 badPatSigTvs sig_ty bad_tvs
1072 = vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs,
1073 quotes (pprWithCommas ppr bad_tvs),
1074 ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty),
1075 ptext (sLit "but are actually discarded by a type synonym") ]
1076 , ptext (sLit "To fix this, expand the type synonym")
1077 , ptext (sLit "[Note: I hope to lift this restriction in due course]") ]
1079 scopedNonVar :: Name -> Type -> SDoc
1081 = vcat [sep [ptext (sLit "The scoped type variable") <+> quotes (ppr n),
1082 nest 2 (ptext (sLit "is bound to the type") <+> quotes (ppr ty))],
1083 nest 2 (ptext (sLit "You can only bind scoped type variables to type variables"))]
1085 dupInScope :: Name -> Name -> Type -> SDoc
1087 = hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1088 2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1089 ptext (sLit "Distinct scoped type variables must be distinct")])
1091 wrongPredErr :: HsPred Name -> TcM (HsType Name, TcKind)
1092 wrongPredErr pred = failWithTc (text "Predicate used as a type:" <+> ppr pred)