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, kcHsLPred, dsHsLPred,
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
58
----------------------------
60
----------------------------
62
Generally speaking we now type-check types in three phases
64
1. kcHsType: kind check the HsType
65
*includes* performing any TH type splices;
66
so it returns a translated, and kind-annotated, type
68
2. dsHsType: convert from HsType to Type:
70
expand type synonyms [mkGenTyApps]
71
hoist the foralls [tcHsType]
73
3. checkValidType: check the validity of the resulting type
75
Often these steps are done one after the other (tcHsSigType).
76
But in mutually recursive groups of type and class decls we do
77
1 kind-check the whole group
78
2 build TyCons/Classes in a knot-tied way
79
3 check the validity of types in the now-unknotted TyCons/Classes
81
For example, when we find
82
(forall a m. m a -> m a)
83
we bind a,m to kind varibles and kind-check (m a -> m a). This makes
84
a get kind *, and m get kind *->*. Now we typecheck (m a -> m a) in
85
an environment that binds a and m suitably.
87
The kind checker passed to tcHsTyVars needs to look at enough to
88
establish the kind of the tyvar:
89
* For a group of type and class decls, it's just the group, not
90
the rest of the program
91
* For a tyvar bound in a pattern type signature, its the types
92
mentioned in the other type signatures in that bunch of patterns
93
* For a tyvar bound in a RULE, it's the type signatures on other
94
universally quantified variables in the rule
96
Note that this may occasionally give surprising results. For example:
98
data T a b = MkT (a b)
100
Here we deduce a::*->*, b::*
101
But equally valid would be a::(*->*)-> *, b::*->*
106
Some of the validity check could in principle be done by the kind checker,
109
- During desugaring, we normalise by expanding type synonyms. Only
110
after this step can we check things like type-synonym saturation
111
e.g. type T k = k Int
113
Then (T S) is ok, because T is saturated; (T S) expands to (S Int);
114
and then S is saturated. This is a GHC extension.
116
- Similarly, also a GHC extension, we look through synonyms before complaining
117
about the form of a class or instance declaration
119
- Ambiguity checks involve functional dependencies, and it's easier to wait
120
until knots have been resolved before poking into them
122
Also, in a mutually recursive group of types, we can't look at the TyCon until we've
123
finished building the loop. So to keep things simple, we postpone most validity
124
checking until step (3).
128
During step (1) we might fault in a TyCon defined in another module, and it might
129
(via a loop) refer back to a TyCon defined in this module. So when we tie a big
130
knot around type declarations with ARecThing, so that the fault-in code can get
131
the TyCon being defined.
134
%************************************************************************
136
\subsection{Checking types}
138
%************************************************************************
141
tcHsSigType, tcHsSigTypeNC :: UserTypeCtxt -> LHsType Name -> TcM Type
142
-- Do kind checking, and hoist for-alls to the top
143
-- NB: it's important that the foralls that come from the top-level
144
-- HsForAllTy in hs_ty occur *first* in the returned type.
145
-- See Note [Scoped] with TcSigInfo
146
tcHsSigType ctxt hs_ty
147
= addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
148
tcHsSigTypeNC ctxt hs_ty
150
tcHsSigTypeNC ctxt hs_ty
151
= do { (kinded_ty, _kind) <- kc_lhs_type hs_ty
152
-- The kind is checked by checkValidType, and isn't necessarily
153
-- of kind * in a Template Haskell quote eg [t| Maybe |]
154
; ty <- tcHsKindedType kinded_ty
155
; checkValidType ctxt ty
158
tcHsInstHead :: LHsType Name -> TcM ([TyVar], ThetaType, Type)
159
-- Typecheck an instance head. We can't use
160
-- tcHsSigType, because it's not a valid user type.
161
tcHsInstHead (L loc ty)
162
= setSrcSpan loc $ -- No need for an "In the type..." context
163
tc_inst_head ty -- because that comes from the caller
165
-- tc_inst_head expects HsPredTy, which isn't usually even allowed
166
tc_inst_head (HsPredTy pred)
167
= do { pred' <- kcHsPred pred
168
; pred'' <- dsHsPred pred'
169
; return ([], [], mkPredTy pred'') }
171
tc_inst_head (HsForAllTy _ tvs ctxt (L _ (HsPredTy pred)))
172
= kcHsTyVars tvs $ \ tvs' ->
173
do { ctxt' <- kcHsContext ctxt
174
; pred' <- kcHsPred pred
175
; tcTyVarBndrs tvs' $ \ tvs'' ->
176
do { ctxt'' <- mapM dsHsLPred (unLoc ctxt')
177
; pred'' <- dsHsPred pred'
178
; return (tvs'', ctxt'', mkPredTy pred'') } }
180
tc_inst_head _ = failWithTc (ptext (sLit "Malformed instance type"))
182
tcHsQuantifiedType :: [LHsTyVarBndr Name] -> LHsType Name -> TcM ([TyVar], Type)
183
-- Behave very like type-checking (HsForAllTy sig_tvs hs_ty),
184
-- except that we want to keep the tvs separate
185
tcHsQuantifiedType tv_names hs_ty
186
= kcHsTyVars tv_names $ \ tv_names' ->
187
do { kc_ty <- kcHsSigType hs_ty
188
; tcTyVarBndrs tv_names' $ \ tvs ->
189
do { ty <- dsHsType kc_ty
190
; return (tvs, ty) } }
192
-- Used for the deriving(...) items
193
tcHsDeriv :: HsType Name -> TcM ([TyVar], Class, [Type])
194
tcHsDeriv = tc_hs_deriv []
196
tc_hs_deriv :: [LHsTyVarBndr Name] -> HsType Name
197
-> TcM ([TyVar], Class, [Type])
198
tc_hs_deriv tv_names (HsPredTy (HsClassP cls_name hs_tys))
199
= kcHsTyVars tv_names $ \ tv_names' ->
200
do { cls_kind <- kcClass cls_name
201
; (tys, _res_kind) <- kcApps cls_name cls_kind hs_tys
202
; tcTyVarBndrs tv_names' $ \ tyvars ->
203
do { arg_tys <- dsHsTypes tys
204
; cls <- tcLookupClass cls_name
205
; return (tyvars, cls, arg_tys) }}
207
tc_hs_deriv tv_names1 (HsForAllTy _ tv_names2 (L _ []) (L _ ty))
208
= -- Funny newtype deriving form
210
-- where C has arity 2. Hence can't use regular functions
211
tc_hs_deriv (tv_names1 ++ tv_names2) ty
214
= failWithTc (ptext (sLit "Illegal deriving item") <+> ppr other)
217
These functions are used during knot-tying in
218
type and class declarations, when we have to
219
separate kind-checking, desugaring, and validity checking
222
kcHsSigType, kcHsLiftedSigType :: LHsType Name -> TcM (LHsType Name)
223
-- Used for type signatures
224
kcHsSigType ty = addKcTypeCtxt ty $ kcTypeType ty
225
kcHsLiftedSigType ty = addKcTypeCtxt ty $ kcLiftedType ty
227
tcHsKindedType :: LHsType Name -> TcM Type
228
-- Don't do kind checking, nor validity checking.
229
-- This is used in type and class decls, where kinding is
230
-- done in advance, and validity checking is done later
231
-- [Validity checking done later because of knot-tying issues.]
232
tcHsKindedType hs_ty = dsHsType hs_ty
234
tcHsBangType :: LHsType Name -> TcM Type
235
-- Permit a bang, but discard it
236
tcHsBangType (L _ (HsBangTy _ ty)) = tcHsKindedType ty
237
tcHsBangType ty = tcHsKindedType ty
239
tcHsKindedContext :: LHsContext Name -> TcM ThetaType
240
-- Used when we are expecting a ClassContext (i.e. no implicit params)
241
-- Does not do validity checking, like tcHsKindedType
242
tcHsKindedContext hs_theta = addLocM (mapM dsHsLPred) hs_theta
246
%************************************************************************
248
The main kind checker: kcHsType
250
%************************************************************************
252
First a couple of simple wrappers for kcHsType
255
---------------------------
256
kcLiftedType :: LHsType Name -> TcM (LHsType Name)
257
-- The type ty must be a *lifted* *type*
258
kcLiftedType ty = kc_check_lhs_type ty ekLifted
260
---------------------------
261
kcTypeType :: LHsType Name -> TcM (LHsType Name)
262
-- The type ty must be a *type*, but it can be lifted or
263
-- unlifted or an unboxed tuple.
264
kcTypeType ty = kc_check_lhs_type ty ekOpen
266
---------------------------
267
kcCheckLHsType :: LHsType Name -> ExpKind -> TcM (LHsType Name)
268
kcCheckLHsType ty kind = addKcTypeCtxt ty $ kc_check_lhs_type ty kind
271
kc_check_lhs_type :: LHsType Name -> ExpKind -> TcM (LHsType Name)
272
-- Check that the type has the specified kind
273
-- Be sure to use checkExpectedKind, rather than simply unifying
274
-- with OpenTypeKind, because it gives better error messages
275
kc_check_lhs_type (L span ty) exp_kind
277
do { ty' <- kc_check_hs_type ty exp_kind
278
; return (L span ty') }
280
kc_check_lhs_types :: [(LHsType Name, ExpKind)] -> TcM [LHsType Name]
281
kc_check_lhs_types tys_w_kinds
282
= mapM kc_arg tys_w_kinds
284
kc_arg (arg, arg_kind) = kc_check_lhs_type arg arg_kind
287
---------------------------
288
kc_check_hs_type :: HsType Name -> ExpKind -> TcM (HsType Name)
290
-- First some special cases for better error messages
291
-- when we know the expected kind
292
kc_check_hs_type (HsParTy ty) exp_kind
293
= do { ty' <- kc_check_lhs_type ty exp_kind; return (HsParTy ty') }
295
kc_check_hs_type ty@(HsAppTy ty1 ty2) exp_kind
296
= do { let (fun_ty, arg_tys) = splitHsAppTys ty1 ty2
297
; (fun_ty', fun_kind) <- kc_lhs_type fun_ty
298
; arg_tys' <- kcCheckApps fun_ty fun_kind arg_tys ty exp_kind
299
; return (mkHsAppTys fun_ty' arg_tys') }
301
-- This is the general case: infer the kind and compare
302
kc_check_hs_type ty exp_kind
303
= do { (ty', act_kind) <- kc_hs_type ty
304
-- Add the context round the inner check only
305
-- because checkExpectedKind already mentions
306
-- 'ty' by name in any error message
308
; checkExpectedKind (strip ty) act_kind exp_kind
311
-- We infer the kind of the type, and then complain if it's
312
-- not right. But we don't want to complain about
313
-- (ty) or !(ty) or forall a. ty
314
-- when the real difficulty is with the 'ty' part.
315
strip (HsParTy (L _ ty)) = strip ty
316
strip (HsBangTy _ (L _ ty)) = strip ty
317
strip (HsForAllTy _ _ _ (L _ ty)) = strip ty
321
Here comes the main function
324
kcLHsType :: LHsType Name -> TcM (LHsType Name, TcKind)
325
-- Called from outside: set the context
326
kcLHsType ty = addKcTypeCtxt ty (kc_lhs_type ty)
328
kc_lhs_type :: LHsType Name -> TcM (LHsType Name, TcKind)
329
kc_lhs_type (L span ty)
331
do { (ty', kind) <- kc_hs_type ty
332
; return (L span ty', kind) }
334
-- kc_hs_type *returns* the kind of the type, rather than taking an expected
335
-- kind as argument as tcExpr does.
337
-- (a) the kind of (->) is
338
-- forall bx1 bx2. Type bx1 -> Type bx2 -> Type Boxed
339
-- so we'd need to generate huge numbers of bx variables.
340
-- (b) kinds are so simple that the error messages are fine
342
-- The translated type has explicitly-kinded type-variable binders
344
kc_hs_type :: HsType Name -> TcM (HsType Name, TcKind)
345
kc_hs_type (HsParTy ty) = do
346
(ty', kind) <- kc_lhs_type ty
347
return (HsParTy ty', kind)
349
kc_hs_type (HsTyVar name) = do
351
return (HsTyVar name, kind)
353
kc_hs_type (HsListTy ty) = do
354
ty' <- kcLiftedType ty
355
return (HsListTy ty', liftedTypeKind)
357
kc_hs_type (HsPArrTy ty) = do
358
ty' <- kcLiftedType ty
359
return (HsPArrTy ty', liftedTypeKind)
361
kc_hs_type (HsNumTy n)
362
= return (HsNumTy n, liftedTypeKind)
364
kc_hs_type (HsKindSig ty k) = do
365
ty' <- kc_check_lhs_type ty (EK k EkKindSig)
366
return (HsKindSig ty' k, k)
368
kc_hs_type (HsTupleTy Boxed tys) = do
369
tys' <- mapM kcLiftedType tys
370
return (HsTupleTy Boxed tys', liftedTypeKind)
372
kc_hs_type (HsTupleTy Unboxed tys) = do
373
tys' <- mapM kcTypeType tys
374
return (HsTupleTy Unboxed tys', ubxTupleKind)
376
kc_hs_type (HsFunTy ty1 ty2) = do
377
ty1' <- kc_check_lhs_type ty1 (EK argTypeKind EkUnk)
378
ty2' <- kcTypeType ty2
379
return (HsFunTy ty1' ty2', liftedTypeKind)
381
kc_hs_type (HsOpTy ty1 op ty2) = do
382
op_kind <- addLocM kcTyVar op
383
([ty1',ty2'], res_kind) <- kcApps op op_kind [ty1,ty2]
384
return (HsOpTy ty1' op ty2', res_kind)
386
kc_hs_type (HsAppTy ty1 ty2) = do
387
(fun_ty', fun_kind) <- kc_lhs_type fun_ty
388
(arg_tys', res_kind) <- kcApps fun_ty fun_kind arg_tys
389
return (mkHsAppTys fun_ty' arg_tys', res_kind)
391
(fun_ty, arg_tys) = splitHsAppTys ty1 ty2
393
kc_hs_type (HsPredTy pred)
396
kc_hs_type (HsCoreTy ty)
397
= return (HsCoreTy ty, typeKind ty)
399
kc_hs_type (HsForAllTy exp tv_names context ty)
400
= kcHsTyVars tv_names $ \ tv_names' ->
401
do { ctxt' <- kcHsContext context
402
; ty' <- kcLiftedType ty
403
-- The body of a forall is usually a type, but in principle
404
-- there's no reason to prohibit *unlifted* types.
405
-- In fact, GHC can itself construct a function with an
406
-- unboxed tuple inside a for-all (via CPR analyis; see
407
-- typecheck/should_compile/tc170)
409
-- Still, that's only for internal interfaces, which aren't
410
-- kind-checked, so we only allow liftedTypeKind here
412
; return (HsForAllTy exp tv_names' ctxt' ty', liftedTypeKind) }
414
kc_hs_type (HsBangTy b ty)
415
= do { (ty', kind) <- kc_lhs_type ty
416
; return (HsBangTy b ty', kind) }
418
kc_hs_type ty@(HsRecTy _)
419
= failWithTc (ptext (sLit "Unexpected record type") <+> ppr ty)
420
-- Record types (which only show up temporarily in constructor signatures)
421
-- should have been removed by now
423
#ifdef GHCI /* Only if bootstrapped */
424
kc_hs_type (HsSpliceTy sp fvs _) = kcSpliceType sp fvs
426
kc_hs_type ty@(HsSpliceTy {}) = failWithTc (ptext (sLit "Unexpected type splice:") <+> ppr ty)
429
kc_hs_type (HsQuasiQuoteTy {}) = panic "kc_hs_type" -- Eliminated by renamer
431
-- remove the doc nodes here, no need to worry about the location since
432
-- its the same for a doc node and it's child type node
433
kc_hs_type (HsDocTy ty _)
434
= kc_hs_type (unLoc ty)
436
---------------------------
437
kcApps :: Outputable a
439
-> TcKind -- Function kind
440
-> [LHsType Name] -- Arg types
441
-> TcM ([LHsType Name], TcKind) -- Kind-checked args
442
kcApps the_fun fun_kind args
443
= do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
444
; args' <- kc_check_lhs_types args_w_kinds
445
; return (args', res_kind) }
447
kcCheckApps :: Outputable a => a -> TcKind -> [LHsType Name]
448
-> HsType Name -- The type being checked (for err messages only)
449
-> ExpKind -- Expected kind
450
-> TcM [LHsType Name]
451
kcCheckApps the_fun fun_kind args ty exp_kind
452
= do { (args_w_kinds, res_kind) <- splitFunKind (ppr the_fun) 1 fun_kind args
453
; checkExpectedKind ty res_kind exp_kind
454
-- Check the result kind *before* checking argument kinds
455
-- This improves error message; Trac #2994
456
; kc_check_lhs_types args_w_kinds }
458
splitHsAppTys :: LHsType Name -> LHsType Name -> (LHsType Name, [LHsType Name])
459
splitHsAppTys fun_ty arg_ty = split fun_ty [arg_ty]
461
split (L _ (HsAppTy f a)) as = split f (a:as)
464
mkHsAppTys :: LHsType Name -> [LHsType Name] -> HsType Name
465
mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
466
mkHsAppTys fun_ty (arg_ty:arg_tys)
467
= foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
469
mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of
470
-- the application; they are
473
---------------------------
474
splitFunKind :: SDoc -> Int -> TcKind -> [b] -> TcM ([(b,ExpKind)], TcKind)
475
splitFunKind _ _ fk [] = return ([], fk)
476
splitFunKind the_fun arg_no fk (arg:args)
477
= do { mb_fk <- matchExpectedFunKind fk
479
Nothing -> failWithTc too_many_args
480
Just (ak,fk') -> do { (aks, rk) <- splitFunKind the_fun (arg_no+1) fk' args
481
; return ((arg, EK ak (EkArg the_fun arg_no)):aks, rk) } }
483
too_many_args = quotes the_fun <+>
484
ptext (sLit "is applied to too many type arguments")
486
---------------------------
487
kcHsContext :: LHsContext Name -> TcM (LHsContext Name)
488
kcHsContext ctxt = wrapLocM (mapM kcHsLPred) ctxt
490
kcHsLPred :: LHsPred Name -> TcM (LHsPred Name)
491
kcHsLPred = wrapLocM kcHsPred
493
kcHsPred :: HsPred Name -> TcM (HsPred Name)
494
kcHsPred pred = do -- Checks that the result is of kind liftedType
495
(pred', kind) <- kc_pred pred
496
checkExpectedKind pred kind ekLifted
499
---------------------------
500
kc_pred :: HsPred Name -> TcM (HsPred Name, TcKind)
501
-- Does *not* check for a saturated
502
-- application (reason: used from TcDeriv)
503
kc_pred (HsIParam name ty)
504
= do { (ty', kind) <- kc_lhs_type ty
505
; return (HsIParam name ty', kind)
507
kc_pred (HsClassP cls tys)
508
= do { kind <- kcClass cls
509
; (tys', res_kind) <- kcApps cls kind tys
510
; return (HsClassP cls tys', res_kind)
512
kc_pred (HsEqualP ty1 ty2)
513
= do { (ty1', kind1) <- kc_lhs_type ty1
514
-- ; checkExpectedKind ty1 kind1 liftedTypeKind
515
; (ty2', kind2) <- kc_lhs_type ty2
516
-- ; checkExpectedKind ty2 kind2 liftedTypeKind
517
; checkExpectedKind ty2 kind2 (EK kind1 EkEqPred)
518
; return (HsEqualP ty1' ty2', liftedTypeKind)
521
---------------------------
522
kcTyVar :: Name -> TcM TcKind
523
kcTyVar name = do -- Could be a tyvar or a tycon
524
traceTc "lk1" (ppr name)
525
thing <- tcLookup name
526
traceTc "lk2" (ppr name <+> ppr thing)
528
ATyVar _ ty -> return (typeKind ty)
529
AThing kind -> return kind
530
AGlobal (ATyCon tc) -> return (tyConKind tc)
531
_ -> wrongThingErr "type" thing name
533
kcClass :: Name -> TcM TcKind
534
kcClass cls = do -- Must be a class
535
thing <- tcLookup cls
537
AThing kind -> return kind
538
AGlobal (AClass cls) -> return (tyConKind (classTyCon cls))
539
_ -> wrongThingErr "class" thing cls
543
%************************************************************************
547
%************************************************************************
551
* Transforms from HsType to Type
554
It cannot fail, and does no validity checking, except for
555
structural matters, such as
556
(a) spurious ! annotations.
557
(b) a class used as a type
560
dsHsType :: LHsType Name -> TcM Type
561
-- All HsTyVarBndrs in the intput type are kind-annotated
562
dsHsType ty = ds_type (unLoc ty)
564
ds_type :: HsType Name -> TcM Type
565
ds_type ty@(HsTyVar _)
568
ds_type (HsParTy ty) -- Remove the parentheses markers
571
ds_type ty@(HsBangTy {}) -- No bangs should be here
572
= failWithTc (ptext (sLit "Unexpected strictness annotation:") <+> ppr ty)
574
ds_type ty@(HsRecTy {}) -- No bangs should be here
575
= failWithTc (ptext (sLit "Unexpected record type:") <+> ppr ty)
577
ds_type (HsKindSig ty _)
578
= dsHsType ty -- Kind checking done already
580
ds_type (HsListTy ty) = do
581
tau_ty <- dsHsType ty
582
checkWiredInTyCon listTyCon
583
return (mkListTy tau_ty)
585
ds_type (HsPArrTy ty) = do
586
tau_ty <- dsHsType ty
587
checkWiredInTyCon parrTyCon
588
return (mkPArrTy tau_ty)
590
ds_type (HsTupleTy boxity tys) = do
591
tau_tys <- dsHsTypes tys
592
checkWiredInTyCon tycon
593
return (mkTyConApp tycon tau_tys)
595
tycon = tupleTyCon boxity (length tys)
597
ds_type (HsFunTy ty1 ty2) = do
598
tau_ty1 <- dsHsType ty1
599
tau_ty2 <- dsHsType ty2
600
return (mkFunTy tau_ty1 tau_ty2)
602
ds_type (HsOpTy ty1 (L span op) ty2) = do
603
tau_ty1 <- dsHsType ty1
604
tau_ty2 <- dsHsType ty2
605
setSrcSpan span (ds_var_app op [tau_ty1,tau_ty2])
609
tc <- tcLookupTyCon genUnitTyConName
610
return (mkTyConApp tc [])
612
ds_type ty@(HsAppTy _ _)
615
ds_type (HsPredTy pred) = do
616
pred' <- dsHsPred pred
617
return (mkPredTy pred')
619
ds_type (HsForAllTy _ tv_names ctxt ty)
620
= tcTyVarBndrs tv_names $ \ tyvars -> do
621
theta <- mapM dsHsLPred (unLoc ctxt)
623
return (mkSigmaTy tyvars theta tau)
625
ds_type (HsDocTy ty _) -- Remove the doc comment
628
ds_type (HsSpliceTy _ _ kind)
629
= do { kind' <- zonkTcKindToKind kind
630
; newFlexiTyVarTy kind' }
632
ds_type (HsQuasiQuoteTy {}) = panic "ds_type" -- Eliminated by renamer
633
ds_type (HsCoreTy ty) = return ty
635
dsHsTypes :: [LHsType Name] -> TcM [Type]
636
dsHsTypes arg_tys = mapM dsHsType arg_tys
639
Help functions for type applications
640
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
643
ds_app :: HsType Name -> [LHsType Name] -> TcM Type
644
ds_app (HsAppTy ty1 ty2) tys
645
= ds_app (unLoc ty1) (ty2:tys)
648
arg_tys <- dsHsTypes tys
650
HsTyVar fun -> ds_var_app fun arg_tys
651
_ -> do fun_ty <- ds_type ty
652
return (mkAppTys fun_ty arg_tys)
654
ds_var_app :: Name -> [Type] -> TcM Type
655
ds_var_app name arg_tys = do
656
thing <- tcLookup name
658
ATyVar _ ty -> return (mkAppTys ty arg_tys)
659
AGlobal (ATyCon tc) -> return (mkTyConApp tc arg_tys)
660
_ -> wrongThingErr "type" thing name
668
dsHsLPred :: LHsPred Name -> TcM PredType
669
dsHsLPred pred = dsHsPred (unLoc pred)
671
dsHsPred :: HsPred Name -> TcM PredType
672
dsHsPred (HsClassP class_name tys)
673
= do { arg_tys <- dsHsTypes tys
674
; clas <- tcLookupClass class_name
675
; return (ClassP clas arg_tys)
677
dsHsPred (HsEqualP ty1 ty2)
678
= do { arg_ty1 <- dsHsType ty1
679
; arg_ty2 <- dsHsType ty2
680
; return (EqPred arg_ty1 arg_ty2)
682
dsHsPred (HsIParam name ty)
683
= do { arg_ty <- dsHsType ty
684
; return (IParam name arg_ty)
689
addKcTypeCtxt :: LHsType Name -> TcM a -> TcM a
690
-- Wrap a context around only if we want to show that contexts.
691
addKcTypeCtxt (L _ (HsPredTy _)) thing = thing
692
-- Omit invisble ones and ones user's won't grok (HsPred p).
693
addKcTypeCtxt (L _ other_ty) thing = addErrCtxt (typeCtxt other_ty) thing
695
typeCtxt :: HsType Name -> SDoc
696
typeCtxt ty = ptext (sLit "In the type") <+> quotes (ppr ty)
699
%************************************************************************
701
Type-variable binders
703
%************************************************************************
707
kcHsTyVars :: [LHsTyVarBndr Name]
708
-> ([LHsTyVarBndr Name] -> TcM r) -- These binders are kind-annotated
709
-- They scope over the thing inside
711
kcHsTyVars tvs thing_inside
712
= do { kinded_tvs <- mapM (wrapLocM kcHsTyVar) tvs
713
; tcExtendKindEnvTvs kinded_tvs thing_inside }
715
kcHsTyVar :: HsTyVarBndr Name -> TcM (HsTyVarBndr Name)
716
-- Return a *kind-annotated* binder, and a tyvar with a mutable kind in it
717
kcHsTyVar (UserTyVar name _) = UserTyVar name <$> newKindVar
718
kcHsTyVar tv@(KindedTyVar {}) = return tv
721
tcTyVarBndrs :: [LHsTyVarBndr Name] -- Kind-annotated binders, which need kind-zonking
722
-> ([TyVar] -> TcM r)
724
-- Used when type-checking types/classes/type-decls
725
-- Brings into scope immutable TyVars, not mutable ones that require later zonking
726
tcTyVarBndrs bndrs thing_inside = do
727
tyvars <- mapM (zonk . unLoc) bndrs
728
tcExtendTyVarEnv tyvars (thing_inside tyvars)
730
zonk (UserTyVar name kind) = do { kind' <- zonkTcKindToKind kind
731
; return (mkTyVar name kind') }
732
zonk (KindedTyVar name kind) = return (mkTyVar name kind)
734
-----------------------------------
735
tcDataKindSig :: Maybe Kind -> TcM [TyVar]
736
-- GADT decls can have a (perhaps partial) kind signature
737
-- e.g. data T :: * -> * -> * where ...
738
-- This function makes up suitable (kinded) type variables for
739
-- the argument kinds, and checks that the result kind is indeed *.
740
-- We use it also to make up argument type variables for for data instances.
741
tcDataKindSig Nothing = return []
742
tcDataKindSig (Just kind)
743
= do { checkTc (isLiftedTypeKind res_kind) (badKindSig kind)
744
; span <- getSrcSpanM
745
; us <- newUniqueSupply
746
; let uniqs = uniqsFromSupply us
747
; return [ mk_tv span uniq str kind
748
| ((kind, str), uniq) <- arg_kinds `zip` dnames `zip` uniqs ] }
750
(arg_kinds, res_kind) = splitKindFunTys kind
751
mk_tv loc uniq str kind = mkTyVar name kind
753
name = mkInternalName uniq occ loc
754
occ = mkOccName tvName str
756
dnames = map ('$' :) names -- Note [Avoid name clashes for associated data types]
759
names = [ c:cs | cs <- "" : names, c <- ['a'..'z'] ]
761
badKindSig :: Kind -> SDoc
763
= hang (ptext (sLit "Kind signature on data type declaration has non-* return kind"))
767
Note [Avoid name clashes for associated data types]
768
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
769
Consider class C a b where
771
When typechecking the decl for D, we'll invent an extra type variable for D,
772
to fill out its kind. We *don't* want this type variable to be 'a', because
773
in an .hi file we'd get
776
which makes it look as if there are *two* type indices. But there aren't!
777
So we use $a instead, which cannot clash with a user-written type variable.
778
Remember that type variable binders in interface files are just FastStrings,
781
(The tidying phase can't help here because we don't tidy TyCons. Another
782
alternative would be to record the number of indexing parameters in the
786
%************************************************************************
788
Scoped type variables
790
%************************************************************************
793
tcAddScopedTyVars is used for scoped type variables added by pattern
795
e.g. \ ((x::a), (y::a)) -> x+y
796
They never have explicit kinds (because this is source-code only)
797
They are mutable (because they can get bound to a more specific type).
799
Usually we kind-infer and expand type splices, and then
800
tupecheck/desugar the type. That doesn't work well for scoped type
801
variables, because they scope left-right in patterns. (e.g. in the
802
example above, the 'a' in (y::a) is bound by the 'a' in (x::a).
804
The current not-very-good plan is to
805
* find all the types in the patterns
806
* find their free tyvars
808
* bring the kinded type vars into scope
809
* BUT throw away the kind-checked type
810
(we'll kind-check it again when we type-check the pattern)
812
This is bad because throwing away the kind checked type throws away
813
its splices. But too bad for now. [July 03]
816
We no longer specify that these type variables must be univerally
817
quantified (lots of email on the subject). If you want to put that
819
a) Do a checkSigTyVars after thing_inside
820
b) More insidiously, don't pass in expected_ty, else
821
we unify with it too early and checkSigTyVars barfs
822
Instead you have to pass in a fresh ty var, and unify
823
it with expected_ty afterwards
826
tcHsPatSigType :: UserTypeCtxt
827
-> LHsType Name -- The type signature
828
-> TcM ([TyVar], -- Newly in-scope type variables
829
Type) -- The signature
830
-- Used for type-checking type signatures in
831
-- (a) patterns e.g f (x::Int) = e
832
-- (b) result signatures e.g. g x :: Int = e
833
-- (c) RULE forall bndrs e.g. forall (x::Int). f x = x
835
tcHsPatSigType ctxt hs_ty
836
= addErrCtxt (pprHsSigCtxt ctxt hs_ty) $
837
do { -- Find the type variables that are mentioned in the type
838
-- but not already in scope. These are the ones that
839
-- should be bound by the pattern signature
840
in_scope <- getInLocalScope
841
; let span = getLoc hs_ty
842
sig_tvs = userHsTyVarBndrs $ map (L span) $
844
nameSetToList (extractHsTyVars hs_ty)
846
; (tyvars, sig_ty) <- tcHsQuantifiedType sig_tvs hs_ty
847
; checkValidType ctxt sig_ty
848
; return (tyvars, sig_ty)
851
tcPatSig :: UserTypeCtxt
854
-> TcM (TcType, -- The type to use for "inside" the signature
855
[(Name, TcType)], -- The new bit of type environment, binding
856
-- the scoped type variables
857
HsWrapper) -- Coercion due to unification with actual ty
858
-- Of shape: res_ty ~ sig_ty
859
tcPatSig ctxt sig res_ty
860
= do { (sig_tvs, sig_ty) <- tcHsPatSigType ctxt sig
861
-- sig_tvs are the type variables free in 'sig',
862
-- and not already in scope. These are the ones
863
-- that should be brought into scope
865
; if null sig_tvs then do {
866
-- The type signature binds no type variables,
867
-- and hence is rigid, so use it to zap the res_ty
868
wrap <- tcSubType PatSigOrigin (SigSkol ctxt) res_ty sig_ty
869
; return (sig_ty, [], wrap)
872
-- Type signature binds at least one scoped type variable
874
-- A pattern binding cannot bind scoped type variables
875
-- The renamer fails with a name-out-of-scope error
876
-- if a pattern binding tries to bind a type variable,
877
-- So we just have an ASSERT here
878
; let in_pat_bind = case ctxt of
879
BindPatSigCtxt -> True
881
; ASSERT( not in_pat_bind || null sig_tvs ) return ()
883
-- Check that all newly-in-scope tyvars are in fact
884
-- constrained by the pattern. This catches tiresome
888
-- f (x :: T a) = ...
889
-- Here 'a' doesn't get a binding. Sigh
890
; let bad_tvs = filterOut (`elemVarSet` exactTyVarsOfType sig_ty) sig_tvs
891
; checkTc (null bad_tvs) (badPatSigTvs sig_ty bad_tvs)
893
-- Now do a subsumption check of the pattern signature against res_ty
894
; sig_tvs' <- tcInstSigTyVars sig_tvs
895
; let sig_ty' = substTyWith sig_tvs sig_tv_tys' sig_ty
896
sig_tv_tys' = mkTyVarTys sig_tvs'
897
; wrap <- tcSubType PatSigOrigin (SigSkol ctxt) res_ty sig_ty'
899
-- Check that each is bound to a distinct type variable,
900
-- and one that is not already in scope
901
; binds_in_scope <- getScopedTyVarBinds
902
; let tv_binds = map tyVarName sig_tvs `zip` sig_tv_tys'
903
; check binds_in_scope tv_binds
906
; return (sig_ty', tv_binds, wrap)
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
= checkTc (null dups) (dupInScope n (head dups) ty)
915
-- Must not bind to the same type variable
916
-- as some other in-scope type variable
918
dups = [n' | (n',ty') <- in_scope, tcEqType ty' ty]
922
%************************************************************************
926
%************************************************************************
928
We would like to get a decent error message from
929
(a) Under-applied type constructors
931
(b) Over-applied type constructors
935
-- The ExpKind datatype means "expected kind" and contains
936
-- some info about just why that kind is expected, to improve
937
-- the error message on a mis-match
938
data ExpKind = EK TcKind EkCtxt
939
data EkCtxt = EkUnk -- Unknown context
940
| EkEqPred -- Second argument of an equality predicate
941
| EkKindSig -- Kind signature
942
| EkArg SDoc Int -- Function, arg posn, expected kind
945
ekLifted, ekOpen :: ExpKind
946
ekLifted = EK liftedTypeKind EkUnk
947
ekOpen = EK openTypeKind EkUnk
949
checkExpectedKind :: Outputable a => a -> TcKind -> ExpKind -> TcM ()
950
-- A fancy wrapper for 'unifyKind', which tries
951
-- to give decent error messages.
952
-- (checkExpectedKind ty act_kind exp_kind)
953
-- checks that the actual kind act_kind is compatible
954
-- with the expected kind exp_kind
955
-- The first argument, ty, is used only in the error message generation
956
checkExpectedKind ty act_kind (EK exp_kind ek_ctxt)
957
| act_kind `isSubKind` exp_kind -- Short cut for a very common case
960
(_errs, mb_r) <- tryTc (unifyKind exp_kind act_kind)
962
Just _ -> return () -- Unification succeeded
965
-- So there's definitely an error
966
-- Now to find out what sort
967
exp_kind <- zonkTcKind exp_kind
968
act_kind <- zonkTcKind act_kind
970
env0 <- tcInitTidyEnv
971
let (exp_as, _) = splitKindFunTys exp_kind
972
(act_as, _) = splitKindFunTys act_kind
973
n_exp_as = length exp_as
974
n_act_as = length act_as
976
(env1, tidy_exp_kind) = tidyKind env0 exp_kind
977
(env2, tidy_act_kind) = tidyKind env1 act_kind
979
err | n_exp_as < n_act_as -- E.g. [Maybe]
980
= quotes (ppr ty) <+> ptext (sLit "is not applied to enough type arguments")
982
-- Now n_exp_as >= n_act_as. In the next two cases,
983
-- n_exp_as == 0, and hence so is n_act_as
984
| isLiftedTypeKind exp_kind && isUnliftedTypeKind act_kind
985
= ptext (sLit "Expecting a lifted type, but") <+> quotes (ppr ty)
986
<+> ptext (sLit "is unlifted")
988
| isUnliftedTypeKind exp_kind && isLiftedTypeKind act_kind
989
= ptext (sLit "Expecting an unlifted type, but") <+> quotes (ppr ty)
990
<+> ptext (sLit "is lifted")
992
| otherwise -- E.g. Monad [Int]
993
= ptext (sLit "Kind mis-match")
995
more_info = sep [ expected_herald ek_ctxt <+> ptext (sLit "kind")
996
<+> quotes (pprKind tidy_exp_kind) <> comma,
997
ptext (sLit "but") <+> quotes (ppr ty) <+>
998
ptext (sLit "has kind") <+> quotes (pprKind tidy_act_kind)]
1000
expected_herald EkUnk = ptext (sLit "Expected")
1001
expected_herald EkKindSig = ptext (sLit "An enclosing kind signature specified")
1002
expected_herald EkEqPred = ptext (sLit "The left argument of the equality predicate had")
1003
expected_herald (EkArg fun arg_no)
1004
= ptext (sLit "The") <+> speakNth arg_no <+> ptext (sLit "argument of")
1005
<+> quotes fun <+> ptext (sLit ("should have"))
1007
failWithTcM (env2, err $$ more_info)
1010
%************************************************************************
1012
Scoped type variables
1014
%************************************************************************
1017
pprHsSigCtxt :: UserTypeCtxt -> LHsType Name -> SDoc
1018
pprHsSigCtxt ctxt hs_ty = sep [ ptext (sLit "In") <+> pprUserTypeCtxt ctxt <> colon,
1019
nest 2 (pp_sig ctxt) ]
1021
pp_sig (FunSigCtxt n) = pp_n_colon n
1022
pp_sig (ConArgCtxt n) = pp_n_colon n
1023
pp_sig (ForSigCtxt n) = pp_n_colon n
1024
pp_sig _ = ppr (unLoc hs_ty)
1026
pp_n_colon n = ppr n <+> dcolon <+> ppr (unLoc hs_ty)
1028
badPatSigTvs :: TcType -> [TyVar] -> SDoc
1029
badPatSigTvs sig_ty bad_tvs
1030
= vcat [ fsep [ptext (sLit "The type variable") <> plural bad_tvs,
1031
quotes (pprWithCommas ppr bad_tvs),
1032
ptext (sLit "should be bound by the pattern signature") <+> quotes (ppr sig_ty),
1033
ptext (sLit "but are actually discarded by a type synonym") ]
1034
, ptext (sLit "To fix this, expand the type synonym")
1035
, ptext (sLit "[Note: I hope to lift this restriction in due course]") ]
1037
dupInScope :: Name -> Name -> Type -> SDoc
1039
= hang (ptext (sLit "The scoped type variables") <+> quotes (ppr n) <+> ptext (sLit "and") <+> quotes (ppr n'))
1040
2 (vcat [ptext (sLit "are bound to the same type (variable)"),
1041
ptext (sLit "Distinct scoped type variables must be distinct")])
1043
wrongPredErr :: HsPred Name -> TcM (HsType Name, TcKind)
1044
wrongPredErr pred = failWithTc (text "Predicate used as a type:" <+> ppr pred)