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 unless (isSynTyCon family) $
275 addErr (wrongKindOfFamily family)
277 ; -- (1) kind check the right-hand side of the type equation
278 ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) resKind
280 -- we need the exact same number of type parameters as the family
282 ; let famArity = tyConArity family
283 ; checkTc (length k_typats == famArity) $
284 wrongNumberOfParmsErr famArity
286 -- (2) type check type equation
287 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
288 ; t_typats <- mapM tcHsKindedType k_typats
289 ; t_rhs <- tcHsKindedType k_rhs
291 -- (3) check the well-formedness of the instance
292 ; checkValidTypeInst t_typats t_rhs
294 -- (4) construct representation tycon
295 ; rep_tc_name <- newFamInstTyConName tc_name loc
296 ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs)
297 (typeKind t_rhs) (Just (family, t_typats))
300 -- "newtype instance" and "data instance"
301 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
303 = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
304 do { -- check that the family declaration is for the right kind
305 unless (isAlgTyCon fam_tycon) $
306 addErr (wrongKindOfFamily fam_tycon)
308 ; -- (1) kind check the data declaration as usual
309 ; k_decl <- kcDataDecl decl k_tvs
310 ; let k_ctxt = tcdCtxt k_decl
311 k_cons = tcdCons k_decl
313 -- result kind must be '*' (otherwise, we have too few patterns)
314 ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
316 -- (2) type check indexed data type declaration
317 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
318 ; unbox_strict <- doptM Opt_UnboxStrictFields
320 -- kind check the type indexes and the context
321 ; t_typats <- mapM tcHsKindedType k_typats
322 ; stupid_theta <- tcHsKindedContext k_ctxt
325 -- (a) left-hand side contains no type family applications
326 -- (vanilla synonyms are fine, though, and we checked for
328 ; mapM_ checkTyFamFreeness t_typats
330 -- Check that we don't use GADT syntax in H98 world
331 ; gadt_ok <- doptM Opt_GADTs
332 ; checkTc (gadt_ok || consUseH98Syntax cons) (badGadtDecl tc_name)
334 -- (b) a newtype has exactly one constructor
335 ; checkTc (new_or_data == DataType || isSingleton k_cons) $
336 newtypeConError tc_name (length k_cons)
338 -- (4) construct representation tycon
339 ; rep_tc_name <- newFamInstTyConName tc_name loc
340 ; let ex_ok = True -- Existentials ok for type families!
341 ; fixM (\ rep_tycon -> do
342 { let orig_res_ty = mkTyConApp fam_tycon t_typats
343 ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
344 (t_tvs, orig_res_ty) k_cons
347 DataType -> return (mkDataTyConRhs data_cons)
348 NewType -> ASSERT( not (null data_cons) )
349 mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
350 ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
351 False h98_syntax (Just (fam_tycon, t_typats))
352 -- We always assume that indexed types are recursive. Why?
353 -- (1) Due to their open nature, we can never be sure that a
354 -- further instance might not introduce a new recursive
355 -- dependency. (2) They are always valid loop breakers as
356 -- they involve a coercion.
360 h98_syntax = case cons of -- All constructors have same shape
361 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
364 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
366 -- Kind checking of indexed types
369 -- Kind check type patterns and kind annotate the embedded type variables.
371 -- * Here we check that a type instance matches its kind signature, but we do
372 -- not check whether there is a pattern for each type index; the latter
373 -- check is only required for type synonym instances.
375 kcIdxTyPats :: TyClDecl Name
376 -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
377 -- ^^kinded tvs ^^kinded ty pats ^^res kind
379 kcIdxTyPats decl thing_inside
380 = kcHsTyVars (tcdTyVars decl) $ \tvs ->
381 do { fam_tycon <- tcLookupLocatedTyCon (tcdLName decl)
382 ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
383 ; hs_typats = fromJust $ tcdTyPats decl }
385 -- we may not have more parameters than the kind indicates
386 ; checkTc (length kinds >= length hs_typats) $
387 tooManyParmsErr (tcdLName decl)
389 -- type functions can have a higher-kinded result
390 ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
391 ; typats <- zipWithM kcCheckLHsType hs_typats kinds
392 ; thing_inside tvs typats resultKind fam_tycon
398 %************************************************************************
402 %************************************************************************
404 We need to kind check all types in the mutually recursive group
405 before we know the kind of the type variables. For example:
408 op :: D b => a -> b -> b
411 bop :: (Monad c) => ...
413 Here, the kind of the locally-polymorphic type variable "b"
414 depends on *all the uses of class D*. For example, the use of
415 Monad c in bop's type signature means that D must have kind Type->Type.
417 However type synonyms work differently. They can have kinds which don't
418 just involve (->) and *:
419 type R = Int# -- Kind #
420 type S a = Array# a -- Kind * -> #
421 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
422 So we must infer their kinds from their right-hand sides *first* and then
423 use them, whereas for the mutually recursive data types D we bring into
424 scope kind bindings D -> k, where k is a kind variable, and do inference.
428 This treatment of type synonyms only applies to Haskell 98-style synonyms.
429 General type functions can be recursive, and hence, appear in `alg_decls'.
431 The kind of a type family is solely determinded by its kind signature;
432 hence, only kind signatures participate in the construction of the initial
433 kind environment (as constructed by `getInitialKind'). In fact, we ignore
434 instances of families altogether in the following. However, we need to
435 include the kinds of associated families into the construction of the
436 initial kind environment. (This is handled by `allDecls').
439 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
440 -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
441 kcTyClDecls syn_decls alg_decls
442 = do { -- First extend the kind env with each data type, class, and
443 -- indexed type, mapping them to a type variable
444 let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
445 ; alg_kinds <- mapM getInitialKind initialKindDecls
446 ; tcExtendKindEnv alg_kinds $ do
448 -- Now kind-check the type synonyms, in dependency order
449 -- We do these differently to data type and classes,
450 -- because a type synonym can be an unboxed type
452 -- and a kind variable can't unify with UnboxedTypeKind
453 -- So we infer their kinds in dependency order
454 { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
455 ; tcExtendKindEnv syn_kinds $ do
457 -- Now kind-check the data type, class, and kind signatures,
458 -- returning kind-annotated decls; we don't kind-check
459 -- instances of indexed types yet, but leave this to
461 { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
462 (filter (not . isFamInstDecl . unLoc) alg_decls)
464 ; return (kc_syn_decls, kc_alg_decls) }}}
466 -- get all declarations relevant for determining the initial kind
468 allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at
471 allDecls decl | isFamInstDecl decl = []
474 ------------------------------------------------------------------------
475 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
476 -- Only for data type, class, and indexed type declarations
477 -- Get as much info as possible from the data, class, or indexed type decl,
478 -- so as to maximise usefulness of error messages
480 = do { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
481 ; res_kind <- mk_res_kind decl
482 ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
484 mk_arg_kind (UserTyVar _) = newKindVar
485 mk_arg_kind (KindedTyVar _ kind) = return kind
487 mk_res_kind (TyFamily { tcdKind = Just kind }) = return kind
488 mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
489 -- On GADT-style declarations we allow a kind signature
490 -- data T :: *->* where { ... }
491 mk_res_kind _ = return liftedTypeKind
495 kcSynDecls :: [SCC (LTyClDecl Name)]
496 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
497 [(Name,TcKind)]) -- Kind bindings
500 kcSynDecls (group : groups)
501 = do { (decl, nk) <- kcSynDecl group
502 ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
503 ; return (decl:decls, nk:nks) }
506 kcSynDecl :: SCC (LTyClDecl Name)
507 -> TcM (LTyClDecl Name, -- Kind-annotated decls
508 (Name,TcKind)) -- Kind bindings
509 kcSynDecl (AcyclicSCC (L loc decl))
510 = tcAddDeclCtxt decl $
511 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
512 do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
513 <+> brackets (ppr k_tvs))
514 ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
515 ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
516 ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
517 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
518 (unLoc (tcdLName decl), tc_kind)) })
520 kcSynDecl (CyclicSCC decls)
521 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
522 -- of out-of-scope tycons
524 kindedTyVarKind :: LHsTyVarBndr Name -> Kind
525 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
526 kindedTyVarKind x = pprPanic "kindedTyVarKind" (ppr x)
528 ------------------------------------------------------------------------
529 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
530 -- Not used for type synonyms (see kcSynDecl)
532 kcTyClDecl decl@(TyData {})
533 = ASSERT( not . isFamInstDecl $ decl ) -- must not be a family instance
534 kcTyClDeclBody decl $
537 kcTyClDecl decl@(TyFamily {})
538 = kcFamilyDecl [] decl -- the empty list signals a toplevel decl
540 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
541 = kcTyClDeclBody decl $ \ tvs' ->
542 do { ctxt' <- kcHsContext ctxt
543 ; ats' <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
544 ; sigs' <- mapM (wrapLocM kc_sig) sigs
545 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
548 kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
549 ; return (TypeSig nm op_ty') }
550 kc_sig other_sig = return other_sig
552 kcTyClDecl decl@(ForeignType {})
555 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
557 kcTyClDeclBody :: TyClDecl Name
558 -> ([LHsTyVarBndr Name] -> TcM a)
560 -- getInitialKind has made a suitably-shaped kind for the type or class
561 -- Unpack it, and attribute those kinds to the type variables
562 -- Extend the env with bindings for the tyvars, taken from
563 -- the kind of the tycon/class. Give it to the thing inside, and
564 -- check the result kind matches
565 kcTyClDeclBody decl thing_inside
566 = tcAddDeclCtxt decl $
567 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
568 ; let tc_kind = case tc_ty_thing of
570 _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
571 (kinds, _) = splitKindFunTys tc_kind
572 hs_tvs = tcdTyVars decl
573 kinded_tvs = ASSERT( length kinds >= length hs_tvs )
574 [ L loc (KindedTyVar (hsTyVarName tv) k)
575 | (L loc tv, k) <- zip hs_tvs kinds]
576 ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
578 -- Kind check a data declaration, assuming that we already extended the
579 -- kind environment with the type variables of the left-hand side (these
580 -- kinded type variables are also passed as the second parameter).
582 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
583 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
585 = do { ctxt' <- kcHsContext ctxt
586 ; cons' <- mapM (wrapLocM kc_con_decl) cons
587 ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
589 -- doc comments are typechecked to Nothing here
590 kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res _)
591 = addErrCtxt (dataConCtxt name) $
592 kcHsTyVars ex_tvs $ \ex_tvs' -> do
593 do { ex_ctxt' <- kcHsContext ex_ctxt
594 ; details' <- kc_con_details details
595 ; res' <- case res of
596 ResTyH98 -> return ResTyH98
597 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
598 ; return (ConDecl name expl ex_tvs' ex_ctxt' details' res' Nothing) }
600 kc_con_details (PrefixCon btys)
601 = do { btys' <- mapM kc_larg_ty btys
602 ; return (PrefixCon btys') }
603 kc_con_details (InfixCon bty1 bty2)
604 = do { bty1' <- kc_larg_ty bty1
605 ; bty2' <- kc_larg_ty bty2
606 ; return (InfixCon bty1' bty2') }
607 kc_con_details (RecCon fields)
608 = do { fields' <- mapM kc_field fields
609 ; return (RecCon fields') }
611 kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
612 ; return (ConDeclField fld bty' d) }
614 kc_larg_ty bty = case new_or_data of
615 DataType -> kcHsSigType bty
616 NewType -> kcHsLiftedSigType bty
617 -- Can't allow an unlifted type for newtypes, because we're effectively
618 -- going to remove the constructor while coercing it to a lifted type.
619 -- And newtypes can't be bang'd
620 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
622 -- Kind check a family declaration or type family default declaration.
624 kcFamilyDecl :: [LHsTyVarBndr Name] -- tyvars of enclosing class decl if any
625 -> TyClDecl Name -> TcM (TyClDecl Name)
626 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
627 = kcTyClDeclBody decl $ \tvs' ->
628 do { mapM_ unifyClassParmKinds tvs'
629 ; return (decl {tcdTyVars = tvs',
630 tcdKind = kind `mplus` Just liftedTypeKind})
631 -- default result kind is '*'
634 unifyClassParmKinds (L _ (KindedTyVar n k))
635 | Just classParmKind <- lookup n classTyKinds = unifyKind k classParmKind
636 | otherwise = return ()
637 unifyClassParmKinds x = pprPanic "kcFamilyDecl/unifyClassParmKinds" (ppr x)
638 classTyKinds = [(n, k) | L _ (KindedTyVar n k) <- classTvs]
639 kcFamilyDecl _ (TySynonym {}) -- type family defaults
640 = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
641 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
645 %************************************************************************
647 \subsection{Type checking}
649 %************************************************************************
652 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
653 tcSynDecls [] = return []
654 tcSynDecls (decl : decls)
655 = do { syn_tc <- addLocM tcSynDecl decl
656 ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
657 ; return (syn_tc : syn_tcs) }
660 tcSynDecl :: TyClDecl Name -> TcM TyThing
662 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
663 = tcTyVarBndrs tvs $ \ tvs' -> do
664 { traceTc (text "tcd1" <+> ppr tc_name)
665 ; rhs_ty' <- tcHsKindedType rhs_ty
666 ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty')
667 (typeKind rhs_ty') Nothing
668 ; return (ATyCon tycon)
670 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
673 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
675 tcTyClDecl calc_isrec decl
676 = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
678 -- "type family" declarations
679 tcTyClDecl1 :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
680 tcTyClDecl1 _calc_isrec
681 (TyFamily {tcdFlavour = TypeFamily,
682 tcdLName = L _ tc_name, tcdTyVars = tvs,
683 tcdKind = Just kind}) -- NB: kind at latest added during kind checking
684 = tcTyVarBndrs tvs $ \ tvs' -> do
685 { traceTc (text "type family: " <+> ppr tc_name)
687 -- Check that we don't use families without -XTypeFamilies
688 ; idx_tys <- doptM Opt_TypeFamilies
689 ; checkTc idx_tys $ badFamInstDecl tc_name
691 -- Check for no type indices
692 ; checkTc (not (null tvs)) (noIndexTypes tc_name)
694 ; tycon <- buildSynTyCon tc_name tvs' (OpenSynTyCon kind Nothing) kind Nothing
695 ; return [ATyCon tycon]
698 -- "data family" declaration
699 tcTyClDecl1 _calc_isrec
700 (TyFamily {tcdFlavour = DataFamily,
701 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
702 = tcTyVarBndrs tvs $ \ tvs' -> do
703 { traceTc (text "data family: " <+> ppr tc_name)
704 ; extra_tvs <- tcDataKindSig mb_kind
705 ; let final_tvs = tvs' ++ extra_tvs -- we may not need these
708 -- Check that we don't use families without -XTypeFamilies
709 ; idx_tys <- doptM Opt_TypeFamilies
710 ; checkTc idx_tys $ badFamInstDecl tc_name
712 -- Check for no type indices
713 ; checkTc (not (null tvs)) (noIndexTypes tc_name)
715 ; tycon <- buildAlgTyCon tc_name final_tvs []
716 mkOpenDataTyConRhs Recursive False True Nothing
717 ; return [ATyCon tycon]
720 -- "newtype" and "data"
721 -- NB: not used for newtype/data instances (whether associated or not)
722 tcTyClDecl1 calc_isrec
723 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
724 tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
725 = tcTyVarBndrs tvs $ \ tvs' -> do
726 { extra_tvs <- tcDataKindSig mb_ksig
727 ; let final_tvs = tvs' ++ extra_tvs
728 ; stupid_theta <- tcHsKindedContext ctxt
729 ; want_generic <- doptM Opt_Generics
730 ; unbox_strict <- doptM Opt_UnboxStrictFields
731 ; empty_data_decls <- doptM Opt_EmptyDataDecls
732 ; kind_signatures <- doptM Opt_KindSignatures
733 ; existential_ok <- doptM Opt_ExistentialQuantification
734 ; gadt_ok <- doptM Opt_GADTs
735 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
736 ; let ex_ok = existential_ok || gadt_ok -- Data cons can have existential context
738 -- Check that we don't use GADT syntax in H98 world
739 ; checkTc (gadt_ok || h98_syntax) (badGadtDecl tc_name)
741 -- Check that we don't use kind signatures without Glasgow extensions
742 ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
744 -- Check that the stupid theta is empty for a GADT-style declaration
745 ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
747 -- Check that a newtype has exactly one constructor
748 -- Do this before checking for empty data decls, so that
749 -- we don't suggest -XEmptyDataDecls for newtypes
750 ; checkTc (new_or_data == DataType || isSingleton cons)
751 (newtypeConError tc_name (length cons))
753 -- Check that there's at least one condecl,
754 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
755 ; checkTc (not (null cons) || empty_data_decls || is_boot)
756 (emptyConDeclsErr tc_name)
758 ; tycon <- fixM (\ tycon -> do
759 { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
760 ; data_cons <- tcConDecls unbox_strict ex_ok
761 tycon (final_tvs, res_ty) cons
763 if null cons && is_boot -- In a hs-boot file, empty cons means
764 then return AbstractTyCon -- "don't know"; hence Abstract
765 else case new_or_data of
766 DataType -> return (mkDataTyConRhs data_cons)
767 NewType -> ASSERT( not (null data_cons) )
768 mkNewTyConRhs tc_name tycon (head data_cons)
769 ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
770 (want_generic && canDoGenerics data_cons) h98_syntax Nothing
772 ; return [ATyCon tycon]
775 is_rec = calc_isrec tc_name
776 h98_syntax = consUseH98Syntax cons
778 tcTyClDecl1 calc_isrec
779 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
780 tcdCtxt = ctxt, tcdMeths = meths,
781 tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
782 = tcTyVarBndrs tvs $ \ tvs' -> do
783 { ctxt' <- tcHsKindedContext ctxt
784 ; fds' <- mapM (addLocM tc_fundep) fundeps
785 ; atss <- mapM (addLocM (tcTyClDecl1 (const Recursive))) ats
786 -- NB: 'ats' only contains "type family" and "data family"
787 -- declarations as well as type family defaults
788 ; let ats' = map (setAssocFamilyPermutation tvs') (concat atss)
789 ; sig_stuff <- tcClassSigs class_name sigs meths
790 ; clas <- fixM (\ clas ->
791 let -- This little knot is just so we can get
792 -- hold of the name of the class TyCon, which we
793 -- need to look up its recursiveness
794 tycon_name = tyConName (classTyCon clas)
795 tc_isrec = calc_isrec tycon_name
797 buildClass False {- Must include unfoldings for selectors -}
798 class_name tvs' ctxt' fds' ats'
800 ; return (AClass clas : ats')
801 -- NB: Order is important due to the call to `mkGlobalThings' when
802 -- tying the the type and class declaration type checking knot.
805 tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
806 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
807 ; return (tvs1', tvs2') }
810 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
811 = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
813 tcTyClDecl1 _ d = pprPanic "tcTyClDecl1" (ppr d)
815 -----------------------------------
816 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
817 -> [LConDecl Name] -> TcM [DataCon]
818 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
819 = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
821 tcConDecl :: Bool -- True <=> -funbox-strict_fields
822 -> Bool -- True <=> -XExistentialQuantificaton or -XGADTs
823 -> TyCon -- Representation tycon
824 -> ([TyVar], Type) -- Return type template (with its template tyvars)
828 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl -- Data types
829 (ConDecl name _ tvs ctxt details res_ty _)
830 = addErrCtxt (dataConCtxt name) $
831 tcTyVarBndrs tvs $ \ tvs' -> do
832 { ctxt' <- tcHsKindedContext ctxt
833 ; checkTc (existential_ok || (null tvs && null (unLoc ctxt)))
834 (badExistential name)
835 ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
837 tc_datacon is_infix field_lbls btys
838 = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
839 ; buildDataCon (unLoc name) is_infix
841 univ_tvs ex_tvs eq_preds ctxt' arg_tys
843 -- NB: we put data_tc, the type constructor gotten from the
844 -- constructor type signature into the data constructor;
845 -- that way checkValidDataCon can complain if it's wrong.
848 PrefixCon btys -> tc_datacon False [] btys
849 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
850 RecCon fields -> tc_datacon False field_names btys
852 field_names = map (unLoc . cd_fld_name) fields
853 btys = map cd_fld_type fields
857 -- data instance T (b,c) where
858 -- TI :: forall e. e -> T (e,e)
860 -- The representation tycon looks like this:
861 -- data :R7T b c where
862 -- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
863 -- In this case orig_res_ty = T (e,e)
865 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
866 -- data instance T [a] b c = ...
867 -- gives template ([a,b,c], T [a] b c)
868 -> [TyVar] -- where MkT :: forall x y z. ...
870 -> TcM ([TyVar], -- Universal
871 [TyVar], -- Existential (distinct OccNames from univs)
872 [(TyVar,Type)], -- Equality predicates
873 Type) -- Typechecked return type
874 -- We don't check that the TyCon given in the ResTy is
875 -- the same as the parent tycon, becuase we are in the middle
876 -- of a recursive knot; so it's postponed until checkValidDataCon
878 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
879 = return (tmpl_tvs, dc_tvs, [], res_ty)
880 -- In H98 syntax the dc_tvs are the existential ones
881 -- data T a b c = forall d e. MkT ...
882 -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
884 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
885 -- E.g. data T [a] b c where
886 -- MkT :: forall x y z. T [(x,y)] z z
888 -- Univ tyvars Eq-spec
892 -- Existentials are the leftover type vars: [x,y]
893 -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
894 = do { res_ty' <- tcHsKindedType res_ty
895 ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
897 -- /Lazily/ figure out the univ_tvs etc
898 -- Each univ_tv is either a dc_tv or a tmpl_tv
899 (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
900 choose tmpl (univs, eqs)
901 | Just ty <- lookupTyVar subst tmpl
902 = case tcGetTyVar_maybe ty of
903 Just tv | not (tv `elem` univs)
905 _other -> (tmpl:univs, (tmpl,ty):eqs)
906 | otherwise = pprPanic "tcResultType" (ppr res_ty)
907 ex_tvs = dc_tvs `minusList` univ_tvs
909 ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
911 -- NB: tmpl_tvs and dc_tvs are distinct, but
912 -- we want them to be *visibly* distinct, both for
913 -- interface files and general confusion. So rename
914 -- the tc_tvs, since they are not used yet (no
915 -- consequential renaming needed)
916 (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
917 init_occ_env = initTidyOccEnv (map getOccName dc_tvs)
918 tidy_one env tv = (env', setTyVarName tv (tidyNameOcc name occ'))
921 (env', occ') = tidyOccName env (getOccName name)
923 consUseH98Syntax :: [LConDecl a] -> Bool
924 consUseH98Syntax (L _ (ConDecl { con_res = ResTyGADT _ }) : _) = False
925 consUseH98Syntax _ = True
926 -- All constructors have same shape
929 tcConArg :: Bool -- True <=> -funbox-strict_fields
931 -> TcM (TcType, StrictnessMark)
932 tcConArg unbox_strict bty
933 = do { arg_ty <- tcHsBangType bty
934 ; let bang = getBangStrictness bty
935 ; return (arg_ty, chooseBoxingStrategy unbox_strict arg_ty bang) }
937 -- We attempt to unbox/unpack a strict field when either:
938 -- (i) The field is marked '!!', or
939 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
941 -- We have turned off unboxing of newtypes because coercions make unboxing
942 -- and reboxing more complicated
943 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> StrictnessMark
944 chooseBoxingStrategy unbox_strict_fields arg_ty bang
946 HsNoBang -> NotMarkedStrict
947 HsStrict | unbox_strict_fields
948 && can_unbox arg_ty -> MarkedUnboxed
949 HsUnbox | can_unbox arg_ty -> MarkedUnboxed
952 -- we can unbox if the type is a chain of newtypes with a product tycon
954 can_unbox arg_ty = case splitTyConApp_maybe arg_ty of
956 Just (arg_tycon, tycon_args) ->
957 not (isRecursiveTyCon arg_tycon) && -- Note [Recusive unboxing]
958 isProductTyCon arg_tycon &&
959 (if isNewTyCon arg_tycon then
960 can_unbox (newTyConInstRhs arg_tycon tycon_args)
964 Note [Recursive unboxing]
965 ~~~~~~~~~~~~~~~~~~~~~~~~~
966 Be careful not to try to unbox this!
968 But it's the *argument* type that matters. This is fine:
970 because Int is non-recursive.
973 %************************************************************************
977 %************************************************************************
979 Validity checking is done once the mutually-recursive knot has been
980 tied, so we can look at things freely.
983 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
984 checkCycleErrs tyclss
988 = do { mapM_ recClsErr cls_cycles
989 ; failM } -- Give up now, because later checkValidTyCl
990 -- will loop if the synonym is recursive
992 cls_cycles = calcClassCycles tyclss
994 checkValidTyCl :: TyClDecl Name -> TcM ()
995 -- We do the validity check over declarations, rather than TyThings
996 -- only so that we can add a nice context with tcAddDeclCtxt
998 = tcAddDeclCtxt decl $
999 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
1000 ; traceTc (text "Validity of" <+> ppr thing)
1002 ATyCon tc -> checkValidTyCon tc
1003 AClass cl -> checkValidClass cl
1004 _ -> panic "checkValidTyCl"
1005 ; traceTc (text "Done validity of" <+> ppr thing)
1008 -------------------------
1009 -- For data types declared with record syntax, we require
1010 -- that each constructor that has a field 'f'
1011 -- (a) has the same result type
1012 -- (b) has the same type for 'f'
1013 -- module alpha conversion of the quantified type variables
1014 -- of the constructor.
1016 -- Note that we allow existentials to match becuase the
1017 -- fields can never meet. E.g
1019 -- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1020 -- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
1021 -- Here we do not complain about f1,f2 because they are existential
1023 checkValidTyCon :: TyCon -> TcM ()
1026 = case synTyConRhs tc of
1027 OpenSynTyCon _ _ -> return ()
1028 SynonymTyCon ty -> checkValidType syn_ctxt ty
1030 = do -- Check the context on the data decl
1031 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1033 -- Check arg types of data constructors
1034 mapM_ (checkValidDataCon tc) data_cons
1036 -- Check that fields with the same name share a type
1037 mapM_ check_fields groups
1040 syn_ctxt = TySynCtxt name
1042 data_cons = tyConDataCons tc
1044 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1045 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1046 get_fields con = dataConFieldLabels con `zip` repeat con
1047 -- dataConFieldLabels may return the empty list, which is fine
1049 -- See Note [GADT record selectors] in MkId.lhs
1050 -- We must check (a) that the named field has the same
1051 -- type in each constructor
1052 -- (b) that those constructors have the same result type
1054 -- However, the constructors may have differently named type variable
1055 -- and (worse) we don't know how the correspond to each other. E.g.
1056 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
1057 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
1059 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1060 -- result type against other candidates' types BOTH WAYS ROUND.
1061 -- If they magically agrees, take the substitution and
1062 -- apply them to the latter ones, and see if they match perfectly.
1063 check_fields ((label, con1) : other_fields)
1064 -- These fields all have the same name, but are from
1065 -- different constructors in the data type
1066 = recoverM (return ()) $ mapM_ checkOne other_fields
1067 -- Check that all the fields in the group have the same type
1068 -- NB: this check assumes that all the constructors of a given
1069 -- data type use the same type variables
1071 (tvs1, _, _, res1) = dataConSig con1
1073 fty1 = dataConFieldType con1 label
1075 checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
1076 = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1077 ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1079 (tvs2, _, _, res2) = dataConSig con2
1081 fty2 = dataConFieldType con2 label
1082 check_fields [] = panic "checkValidTyCon/check_fields []"
1084 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1085 -> Type -> Type -> Type -> Type -> TcM ()
1086 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1087 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1088 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1090 mb_subst1 = tcMatchTy tvs1 res1 res2
1091 mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1093 -------------------------------
1094 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1095 checkValidDataCon tc con
1096 = setSrcSpan (srcLocSpan (getSrcLoc con)) $
1097 addErrCtxt (dataConCtxt con) $
1098 do { let tc_tvs = tyConTyVars tc
1099 res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1100 actual_res_ty = dataConOrigResTy con
1101 ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1104 (badDataConTyCon con res_ty_tmpl actual_res_ty)
1105 ; checkValidMonoType (dataConOrigResTy con)
1106 -- Disallow MkT :: T (forall a. a->a)
1107 -- Reason: it's really the argument of an equality constraint
1108 ; checkValidType ctxt (dataConUserType con)
1109 ; when (isNewTyCon tc) (checkNewDataCon con)
1112 ctxt = ConArgCtxt (dataConName con)
1114 -------------------------------
1115 checkNewDataCon :: DataCon -> TcM ()
1116 -- Checks for the data constructor of a newtype
1118 = do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1120 ; checkTc (null eq_spec) (newtypePredError con)
1121 -- Return type is (T a b c)
1122 ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1124 ; checkTc (not (any isMarkedStrict (dataConStrictMarks con)))
1125 (newtypeStrictError con)
1129 (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1131 -------------------------------
1132 checkValidClass :: Class -> TcM ()
1134 = do { constrained_class_methods <- doptM Opt_ConstrainedClassMethods
1135 ; multi_param_type_classes <- doptM Opt_MultiParamTypeClasses
1136 ; fundep_classes <- doptM Opt_FunctionalDependencies
1138 -- Check that the class is unary, unless GlaExs
1139 ; checkTc (notNull tyvars) (nullaryClassErr cls)
1140 ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1141 ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1143 -- Check the super-classes
1144 ; checkValidTheta (ClassSCCtxt (className cls)) theta
1146 -- Check the class operations
1147 ; mapM_ (check_op constrained_class_methods) op_stuff
1149 -- Check that if the class has generic methods, then the
1150 -- class has only one parameter. We can't do generic
1151 -- multi-parameter type classes!
1152 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1155 (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1156 unary = isSingleton tyvars
1157 no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1159 check_op constrained_class_methods (sel_id, dm)
1160 = addErrCtxt (classOpCtxt sel_id tau) $ do
1161 { checkValidTheta SigmaCtxt (tail theta)
1162 -- The 'tail' removes the initial (C a) from the
1163 -- class itself, leaving just the method type
1165 ; traceTc (text "class op type" <+> ppr op_ty <+> ppr tau)
1166 ; checkValidType (FunSigCtxt op_name) tau
1168 -- Check that the type mentions at least one of
1169 -- the class type variables...or at least one reachable
1170 -- from one of the class variables. Example: tc223
1171 -- class Error e => Game b mv e | b -> mv e where
1172 -- newBoard :: MonadState b m => m ()
1173 -- Here, MonadState has a fundep m->b, so newBoard is fine
1174 ; let grown_tyvars = growThetaTyVars theta (mkVarSet tyvars)
1175 ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1176 (noClassTyVarErr cls sel_id)
1178 -- Check that for a generic method, the type of
1179 -- the method is sufficiently simple
1180 ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1181 (badGenericMethodType op_name op_ty)
1184 op_name = idName sel_id
1185 op_ty = idType sel_id
1186 (_,theta1,tau1) = tcSplitSigmaTy op_ty
1187 (_,theta2,tau2) = tcSplitSigmaTy tau1
1188 (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1189 | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1190 -- Ugh! The function might have a type like
1191 -- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1192 -- With -XConstrainedClassMethods, we want to allow this, even though the inner
1193 -- forall has an (Eq a) constraint. Whereas in general, each constraint
1194 -- in the context of a for-all must mention at least one quantified
1195 -- type variable. What a mess!
1199 %************************************************************************
1201 Building record selectors
1203 %************************************************************************
1206 mkAuxBinds :: [TyThing] -> HsValBinds Name
1207 mkAuxBinds ty_things
1208 = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1210 (sigs, binds) = unzip rec_sels
1211 rec_sels = map mkRecSelBind [ (tc,fld)
1212 | ATyCon tc <- ty_things
1213 , fld <- tyConFields tc ]
1216 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1217 mkRecSelBind (tycon, sel_name)
1218 = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1220 loc = getSrcSpan tycon
1221 sel_id = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1222 rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1224 -- Find a representative constructor, con1
1225 all_cons = tyConDataCons tycon
1226 cons_w_field = [ con | con <- all_cons
1227 , sel_name `elem` dataConFieldLabels con ]
1228 con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1230 -- Selector type; Note [Polymorphic selectors]
1231 field_ty = dataConFieldType con1 sel_name
1232 (field_tvs, field_theta, field_tau)
1233 | is_naughty = ([], [], unitTy)
1234 | otherwise = tcSplitSigmaTy field_ty
1235 data_ty = dataConOrigResTy con1
1236 data_tvs = tyVarsOfType data_ty
1237 is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)
1238 sel_ty = mkForAllTys (varSetElems data_tvs ++ field_tvs) $
1239 mkPhiTy (dataConStupidTheta con1) $ -- Urgh!
1240 mkPhiTy field_theta $ -- Urgh!
1241 mkFunTy data_ty field_tau
1243 -- Make the binding: sel (C2 { fld = x }) = x
1244 -- sel (C7 { fld = x }) = x
1245 -- where cons_w_field = [C2,C7]
1246 sel_bind = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1247 mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)]
1249 mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1250 rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1251 rec_field = HsRecField { hsRecFieldId = sel_lname
1252 , hsRecFieldArg = nlVarPat field_var
1253 , hsRecPun = False }
1254 match_body | is_naughty = ExplicitTuple [] Boxed
1255 | otherwise = HsVar field_var
1256 sel_lname = L loc sel_name
1257 field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1259 -- Add catch-all default case unless the case is exhaustive
1260 -- We do this explicitly so that we get a nice error message that
1261 -- mentions this particular record selector
1262 deflt | length cons_w_field == length all_cons = []
1263 | otherwise = [mkSimpleMatch [nlWildPat]
1264 (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1266 msg_lit = HsStringPrim $ mkFastString $
1267 occNameString (getOccName sel_name)
1270 tyConFields :: TyCon -> [FieldLabel]
1272 | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1276 Note [Polymorphic selectors]
1277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1278 When a record has a polymorphic field, we pull the foralls out to the front.
1279 data T = MkT { f :: forall a. [a] -> a }
1280 Then f :: forall a. T -> [a] -> a
1281 NOT f :: T -> forall a. [a] -> a
1283 This is horrid. It's only needed in deeply obscure cases, which I hate.
1284 The only case I know is test tc163, which is worth looking at. It's far
1285 from clear that this test should succeed at all!
1287 Note [Naughty record selectors]
1288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1289 A "naughty" field is one for which we can't define a record
1290 selector, because an existential type variable would escape. For example:
1291 data T = forall a. MkT { x,y::a }
1292 We obviously can't define
1294 Nevertheless we *do* put a RecSelId into the type environment
1295 so that if the user tries to use 'x' as a selector we can bleat
1296 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1297 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1299 In general, a field is naughty if its type mentions a type variable that
1300 isn't in the result type of the constructor.
1302 We make a dummy binding for naughty selectors, so that they can be treated
1303 uniformly, apart from their sel_naughty field. The function is never called.
1305 Note [GADT record selectors]
1306 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1307 For GADTs, we require that all constructors with a common field 'f' have the same
1308 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
1311 T1 { f :: Maybe a } :: T [a]
1312 T2 { f :: Maybe a, y :: b } :: T [a]
1314 and now the selector takes that result type as its argument:
1315 f :: forall a. T [a] -> Maybe a
1317 Details: the "real" types of T1,T2 are:
1318 T1 :: forall r a. (r~[a]) => a -> T r
1319 T2 :: forall r a b. (r~[a]) => a -> b -> T r
1321 So the selector loooks like this:
1322 f :: forall a. T [a] -> Maybe a
1325 T1 c (g:[a]~[c]) (v:Maybe c) -> v `cast` Maybe (right (sym g))
1326 T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1328 Note the forall'd tyvars of the selector are just the free tyvars
1329 of the result type; there may be other tyvars in the constructor's
1330 type (e.g. 'b' in T2).
1332 Note the need for casts in the result!
1334 Note [Selector running example]
1335 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1336 It's OK to combine GADTs and type families. Here's a running example:
1338 data instance T [a] where
1339 T1 { fld :: b } :: T [Maybe b]
1341 The representation type looks like this
1343 T1 { fld :: b } :: :R7T (Maybe b)
1345 and there's coercion from the family type to the representation type
1346 :CoR7T a :: T [a] ~ :R7T a
1348 The selector we want for fld looks like this:
1350 fld :: forall b. T [Maybe b] -> b
1351 fld = /\b. \(d::T [Maybe b]).
1352 case d `cast` :CoR7T (Maybe b) of
1355 The scrutinee of the case has type :R7T (Maybe b), which can be
1356 gotten by appying the eq_spec to the univ_tvs of the data con.
1358 %************************************************************************
1362 %************************************************************************
1365 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1366 resultTypeMisMatch field_name con1 con2
1367 = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1368 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1369 nest 2 $ ptext (sLit "but have different result types")]
1371 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1372 fieldTypeMisMatch field_name con1 con2
1373 = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1374 ptext (sLit "give different types for field"), quotes (ppr field_name)]
1376 dataConCtxt :: Outputable a => a -> SDoc
1377 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1379 classOpCtxt :: Var -> Type -> SDoc
1380 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1381 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1383 nullaryClassErr :: Class -> SDoc
1385 = ptext (sLit "No parameters for class") <+> quotes (ppr cls)
1387 classArityErr :: Class -> SDoc
1389 = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1390 parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1392 classFunDepsErr :: Class -> SDoc
1394 = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1395 parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1397 noClassTyVarErr :: Class -> Var -> SDoc
1398 noClassTyVarErr clas op
1399 = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1400 ptext (sLit "mentions none of the type variables of the class") <+>
1401 ppr clas <+> hsep (map ppr (classTyVars clas))]
1403 genericMultiParamErr :: Class -> SDoc
1404 genericMultiParamErr clas
1405 = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+>
1406 ptext (sLit "cannot have generic methods")
1408 badGenericMethodType :: Name -> Kind -> SDoc
1409 badGenericMethodType op op_ty
1410 = hang (ptext (sLit "Generic method type is too complex"))
1411 4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1412 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1414 recSynErr :: [LTyClDecl Name] -> TcRn ()
1416 = setSrcSpan (getLoc (head sorted_decls)) $
1417 addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1418 nest 2 (vcat (map ppr_decl sorted_decls))])
1420 sorted_decls = sortLocated syn_decls
1421 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1423 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1425 = setSrcSpan (getLoc (head sorted_decls)) $
1426 addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1427 nest 2 (vcat (map ppr_decl sorted_decls))])
1429 sorted_decls = sortLocated cls_decls
1430 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1432 sortLocated :: [Located a] -> [Located a]
1433 sortLocated things = sortLe le things
1435 le (L l1 _) (L l2 _) = l1 <= l2
1437 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1438 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1439 = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1440 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1441 2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1443 badGadtDecl :: Name -> SDoc
1445 = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1446 , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1448 badExistential :: Located Name -> SDoc
1449 badExistential con_name
1450 = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1451 ptext (sLit "has existential type variables, or a context"))
1452 2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1454 badStupidTheta :: Name -> SDoc
1455 badStupidTheta tc_name
1456 = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1458 newtypeConError :: Name -> Int -> SDoc
1459 newtypeConError tycon n
1460 = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1461 nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1463 newtypeExError :: DataCon -> SDoc
1465 = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1466 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1468 newtypeStrictError :: DataCon -> SDoc
1469 newtypeStrictError con
1470 = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1471 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1473 newtypePredError :: DataCon -> SDoc
1474 newtypePredError con
1475 = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1476 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1478 newtypeFieldErr :: DataCon -> Int -> SDoc
1479 newtypeFieldErr con_name n_flds
1480 = sep [ptext (sLit "The constructor of a newtype must have exactly one field"),
1481 nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1483 badSigTyDecl :: Name -> SDoc
1484 badSigTyDecl tc_name
1485 = vcat [ ptext (sLit "Illegal kind signature") <+>
1486 quotes (ppr tc_name)
1487 , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1489 noIndexTypes :: Name -> SDoc
1490 noIndexTypes tc_name
1491 = ptext (sLit "Type family constructor") <+> quotes (ppr tc_name)
1492 <+> ptext (sLit "must have at least one type index parameter")
1494 badFamInstDecl :: Outputable a => a -> SDoc
1495 badFamInstDecl tc_name
1496 = vcat [ ptext (sLit "Illegal family instance for") <+>
1497 quotes (ppr tc_name)
1498 , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1500 tooManyParmsErr :: Located Name -> SDoc
1501 tooManyParmsErr tc_name
1502 = ptext (sLit "Family instance has too many parameters:") <+>
1503 quotes (ppr tc_name)
1505 tooFewParmsErr :: Arity -> SDoc
1506 tooFewParmsErr arity
1507 = ptext (sLit "Family instance has too few parameters; expected") <+>
1510 wrongNumberOfParmsErr :: Arity -> SDoc
1511 wrongNumberOfParmsErr exp_arity
1512 = ptext (sLit "Number of parameters must match family declaration; expected")
1515 badBootFamInstDeclErr :: SDoc
1516 badBootFamInstDeclErr =
1517 ptext (sLit "Illegal family instance in hs-boot file")
1519 wrongKindOfFamily :: TyCon -> SDoc
1520 wrongKindOfFamily family =
1521 ptext (sLit "Wrong category of family instance; declaration was for a") <+>
1524 kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1525 | isAlgTyCon family = ptext (sLit "data type")
1526 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1528 emptyConDeclsErr :: Name -> SDoc
1529 emptyConDeclsErr tycon
1530 = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1531 nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]