2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1996-1998
6 TcTyClsDecls: Typecheck type and class declarations
10 tcTyAndClassDecls, tcFamInstDecl, mkAuxBinds
13 #include "HsVersions.h"
27 import TysWiredIn ( unitTy )
34 import MkId ( rEC_SEL_ERROR_ID )
50 import Unique ( mkBuiltinUnique )
55 import Control.Monad ( mplus )
59 %************************************************************************
61 \subsection{Type checking for type and class declarations}
63 %************************************************************************
67 Consider a mutually-recursive group, binding
68 a type constructor T and a class C.
70 Step 1: getInitialKind
71 Construct a KindEnv by binding T and C to a kind variable
74 In that environment, do a kind check
76 Step 3: Zonk the kinds
78 Step 4: buildTyConOrClass
79 Construct an environment binding T to a TyCon and C to a Class.
80 a) Their kinds comes from zonking the relevant kind variable
81 b) Their arity (for synonyms) comes direct from the decl
82 c) The funcional dependencies come from the decl
83 d) The rest comes a knot-tied binding of T and C, returned from Step 4
84 e) The variances of the tycons in the group is calculated from
88 In this environment, walk over the decls, constructing the TyCons and Classes.
89 This uses in a strict way items (a)-(c) above, which is why they must
90 be constructed in Step 4. Feed the results back to Step 4.
91 For this step, pass the is-recursive flag as the wimp-out flag
95 Step 6: Extend environment
96 We extend the type environment with bindings not only for the TyCons and Classes,
97 but also for their "implicit Ids" like data constructors and class selectors
99 Step 7: checkValidTyCl
100 For a recursive group only, check all the decls again, just
101 to check all the side conditions on validity. We could not
102 do this before because we were in a mutually recursive knot.
104 Identification of recursive TyCons
105 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
106 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
109 Identifying a TyCon as recursive serves two purposes
111 1. Avoid infinite types. Non-recursive newtypes are treated as
112 "transparent", like type synonyms, after the type checker. If we did
113 this for all newtypes, we'd get infinite types. So we figure out for
114 each newtype whether it is "recursive", and add a coercion if so. In
115 effect, we are trying to "cut the loops" by identifying a loop-breaker.
117 2. Avoid infinite unboxing. This is nothing to do with newtypes.
121 Well, this function diverges, but we don't want the strictness analyser
122 to diverge. But the strictness analyser will diverge because it looks
123 deeper and deeper into the structure of T. (I believe there are
124 examples where the function does something sane, and the strictness
125 analyser still diverges, but I can't see one now.)
127 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
128 newtypes. I did this as an experiment, to try to expose cases in which
129 the coercions got in the way of optimisations. If it turns out that we
130 can indeed always use a coercion, then we don't risk recursive types,
131 and don't need to figure out what the loop breakers are.
133 For newtype *families* though, we will always have a coercion, so they
134 are always loop breakers! So you can easily adjust the current
135 algorithm by simply treating all newtype families as loop breakers (and
136 indeed type families). I think.
139 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
140 -> TcM (TcGblEnv, -- Input env extended by types and classes
141 -- and their implicit Ids,DataCons
142 HsValBinds Name) -- Renamed bindings for record selectors
143 -- Fails if there are any errors
145 tcTyAndClassDecls boot_details allDecls
146 = checkNoErrs $ -- The code recovers internally, but if anything gave rise to
147 -- an error we'd better stop now, to avoid a cascade
148 do { -- Omit instances of type families; they are handled together
149 -- with the *heads* of class instances
150 ; let decls = filter (not . isFamInstDecl . unLoc) allDecls
152 -- First check for cyclic type synonysm or classes
153 -- See notes with checkCycleErrs
154 ; checkCycleErrs decls
156 ; traceTc (text "tcTyAndCl" <+> ppr mod)
157 ; (syn_tycons, alg_tyclss) <- fixM (\ ~(_rec_syn_tycons, rec_alg_tyclss) ->
158 do { let { -- Seperate ordinary synonyms from all other type and
159 -- class declarations and add all associated type
160 -- declarations from type classes. The latter is
161 -- required so that the temporary environment for the
162 -- knot includes all associated family declarations.
163 ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
165 ; alg_at_decls = concatMap addATs alg_decls
167 -- Extend the global env with the knot-tied results
168 -- for data types and classes
170 -- We must populate the environment with the loop-tied
171 -- T's right away, because the kind checker may "fault
172 -- in" some type constructors that recursively
174 ; let gbl_things = mkGlobalThings alg_at_decls rec_alg_tyclss
175 ; tcExtendRecEnv gbl_things $ do
177 -- Kind-check the declarations
178 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
180 ; let { -- Calculate rec-flag
181 ; calc_rec = calcRecFlags boot_details rec_alg_tyclss
182 ; tc_decl = addLocM (tcTyClDecl calc_rec) }
184 -- Type-check the type synonyms, and extend the envt
185 ; syn_tycons <- tcSynDecls kc_syn_decls
186 ; tcExtendGlobalEnv syn_tycons $ do
188 -- Type-check the data types and classes
189 { alg_tyclss <- mapM tc_decl kc_alg_decls
190 ; return (syn_tycons, concat alg_tyclss)
192 -- Finished with knot-tying now
193 -- Extend the environment with the finished things
194 ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
196 -- Perform the validity check
197 { traceTc (text "ready for validity check")
198 ; mapM_ (addLocM checkValidTyCl) decls
199 ; traceTc (text "done")
201 -- Add the implicit things;
202 -- we want them in the environment because
203 -- they may be mentioned in interface files
204 -- NB: All associated types and their implicit things will be added a
205 -- second time here. This doesn't matter as the definitions are
207 ; let { implicit_things = concatMap implicitTyThings alg_tyclss
208 ; aux_binds = mkAuxBinds alg_tyclss }
209 ; traceTc ((text "Adding" <+> ppr alg_tyclss)
210 $$ (text "and" <+> ppr implicit_things))
211 ; env <- tcExtendGlobalEnv implicit_things getGblEnv
212 ; return (env, aux_binds) }
215 -- Pull associated types out of class declarations, to tie them into the
217 -- NB: We put them in the same place in the list as `tcTyClDecl' will
218 -- eventually put the matching `TyThing's. That's crucial; otherwise,
219 -- the two argument lists of `mkGlobalThings' don't match up.
220 addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
223 mkGlobalThings :: [LTyClDecl Name] -- The decls
224 -> [TyThing] -- Knot-tied, in 1-1 correspondence with the decls
226 -- Driven by the Decls, and treating the TyThings lazily
227 -- make a TypeEnv for the new things
228 mkGlobalThings decls things
229 = map mk_thing (decls `zipLazy` things)
231 mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
233 mk_thing (L _ decl, ~(ATyCon tc))
234 = (tcdName decl, ATyCon tc)
238 %************************************************************************
240 Type checking family instances
242 %************************************************************************
244 Family instances are somewhat of a hybrid. They are processed together with
245 class instance heads, but can contain data constructors and hence they share a
246 lot of kinding and type checking code with ordinary algebraic data types (and
250 tcFamInstDecl :: LTyClDecl Name -> TcM TyThing
251 tcFamInstDecl (L loc decl)
252 = -- Prime error recovery, set source location
255 do { -- type families require -XTypeFamilies and can't be in an
257 ; type_families <- doptM Opt_TypeFamilies
258 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
259 ; checkTc type_families $ badFamInstDecl (tcdLName decl)
260 ; checkTc (not is_boot) $ badBootFamInstDeclErr
262 -- Perform kind and type checking
263 ; tc <- tcFamInstDecl1 decl
264 ; checkValidTyCon tc -- Remember to check validity;
265 -- no recursion to worry about here
266 ; return (ATyCon tc) }
268 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
271 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
272 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
273 do { -- check that the family declaration is for a synonym
274 checkTc (isOpenTyCon family) (notFamily family)
275 ; checkTc (isSynTyCon family) (wrongKindOfFamily family)
277 ; -- (1) kind check the right-hand side of the type equation
278 ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) (EK resKind EkUnk)
279 -- ToDo: the ExpKind could be better
281 -- we need the exact same number of type parameters as the family
283 ; let famArity = tyConArity family
284 ; checkTc (length k_typats == famArity) $
285 wrongNumberOfParmsErr famArity
287 -- (2) type check type equation
288 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
289 ; t_typats <- mapM tcHsKindedType k_typats
290 ; t_rhs <- tcHsKindedType k_rhs
292 -- (3) check the well-formedness of the instance
293 ; checkValidTypeInst t_typats t_rhs
295 -- (4) construct representation tycon
296 ; rep_tc_name <- newFamInstTyConName tc_name loc
297 ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs)
298 (typeKind t_rhs) (Just (family, t_typats))
301 -- "newtype instance" and "data instance"
302 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
304 = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
305 do { -- check that the family declaration is for the right kind
306 checkTc (isOpenTyCon fam_tycon) (notFamily fam_tycon)
307 ; checkTc (isAlgTyCon fam_tycon) (wrongKindOfFamily fam_tycon)
309 ; -- (1) kind check the data declaration as usual
310 ; k_decl <- kcDataDecl decl k_tvs
311 ; let k_ctxt = tcdCtxt k_decl
312 k_cons = tcdCons k_decl
314 -- result kind must be '*' (otherwise, we have too few patterns)
315 ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
317 -- (2) type check indexed data type declaration
318 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
319 ; unbox_strict <- doptM Opt_UnboxStrictFields
321 -- kind check the type indexes and the context
322 ; t_typats <- mapM tcHsKindedType k_typats
323 ; stupid_theta <- tcHsKindedContext k_ctxt
326 -- (a) left-hand side contains no type family applications
327 -- (vanilla synonyms are fine, though, and we checked for
329 ; mapM_ checkTyFamFreeness t_typats
331 -- Check that we don't use GADT syntax in H98 world
332 ; gadt_ok <- doptM Opt_GADTs
333 ; checkTc (gadt_ok || consUseH98Syntax cons) (badGadtDecl tc_name)
335 -- (b) a newtype has exactly one constructor
336 ; checkTc (new_or_data == DataType || isSingleton k_cons) $
337 newtypeConError tc_name (length k_cons)
339 -- (4) construct representation tycon
340 ; rep_tc_name <- newFamInstTyConName tc_name loc
341 ; let ex_ok = True -- Existentials ok for type families!
342 ; fixM (\ rep_tycon -> do
343 { let orig_res_ty = mkTyConApp fam_tycon t_typats
344 ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
345 (t_tvs, orig_res_ty) k_cons
348 DataType -> return (mkDataTyConRhs data_cons)
349 NewType -> ASSERT( not (null data_cons) )
350 mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
351 ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
352 False h98_syntax (Just (fam_tycon, t_typats))
353 -- We always assume that indexed types are recursive. Why?
354 -- (1) Due to their open nature, we can never be sure that a
355 -- further instance might not introduce a new recursive
356 -- dependency. (2) They are always valid loop breakers as
357 -- they involve a coercion.
361 h98_syntax = case cons of -- All constructors have same shape
362 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
365 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
367 -- Kind checking of indexed types
370 -- Kind check type patterns and kind annotate the embedded type variables.
372 -- * Here we check that a type instance matches its kind signature, but we do
373 -- not check whether there is a pattern for each type index; the latter
374 -- check is only required for type synonym instances.
376 kcIdxTyPats :: TyClDecl Name
377 -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
378 -- ^^kinded tvs ^^kinded ty pats ^^res kind
380 kcIdxTyPats decl thing_inside
381 = kcHsTyVars (tcdTyVars decl) $ \tvs ->
382 do { let tc_name = tcdLName decl
383 ; fam_tycon <- tcLookupLocatedTyCon tc_name
384 ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
385 ; hs_typats = fromJust $ tcdTyPats decl }
387 -- we may not have more parameters than the kind indicates
388 ; checkTc (length kinds >= length hs_typats) $
389 tooManyParmsErr (tcdLName decl)
391 -- type functions can have a higher-kinded result
392 ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
393 ; typats <- zipWithM kcCheckLHsType hs_typats
394 [ EK kind (EkArg (ppr tc_name) n)
395 | (kind,n) <- kinds `zip` [1..]]
396 ; thing_inside tvs typats resultKind fam_tycon
401 %************************************************************************
405 %************************************************************************
407 We need to kind check all types in the mutually recursive group
408 before we know the kind of the type variables. For example:
411 op :: D b => a -> b -> b
414 bop :: (Monad c) => ...
416 Here, the kind of the locally-polymorphic type variable "b"
417 depends on *all the uses of class D*. For example, the use of
418 Monad c in bop's type signature means that D must have kind Type->Type.
420 However type synonyms work differently. They can have kinds which don't
421 just involve (->) and *:
422 type R = Int# -- Kind #
423 type S a = Array# a -- Kind * -> #
424 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
425 So we must infer their kinds from their right-hand sides *first* and then
426 use them, whereas for the mutually recursive data types D we bring into
427 scope kind bindings D -> k, where k is a kind variable, and do inference.
431 This treatment of type synonyms only applies to Haskell 98-style synonyms.
432 General type functions can be recursive, and hence, appear in `alg_decls'.
434 The kind of a type family is solely determinded by its kind signature;
435 hence, only kind signatures participate in the construction of the initial
436 kind environment (as constructed by `getInitialKind'). In fact, we ignore
437 instances of families altogether in the following. However, we need to
438 include the kinds of associated families into the construction of the
439 initial kind environment. (This is handled by `allDecls').
442 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
443 -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
444 kcTyClDecls syn_decls alg_decls
445 = do { -- First extend the kind env with each data type, class, and
446 -- indexed type, mapping them to a type variable
447 let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
448 ; alg_kinds <- mapM getInitialKind initialKindDecls
449 ; tcExtendKindEnv alg_kinds $ do
451 -- Now kind-check the type synonyms, in dependency order
452 -- We do these differently to data type and classes,
453 -- because a type synonym can be an unboxed type
455 -- and a kind variable can't unify with UnboxedTypeKind
456 -- So we infer their kinds in dependency order
457 { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
458 ; tcExtendKindEnv syn_kinds $ do
460 -- Now kind-check the data type, class, and kind signatures,
461 -- returning kind-annotated decls; we don't kind-check
462 -- instances of indexed types yet, but leave this to
464 { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
465 (filter (not . isFamInstDecl . unLoc) alg_decls)
467 ; return (kc_syn_decls, kc_alg_decls) }}}
469 -- get all declarations relevant for determining the initial kind
471 allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at
474 allDecls decl | isFamInstDecl decl = []
477 ------------------------------------------------------------------------
478 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
479 -- Only for data type, class, and indexed type declarations
480 -- Get as much info as possible from the data, class, or indexed type decl,
481 -- so as to maximise usefulness of error messages
483 = do { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
484 ; res_kind <- mk_res_kind decl
485 ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
487 mk_arg_kind (UserTyVar _) = newKindVar
488 mk_arg_kind (KindedTyVar _ kind) = return kind
490 mk_res_kind (TyFamily { tcdKind = Just kind }) = return kind
491 mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
492 -- On GADT-style declarations we allow a kind signature
493 -- data T :: *->* where { ... }
494 mk_res_kind _ = return liftedTypeKind
498 kcSynDecls :: [SCC (LTyClDecl Name)]
499 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
500 [(Name,TcKind)]) -- Kind bindings
503 kcSynDecls (group : groups)
504 = do { (decl, nk) <- kcSynDecl group
505 ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
506 ; return (decl:decls, nk:nks) }
509 kcSynDecl :: SCC (LTyClDecl Name)
510 -> TcM (LTyClDecl Name, -- Kind-annotated decls
511 (Name,TcKind)) -- Kind bindings
512 kcSynDecl (AcyclicSCC (L loc decl))
513 = tcAddDeclCtxt decl $
514 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
515 do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
516 <+> brackets (ppr k_tvs))
517 ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
518 ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
519 ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
520 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
521 (unLoc (tcdLName decl), tc_kind)) })
523 kcSynDecl (CyclicSCC decls)
524 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
525 -- of out-of-scope tycons
527 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
528 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
529 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
531 ------------------------------------------------------------------------
532 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
533 -- Not used for type synonyms (see kcSynDecl)
535 kcTyClDecl decl@(TyData {})
536 = ASSERT( not . isFamInstDecl $ decl ) -- must not be a family instance
537 kcTyClDeclBody decl $
540 kcTyClDecl decl@(TyFamily {})
541 = kcFamilyDecl [] decl -- the empty list signals a toplevel decl
543 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
544 = kcTyClDeclBody decl $ \ tvs' ->
545 do { ctxt' <- kcHsContext ctxt
546 ; ats' <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
547 ; sigs' <- mapM (wrapLocM kc_sig) sigs
548 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
551 kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
552 ; return (TypeSig nm op_ty') }
553 kc_sig other_sig = return other_sig
555 kcTyClDecl decl@(ForeignType {})
558 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
560 kcTyClDeclBody :: TyClDecl Name
561 -> ([LHsTyVarBndr Name] -> TcM a)
563 -- getInitialKind has made a suitably-shaped kind for the type or class
564 -- Unpack it, and attribute those kinds to the type variables
565 -- Extend the env with bindings for the tyvars, taken from
566 -- the kind of the tycon/class. Give it to the thing inside, and
567 -- check the result kind matches
568 kcTyClDeclBody decl thing_inside
569 = tcAddDeclCtxt decl $
570 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
571 ; let tc_kind = case tc_ty_thing of
573 _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
574 (kinds, _) = splitKindFunTys tc_kind
575 hs_tvs = tcdTyVars decl
576 kinded_tvs = ASSERT( length kinds >= length hs_tvs )
577 [ L loc (KindedTyVar (hsTyVarName tv) k)
578 | (L loc tv, k) <- zip hs_tvs kinds]
579 ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
581 -- Kind check a data declaration, assuming that we already extended the
582 -- kind environment with the type variables of the left-hand side (these
583 -- kinded type variables are also passed as the second parameter).
585 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
586 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
588 = do { ctxt' <- kcHsContext ctxt
589 ; cons' <- mapM (wrapLocM kc_con_decl) cons
590 ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
592 -- doc comments are typechecked to Nothing here
593 kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _)
594 = addErrCtxt (dataConCtxt name) $
595 kcHsTyVars ex_tvs $ \ex_tvs' -> do
596 do { ex_ctxt' <- kcHsContext ex_ctxt
597 ; details' <- kc_con_details details
598 ; res' <- case res of
599 ResTyH98 -> return ResTyH98
600 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
601 ; return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing) }
603 kc_con_details (PrefixCon btys)
604 = do { btys' <- mapM kc_larg_ty btys
605 ; return (PrefixCon btys') }
606 kc_con_details (InfixCon bty1 bty2)
607 = do { bty1' <- kc_larg_ty bty1
608 ; bty2' <- kc_larg_ty bty2
609 ; return (InfixCon bty1' bty2') }
610 kc_con_details (RecCon fields)
611 = do { fields' <- mapM kc_field fields
612 ; return (RecCon fields') }
614 kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
615 ; return (ConDeclField fld bty' d) }
617 kc_larg_ty bty = case new_or_data of
618 DataType -> kcHsSigType bty
619 NewType -> kcHsLiftedSigType bty
620 -- Can't allow an unlifted type for newtypes, because we're effectively
621 -- going to remove the constructor while coercing it to a lifted type.
622 -- And newtypes can't be bang'd
623 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
625 -- Kind check a family declaration or type family default declaration.
627 kcFamilyDecl :: [LHsTyVarBndr Name] -- tyvars of enclosing class decl if any
628 -> TyClDecl Name -> TcM (TyClDecl Name)
629 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
630 = kcTyClDeclBody decl $ \tvs' ->
631 do { mapM_ unifyClassParmKinds tvs'
632 ; return (decl {tcdTyVars = tvs',
633 tcdKind = kind `mplus` Just liftedTypeKind})
634 -- default result kind is '*'
637 unifyClassParmKinds (L _ (KindedTyVar n k))
638 | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
639 | otherwise = return ()
640 unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
641 classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
642 kcFamilyDecl _ (TySynonym {}) -- type family defaults
643 = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
644 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
648 %************************************************************************
650 \subsection{Type checking}
652 %************************************************************************
655 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
656 tcSynDecls [] = return []
657 tcSynDecls (decl : decls)
658 = do { syn_tc <- addLocM tcSynDecl decl
659 ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
660 ; return (syn_tc : syn_tcs) }
663 tcSynDecl :: TyClDecl Name -> TcM TyThing
665 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
666 = tcTyVarBndrs tvs $ \ tvs' -> do
667 { traceTc (text "tcd1" <+> ppr tc_name)
668 ; rhs_ty' <- tcHsKindedType rhs_ty
669 ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty')
670 (typeKind rhs_ty') Nothing
671 ; return (ATyCon tycon)
673 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
676 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
678 tcTyClDecl calc_isrec decl
679 = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
681 -- "type family" declarations
682 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
683 tcTyClDecl1 _calc_isrec
684 (TyFamily {tcdFlavour = TypeFamily,
685 tcdLName = L _ tc_name, tcdTyVars = tvs,
686 tcdKind = Just kind}) -- NB: kind at latest added during kind checking
687 = tcTyVarBndrs tvs $ \ tvs' -> do
688 { traceTc (text "type family: " <+> ppr tc_name)
690 -- Check that we don't use families without -XTypeFamilies
691 ; idx_tys <- doptM Opt_TypeFamilies
692 ; checkTc idx_tys $ badFamInstDecl tc_name
694 -- Check for no type indices
695 ; checkTc (not (null tvs)) (noIndexTypes tc_name)
697 ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
698 ; return [ATyCon tycon]
701 -- "data family" declaration
702 tcTyClDecl1 _calc_isrec
703 (TyFamily {tcdFlavour = DataFamily,
704 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
705 = tcTyVarBndrs tvs $ \ tvs' -> do
706 { traceTc (text "data family: " <+> ppr tc_name)
707 ; extra_tvs <- tcDataKindSig mb_kind
708 ; let final_tvs = tvs' ++ extra_tvs -- we may not need these
711 -- Check that we don't use families without -XTypeFamilies
712 ; idx_tys <- doptM Opt_TypeFamilies
713 ; checkTc idx_tys $ badFamInstDecl tc_name
715 -- Check for no type indices
716 ; checkTc (not (null tvs)) (noIndexTypes tc_name)
718 ; tycon <- buildAlgTyCon tc_name final_tvs []
719 mkOpenDataTyConRhs Recursive False True Nothing
720 ; return [ATyCon tycon]
723 -- "newtype" and "data"
724 -- NB: not used for newtype/data instances (whether associated or not)
725 tcTyClDecl1 calc_isrec
726 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
727 tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
728 = tcTyVarBndrs tvs $ \ tvs' -> do
729 { extra_tvs <- tcDataKindSig mb_ksig
730 ; let final_tvs = tvs' ++ extra_tvs
731 ; stupid_theta <- tcHsKindedContext ctxt
732 ; want_generic <- doptM Opt_Generics
733 ; unbox_strict <- doptM Opt_UnboxStrictFields
734 ; empty_data_decls <- doptM Opt_EmptyDataDecls
735 ; kind_signatures <- doptM Opt_KindSignatures
736 ; existential_ok <- doptM Opt_ExistentialQuantification
737 ; gadt_ok <- doptM Opt_GADTs
738 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
739 ; let ex_ok = existential_ok || gadt_ok -- Data cons can have existential context
741 -- Check that we don't use GADT syntax in H98 world
742 ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
744 -- Check that we don't use kind signatures without Glasgow extensions
745 ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
747 -- Check that the stupid theta is empty for a GADT-style declaration
748 ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
750 -- Check that a newtype has exactly one constructor
751 -- Do this before checking for empty data decls, so that
752 -- we don't suggest -XEmptyDataDecls for newtypes
753 ; checkTc (new_or_data == DataType || isSingleton cons)
754 (newtypeConError tc_name (length cons))
756 -- Check that there's at least one condecl,
757 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
758 ; checkTc (not (null cons) || empty_data_decls || is_boot)
759 (emptyConDeclsErr tc_name)
761 ; tycon <- fixM (\ tycon -> do
762 { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
763 ; data_cons <- tcConDecls unbox_strict ex_ok
764 tycon (final_tvs, res_ty) cons
766 if null cons && is_boot -- In a hs-boot file, empty cons means
767 then return AbstractTyCon -- "don't know"; hence Abstract
768 else case new_or_data of
769 DataType -> return (mkDataTyConRhs data_cons)
770 NewType -> ASSERT( not (null data_cons) )
771 mkNewTyConRhs tc_name tycon (head data_cons)
772 ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
773 (want_generic && canDoGenerics data_cons) h98_syntax Nothing
775 ; return [ATyCon tycon]
778 is_rec = calc_isrec tc_name
779 h98_syntax = consUseH98Syntax cons
781 tcTyClDecl1 calc_isrec
782 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
783 tcdCtxt = ctxt, tcdMeths = meths,
784 tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
785 = tcTyVarBndrs tvs $ \ tvs' -> do
786 { ctxt' <- tcHsKindedContext ctxt
787 ; fds' <- mapM (addLocM tc_fundep) fundeps
788 ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
789 -- NB: 'ats' only contains "type family" and "data family"
790 -- declarations as well as type family defaults
791 ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
792 ; sig_stuff <- tcClassSigs class_name sigs meths
793 ; clas <- fixM (\ clas ->
794 let -- This little knot is just so we can get
795 -- hold of the name of the class TyCon, which we
796 -- need to look up its recursiveness
797 tycon_name = tyConName (classTyCon clas)
798 tc_isrec = calc_isrec tycon_name
800 buildClass False {- Must include unfoldings for selectors -}
801 class_name tvs' ctxt' fds' ats'
803 ; return (AClass clas : ats')
804 -- NB: Order is important due to the call to `mkGlobalThings' when
805 -- tying the the type and class declaration type checking knot.
808 tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
809 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
810 ; return (tvs1', tvs2') }
813 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
814 = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
816 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
818 -----------------------------------
819 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
820 -> [LConDecl Name] -> TcM [DataCon]
821 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
822 = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
824 tcConDecl :: Bool -- True <=> -funbox-strict_fields
825 -> Bool -- True <=> -XExistentialQuantificaton or -XGADTs
826 -> TyCon -- Representation tycon
827 -> ([TyVar], Type) -- Return type template (with its template tyvars)
831 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl -- Data types
832 (ConDecl name _ tvs ctxt details res_ty _)
833 = addErrCtxt (dataConCtxt name) $
834 tcTyVarBndrs tvs $ \ tvs' -> do
835 { ctxt' <- tcHsKindedContext ctxt
836 ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
837 (badExistential name)
838 ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
840 tc_datacon is_infix field_lbls btys
841 = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
842 ; buildDataCon (unLoc name) is_infix
844 univ_tvs ex_tvs eq_preds ctxt' arg_tys
846 -- NB: we put data_tc, the type constructor gotten from the
847 -- constructor type signature into the data constructor;
848 -- that way checkValidDataCon can complain if it's wrong.
851 PrefixCon btys -> tc_datacon False [] btys
852 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
853 RecCon fields -> tc_datacon False field_names btys
855 field_names = map (unLoc . cd_fld_name) fields
856 btys = map cd_fld_type fields
860 -- data instance T (b,c) where
861 -- TI :: forall e. e -> T (e,e)
863 -- The representation tycon looks like this:
864 -- data :R7T b c where
865 -- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
866 -- In this case orig_res_ty = T (e,e)
868 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
869 -- data instance T [a] b c = ...
870 -- gives template ([a,b,c], T [a] b c)
871 -> [TyVar] -- where MkT :: forall x y z. ...
873 -> TcM ([TyVar], -- Universal
874 [TyVar], -- Existential (distinct OccNames from univs)
875 [(TyVar,Type)], -- Equality predicates
876 Type) -- Typechecked return type
877 -- We don't check that the TyCon given in the ResTy is
878 -- the same as the parent tycon, becuase we are in the middle
879 -- of a recursive knot; so it's postponed until checkValidDataCon
881 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
882 = return (tmpl_tvs, dc_tvs, [], res_ty)
883 -- In H98 syntax the dc_tvs are the existential ones
884 -- data T a b c = forall d e. MkT ...
885 -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
887 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
888 -- E.g. data T [a] b c where
889 -- MkT :: forall x y z. T [(x,y)] z z
891 -- Univ tyvars Eq-spec
895 -- Existentials are the leftover type vars: [x,y]
896 -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
897 = do { res_ty' <- tcHsKindedType res_ty
898 ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
900 -- /Lazily/ figure out the univ_tvs etc
901 -- Each univ_tv is either a dc_tv or a tmpl_tv
902 (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
903 choose tmpl (univs, eqs)
904 | Just ty <- lookupTyVar subst tmpl
905 = case tcGetTyVar_maybe ty of
906 Just tv | not (tv `elem` univs)
908 _other -> (tmpl:univs, (tmpl,ty):eqs)
909 | otherwise = pprPanic "tcResultType" (ppr res_ty)
910 ex_tvs = dc_tvs `minusList` univ_tvs
912 ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
914 -- NB: tmpl_tvs and dc_tvs are distinct, but
915 -- we want them to be *visibly* distinct, both for
916 -- interface files and general confusion. So rename
917 -- the tc_tvs, since they are not used yet (no
918 -- consequential renaming needed)
919 (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
920 init_occ_env = initTidyOccEnv (map getOccName dc_tvs)
921 tidy_one env tv = (env', setTyVarName tv (tidyNameOcc name occ'))
924 (env', occ') = tidyOccName env (getOccName name)
926 consUseH98Syntax :: [LConDecl a] -> Bool
927 consUseH98Syntax (L _ (ConDecl { con_res = ResTyGADT _ }) : _) = False
928 consUseH98Syntax _ = True
929 -- All constructors have same shape
932 tcConArg :: Bool -- True <=> -funbox-strict_fields
934 -> TcM (TcType, StrictnessMark)
935 tcConArg unbox_strict bty
936 = do { arg_ty <- tcHsBangType bty
937 ; let bang = getBangStrictness bty
938 ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
940 -- We attempt to unbox/unpack a strict field when either:
941 -- (i) The field is marked '!!', or
942 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
944 -- We have turned off unboxing of newtypes because coercions make unboxing
945 -- and reboxing more complicated
946 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
947 chooseBoxingStrategy unbox_strict_fields arg_ty bang
949 HsNoBang -> NotMarkedStrict
950 HsStrict | unbox_strict_fields
951 && can_unbox arg_ty -> MarkedUnboxed
952 HsUnbox | can_unbox arg_ty -> MarkedUnboxed
955 -- we can unbox if the type is a chain of newtypes with a product tycon
957 can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
959 Just (arg_tycon, tycon_args) ->
960 not (isRecursiveTyCon arg_tycon) && -- Note [Recusive unboxing]
961 isProductTyCon arg_tycon &&
962 (if isNewTyCon arg_tycon then
963 can_unbox (newTyConInstRhs arg_tycon tycon_args)
967 Note [Recursive unboxing]
968 ~~~~~~~~~~~~~~~~~~~~~~~~~
969 Be careful not to try to unbox this!
971 But it's the *argument* type that matters. This is fine:
973 because Int is non-recursive.
976 %************************************************************************
980 %************************************************************************
982 Validity checking is done once the mutually-recursive knot has been
983 tied, so we can look at things freely.
986 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
987 checkCycleErrs tyclss
991 = do { mapM_ recClsErr cls_cycles
992 ; failM } -- Give up now, because later checkValidTyCl
993 -- will loop if the synonym is recursive
995 cls_cycles = calcClassCycles tyclss
997 checkValidTyCl :: TyClDecl Name -> TcM ()
998 -- We do the validity check over declarations, rather than TyThings
999 -- only so that we can add a nice context with tcAddDeclCtxt
1001 = tcAddDeclCtxt decl $
1002 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
1003 ; traceTc (text "Validity of" <+> ppr thing)
1005 ATyCon tc -> checkValidTyCon tc
1006 AClass cl -> checkValidClass cl
1007 _ -> panic "checkValidTyCl"
1008 ; traceTc (text "Done validity of" <+> ppr thing)
1011 -------------------------
1012 -- For data types declared with record syntax, we require
1013 -- that each constructor that has a field 'f'
1014 -- (a) has the same result type
1015 -- (b) has the same type for 'f'
1016 -- module alpha conversion of the quantified type variables
1017 -- of the constructor.
1019 -- Note that we allow existentials to match becuase the
1020 -- fields can never meet. E.g
1022 -- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1023 -- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
1024 -- Here we do not complain about f1,f2 because they are existential
1026 checkValidTyCon :: TyCon -> TcM ()
1029 = case synTyConRhs tc of
1030 OpenSynTyCon _ _ -> return ()
1031 SynonymTyCon ty -> checkValidType syn_ctxt ty
1033 = do -- Check the context on the data decl
1034 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1036 -- Check arg types of data constructors
1037 mapM_ (checkValidDataCon tc) data_cons
1039 -- Check that fields with the same name share a type
1040 mapM_ check_fields groups
1043 syn_ctxt = TySynCtxt name
1045 data_cons = tyConDataCons tc
1047 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1048 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1049 get_fields con = dataConFieldLabels con `zip` repeat con
1050 -- dataConFieldLabels may return the empty list, which is fine
1052 -- See Note [GADT record selectors] in MkId.lhs
1053 -- We must check (a) that the named field has the same
1054 -- type in each constructor
1055 -- (b) that those constructors have the same result type
1057 -- However, the constructors may have differently named type variable
1058 -- and (worse) we don't know how the correspond to each other. E.g.
1059 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
1060 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
1062 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1063 -- result type against other candidates' types BOTH WAYS ROUND.
1064 -- If they magically agrees, take the substitution and
1065 -- apply them to the latter ones, and see if they match perfectly.
1066 check_fields ((label, con1) : other_fields)
1067 -- These fields all have the same name, but are from
1068 -- different constructors in the data type
1069 = recoverM (return ()) $ mapM_ checkOne other_fields
1070 -- Check that all the fields in the group have the same type
1071 -- NB: this check assumes that all the constructors of a given
1072 -- data type use the same type variables
1074 (tvs1, _, _, res1) = dataConSig con1
1076 fty1 = dataConFieldType con1 label
1078 checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
1079 = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1080 ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1082 (tvs2, _, _, res2) = dataConSig con2
1084 fty2 = dataConFieldType con2 label
1085 check_fields [] = panic "checkValidTyCon/check_fields []"
1087 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1088 -> Type -> Type -> Type -> Type -> TcM ()
1089 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1090 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1091 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1093 mb_subst1 = tcMatchTy tvs1 res1 res2
1094 mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1096 -------------------------------
1097 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1098 checkValidDataCon tc con
1099 = setSrcSpan (srcLocSpan (getSrcLoc con)) $
1100 addErrCtxt (dataConCtxt con) $
1101 do { traceTc (ptext (sLit "Validity of data con") <+> ppr con)
1102 ; let tc_tvs = tyConTyVars tc
1103 res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1104 actual_res_ty = dataConOrigResTy con
1105 ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1108 (badDataConTyCon con res_ty_tmpl actual_res_ty)
1109 ; checkValidMonoType (dataConOrigResTy con)
1110 -- Disallow MkT :: T (forall a. a->a)
1111 -- Reason: it's really the argument of an equality constraint
1112 ; checkValidType ctxt (dataConUserType con)
1113 ; when (isNewTyCon tc) (checkNewDataCon con)
1116 ctxt = ConArgCtxt (dataConName con)
1118 -------------------------------
1119 checkNewDataCon :: DataCon -> TcM ()
1120 -- Checks for the data constructor of a newtype
1122 = do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1124 ; checkTc (null eq_spec) (newtypePredError con)
1125 -- Return type is (T a b c)
1126 ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1128 ; checkTc (not (any isMarkedStrict (dataConStrictMarks con)))
1129 (newtypeStrictError con)
1133 (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1135 -------------------------------
1136 checkValidClass :: Class -> TcM ()
1138 = do { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1139 ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1140 ; fundep_classes <- doptM Opt_FunctionalDependencies
1142 -- Check that the class is unary, unless GlaExs
1143 ; checkTc (notNull tyvars) (nullaryClassErr cls)
1144 ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1145 ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1147 -- Check the super-classes
1148 ; checkValidTheta (ClassSCCtxt (className cls)) theta
1150 -- Check the class operations
1151 ; mapM_ (check_op constrained_class_methods) op_stuff
1153 -- Check that if the class has generic methods, then the
1154 -- class has only one parameter. We can't do generic
1155 -- multi-parameter type classes!
1156 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1159 (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1160 unary = isSingleton tyvars
1161 no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1163 check_op constrained_class_methods (sel_id, dm)
1164 = addErrCtxt (classOpCtxt sel_id tau) $ do
1165 { checkValidTheta SigmaCtxt (tail theta)
1166 -- The 'tail' removes the initial (C a) from the
1167 -- class itself, leaving just the method type
1169 ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1170 ; checkValidType (FunSigCtxt op_name) tau
1172 -- Check that the type mentions at least one of
1173 -- the class type variables...or at least one reachable
1174 -- from one of the class variables. Example: tc223
1175 -- class Error e => Game b mv e | b -> mv e where
1176 -- newBoard :: MonadState b m => m ()
1177 -- Here, MonadState has a fundep m->b, so newBoard is fine
1178 ; let grown_tyvars = growThetaTyVars theta (mkVarSet tyvars)
1179 ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1180 (noClassTyVarErr cls sel_id)
1182 -- Check that for a generic method, the type of
1183 -- the method is sufficiently simple
1184 ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1185 (badGenericMethodType op_name op_ty)
1188 op_name = idName sel_id
1189 op_ty = idType sel_id
1190 (_,theta1,tau1) = tcSplitSigmaTy op_ty
1191 (_,theta2,tau2) = tcSplitSigmaTy tau1
1192 (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1193 | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1194 -- Ugh! The function might have a type like
1195 -- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1196 -- With -XConstrainedClassMethods, we want to allow this, even though the inner
1197 -- forall has an (Eq a) constraint. Whereas in general, each constraint
1198 -- in the context of a for-all must mention at least one quantified
1199 -- type variable. What a mess!
1203 %************************************************************************
1205 Building record selectors
1207 %************************************************************************
1210 mkAuxBinds :: [TyThing] -> HsValBinds Name
1211 -- NB We produce *un-typechecked* bindings, rather like 'deriving'
1212 -- This makes life easier, because the later type checking will add
1213 -- all necessary type abstractions and applications
1214 mkAuxBinds ty_things
1215 = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1217 (sigs, binds) = unzip rec_sels
1218 rec_sels = map mkRecSelBind [ (tc,fld)
1219 | ATyCon tc <- ty_things
1220 , fld <- tyConFields tc ]
1222 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1223 mkRecSelBind (tycon, sel_name)
1224 = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1226 loc = getSrcSpan tycon
1227 sel_id = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1228 rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1230 -- Find a representative constructor, con1
1231 all_cons = tyConDataCons tycon
1232 cons_w_field = [ con | con <- all_cons
1233 , sel_name `elem` dataConFieldLabels con ]
1234 con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1236 -- Selector type; Note [Polymorphic selectors]
1237 field_ty = dataConFieldType con1 sel_name
1238 data_ty = dataConOrigResTy con1
1239 data_tvs = tyVarsOfType data_ty
1240 is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)
1241 (field_tvs, field_theta, field_tau) = tcSplitSigmaTy field_ty
1242 sel_ty | is_naughty = unitTy
1243 | otherwise = mkForAllTys (varSetElems data_tvs ++ field_tvs) $
1244 mkPhiTy (dataConStupidTheta con1) $ -- Urgh!
1245 mkPhiTy field_theta $ -- Urgh!
1246 mkFunTy data_ty field_tau
1248 -- Make the binding: sel (C2 { fld = x }) = x
1249 -- sel (C7 { fld = x }) = x
1250 -- where cons_w_field = [C2,C7]
1251 sel_bind | is_naughty = mkFunBind sel_lname [mkSimpleMatch [] unit_rhs]
1252 | otherwise = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1253 mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)]
1254 (L loc (HsVar field_var))
1255 mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1256 rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1257 rec_field = HsRecField { hsRecFieldId = sel_lname
1258 , hsRecFieldArg = nlVarPat field_var
1259 , hsRecPun = False }
1260 sel_lname = L loc sel_name
1261 field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1263 -- Add catch-all default case unless the case is exhaustive
1264 -- We do this explicitly so that we get a nice error message that
1265 -- mentions this particular record selector
1266 deflt | length cons_w_field == length all_cons = []
1267 | otherwise = [mkSimpleMatch [nlWildPat]
1268 (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1271 unit_rhs = L loc $ ExplicitTuple [] Boxed
1272 msg_lit = HsStringPrim $ mkFastString $
1273 occNameString (getOccName sel_name)
1276 tyConFields :: TyCon -> [FieldLabel]
1278 | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1282 Note [Polymorphic selectors]
1283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1284 When a record has a polymorphic field, we pull the foralls out to the front.
1285 data T = MkT { f :: forall a. [a] -> a }
1286 Then f :: forall a. T -> [a] -> a
1287 NOT f :: T -> forall a. [a] -> a
1289 This is horrid. It's only needed in deeply obscure cases, which I hate.
1290 The only case I know is test tc163, which is worth looking at. It's far
1291 from clear that this test should succeed at all!
1293 Note [Naughty record selectors]
1294 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1295 A "naughty" field is one for which we can't define a record
1296 selector, because an existential type variable would escape. For example:
1297 data T = forall a. MkT { x,y::a }
1298 We obviously can't define
1300 Nevertheless we *do* put a RecSelId into the type environment
1301 so that if the user tries to use 'x' as a selector we can bleat
1302 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1303 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1305 In general, a field is naughty if its type mentions a type variable that
1306 isn't in the result type of the constructor.
1308 We make a dummy binding
1310 for naughty selectors, so that the later type-check will add them to the
1311 environment, and they'll be exported. The function is never called, because
1312 the tyepchecker spots the sel_naughty field.
1314 Note [GADT record selectors]
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316 For GADTs, we require that all constructors with a common field 'f' have the same
1317 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
1320 T1 { f :: Maybe a } :: T [a]
1321 T2 { f :: Maybe a, y :: b } :: T [a]
1323 and now the selector takes that result type as its argument:
1324 f :: forall a. T [a] -> Maybe a
1326 Details: the "real" types of T1,T2 are:
1327 T1 :: forall r a. (r~[a]) => a -> T r
1328 T2 :: forall r a b. (r~[a]) => a -> b -> T r
1330 So the selector loooks like this:
1331 f :: forall a. T [a] -> Maybe a
1334 T1 c (g:[a]~[c]) (v:Maybe c) -> v `cast` Maybe (right (sym g))
1335 T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1337 Note the forall'd tyvars of the selector are just the free tyvars
1338 of the result type; there may be other tyvars in the constructor's
1339 type (e.g. 'b' in T2).
1341 Note the need for casts in the result!
1343 Note [Selector running example]
1344 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1345 It's OK to combine GADTs and type families. Here's a running example:
1347 data instance T [a] where
1348 T1 { fld :: b } :: T [Maybe b]
1350 The representation type looks like this
1352 T1 { fld :: b } :: :R7T (Maybe b)
1354 and there's coercion from the family type to the representation type
1355 :CoR7T a :: T [a] ~ :R7T a
1357 The selector we want for fld looks like this:
1359 fld :: forall b. T [Maybe b] -> b
1360 fld = /\b. \(d::T [Maybe b]).
1361 case d `cast` :CoR7T (Maybe b) of
1364 The scrutinee of the case has type :R7T (Maybe b), which can be
1365 gotten by appying the eq_spec to the univ_tvs of the data con.
1367 %************************************************************************
1371 %************************************************************************
1374 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1375 resultTypeMisMatch field_name con1 con2
1376 = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1377 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1378 nest 2 $ ptext (sLit "but have different result types")]
1380 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1381 fieldTypeMisMatch field_name con1 con2
1382 = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1383 ptext (sLit "give different types for field"), quotes (ppr field_name)]
1385 dataConCtxt :: Outputable a => a -> SDoc
1386 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1388 classOpCtxt :: Var -> Type -> SDoc
1389 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1390 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1392 nullaryClassErr :: Class -> SDoc
1394 = ptext (sLit "No parameters for class") <+> quotes (ppr cls)
1396 classArityErr :: Class -> SDoc
1398 = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1399 parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1401 classFunDepsErr :: Class -> SDoc
1403 = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1404 parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1406 noClassTyVarErr :: Class -> Var -> SDoc
1407 noClassTyVarErr clas op
1408 = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1409 ptext (sLit "mentions none of the type variables of the class") <+>
1410 ppr clas <+> hsep (map ppr (classTyVars clas))]
1412 genericMultiParamErr :: Class -> SDoc
1413 genericMultiParamErr clas
1414 = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+>
1415 ptext (sLit "cannot have generic methods")
1417 badGenericMethodType :: Name -> Kind -> SDoc
1418 badGenericMethodType op op_ty
1419 = hang (ptext (sLit "Generic method type is too complex"))
1420 4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1421 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1423 recSynErr :: [LTyClDecl Name] -> TcRn ()
1425 = setSrcSpan (getLoc (head sorted_decls)) $
1426 addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1427 nest 2 (vcat (map ppr_decl sorted_decls))])
1429 sorted_decls = sortLocated syn_decls
1430 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1432 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1434 = setSrcSpan (getLoc (head sorted_decls)) $
1435 addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1436 nest 2 (vcat (map ppr_decl sorted_decls))])
1438 sorted_decls = sortLocated cls_decls
1439 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1441 sortLocated :: [Located a] -> [Located a]
1442 sortLocated things = sortLe le things
1444 le (L l1 _) (L l2 _) = l1 <= l2
1446 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1447 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1448 = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1449 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1450 2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1452 badGadtDecl :: Name -> SDoc
1454 = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1455 , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1457 badExistential :: Located Name -> SDoc
1458 badExistential con_name
1459 = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1460 ptext (sLit "has existential type variables, or a context"))
1461 2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1463 badStupidTheta :: Name -> SDoc
1464 badStupidTheta tc_name
1465 = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1467 newtypeConError :: Name -> Int -> SDoc
1468 newtypeConError tycon n
1469 = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1470 nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1472 newtypeExError :: DataCon -> SDoc
1474 = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1475 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1477 newtypeStrictError :: DataCon -> SDoc
1478 newtypeStrictError con
1479 = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1480 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1482 newtypePredError :: DataCon -> SDoc
1483 newtypePredError con
1484 = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1485 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1487 newtypeFieldErr :: DataCon -> Int -> SDoc
1488 newtypeFieldErr con_name n_flds
1489 = sep [ptext (sLit "The constructor of a newtype must have exactly one field"),
1490 nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1492 badSigTyDecl :: Name -> SDoc
1493 badSigTyDecl tc_name
1494 = vcat [ ptext (sLit "Illegal kind signature") <+>
1495 quotes (ppr tc_name)
1496 , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1498 noIndexTypes :: Name -> SDoc
1499 noIndexTypes tc_name
1500 = ptext (sLit "Type family constructor") <+> quotes (ppr tc_name)
1501 <+> ptext (sLit "must have at least one type index parameter")
1503 badFamInstDecl :: Outputable a => a -> SDoc
1504 badFamInstDecl tc_name
1505 = vcat [ ptext (sLit "Illegal family instance for") <+>
1506 quotes (ppr tc_name)
1507 , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1509 tooManyParmsErr :: Located Name -> SDoc
1510 tooManyParmsErr tc_name
1511 = ptext (sLit "Family instance has too many parameters:") <+>
1512 quotes (ppr tc_name)
1514 tooFewParmsErr :: Arity -> SDoc
1515 tooFewParmsErr arity
1516 = ptext (sLit "Family instance has too few parameters; expected") <+>
1519 wrongNumberOfParmsErr :: Arity -> SDoc
1520 wrongNumberOfParmsErr exp_arity
1521 = ptext (sLit "Number of parameters must match family declaration; expected")
1524 badBootFamInstDeclErr :: SDoc
1525 badBootFamInstDeclErr
1526 = ptext (sLit "Illegal family instance in hs-boot file")
1528 notFamily :: TyCon -> SDoc
1530 = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1531 , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1533 wrongKindOfFamily :: TyCon -> SDoc
1534 wrongKindOfFamily family
1535 = ptext (sLit "Wrong category of family instance; declaration was for a")
1538 kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1539 | isAlgTyCon family = ptext (sLit "data type")
1540 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1542 emptyConDeclsErr :: Name -> SDoc
1543 emptyConDeclsErr tycon
1544 = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1545 nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]