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, mkRecSelBinds
13 #include "HsVersions.h"
26 import TysWiredIn ( unitTy )
33 import MkId ( mkDefaultMethodId )
34 import MkCore ( rEC_SEL_ERROR_ID )
48 import Unique ( mkBuiltinUnique )
57 %************************************************************************
59 \subsection{Type checking for type and class declarations}
61 %************************************************************************
65 Consider a mutually-recursive group, binding
66 a type constructor T and a class C.
68 Step 1: getInitialKind
69 Construct a KindEnv by binding T and C to a kind variable
72 In that environment, do a kind check
74 Step 3: Zonk the kinds
76 Step 4: buildTyConOrClass
77 Construct an environment binding T to a TyCon and C to a Class.
78 a) Their kinds comes from zonking the relevant kind variable
79 b) Their arity (for synonyms) comes direct from the decl
80 c) The funcional dependencies come from the decl
81 d) The rest comes a knot-tied binding of T and C, returned from Step 4
82 e) The variances of the tycons in the group is calculated from
86 In this environment, walk over the decls, constructing the TyCons and Classes.
87 This uses in a strict way items (a)-(c) above, which is why they must
88 be constructed in Step 4. Feed the results back to Step 4.
89 For this step, pass the is-recursive flag as the wimp-out flag
93 Step 6: Extend environment
94 We extend the type environment with bindings not only for the TyCons and Classes,
95 but also for their "implicit Ids" like data constructors and class selectors
97 Step 7: checkValidTyCl
98 For a recursive group only, check all the decls again, just
99 to check all the side conditions on validity. We could not
100 do this before because we were in a mutually recursive knot.
102 Identification of recursive TyCons
103 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
104 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
107 Identifying a TyCon as recursive serves two purposes
109 1. Avoid infinite types. Non-recursive newtypes are treated as
110 "transparent", like type synonyms, after the type checker. If we did
111 this for all newtypes, we'd get infinite types. So we figure out for
112 each newtype whether it is "recursive", and add a coercion if so. In
113 effect, we are trying to "cut the loops" by identifying a loop-breaker.
115 2. Avoid infinite unboxing. This is nothing to do with newtypes.
119 Well, this function diverges, but we don't want the strictness analyser
120 to diverge. But the strictness analyser will diverge because it looks
121 deeper and deeper into the structure of T. (I believe there are
122 examples where the function does something sane, and the strictness
123 analyser still diverges, but I can't see one now.)
125 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
126 newtypes. I did this as an experiment, to try to expose cases in which
127 the coercions got in the way of optimisations. If it turns out that we
128 can indeed always use a coercion, then we don't risk recursive types,
129 and don't need to figure out what the loop breakers are.
131 For newtype *families* though, we will always have a coercion, so they
132 are always loop breakers! So you can easily adjust the current
133 algorithm by simply treating all newtype families as loop breakers (and
134 indeed type families). I think.
137 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
138 -> TcM (TcGblEnv, -- Input env extended by types and classes
139 -- and their implicit Ids,DataCons
140 HsValBinds Name, -- Renamed bindings for record selectors
141 [Id]) -- Default method ids
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 "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 "ready for validity check" empty
198 ; mapM_ (addLocM checkValidTyCl) decls
199 ; traceTc "done" empty
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 ; rec_sel_binds = mkRecSelBinds alg_tyclss
209 ; dm_ids = mkDefaultMethodIds alg_tyclss }
210 ; traceTc "Adding types and classes" $ vcat
212 , text "and" <+> ppr implicit_things ]
213 ; env <- tcExtendGlobalEnv implicit_things getGblEnv
214 ; return (env, rec_sel_binds, dm_ids) }
217 -- Pull associated types out of class declarations, to tie them into the
219 -- NB: We put them in the same place in the list as `tcTyClDecl' will
220 -- eventually put the matching `TyThing's. That's crucial; otherwise,
221 -- the two argument lists of `mkGlobalThings' don't match up.
222 addATs decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
225 mkGlobalThings :: [LTyClDecl Name] -- The decls
226 -> [TyThing] -- Knot-tied, in 1-1 correspondence with the decls
228 -- Driven by the Decls, and treating the TyThings lazily
229 -- make a TypeEnv for the new things
230 mkGlobalThings decls things
231 = map mk_thing (decls `zipLazy` things)
233 mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
235 mk_thing (L _ decl, ~(ATyCon tc))
236 = (tcdName decl, ATyCon tc)
240 %************************************************************************
242 Type checking family instances
244 %************************************************************************
246 Family instances are somewhat of a hybrid. They are processed together with
247 class instance heads, but can contain data constructors and hence they share a
248 lot of kinding and type checking code with ordinary algebraic data types (and
252 tcFamInstDecl :: TopLevelFlag -> LTyClDecl Name -> TcM TyThing
253 tcFamInstDecl top_lvl (L loc decl)
254 = -- Prime error recovery, set source location
257 do { -- type family instances require -XTypeFamilies
258 -- and can't (currently) be in an hs-boot file
259 ; type_families <- xoptM Opt_TypeFamilies
260 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
261 ; checkTc type_families $ badFamInstDecl (tcdLName decl)
262 ; checkTc (not is_boot) $ badBootFamInstDeclErr
264 -- Perform kind and type checking
265 ; tc <- tcFamInstDecl1 decl
266 ; checkValidTyCon tc -- Remember to check validity;
267 -- no recursion to worry about here
269 -- Check that toplevel type instances are not for associated types.
270 ; when (isTopLevel top_lvl && isAssocFamily tc)
271 (addErr $ assocInClassErr (tcdName decl))
273 ; return (ATyCon tc) }
275 isAssocFamily :: TyCon -> Bool -- Is an assocaited type
277 = case tyConFamInst_maybe tycon of
278 Nothing -> panic "isAssocFamily: no family?!?"
279 Just (fam, _) -> isTyConAssoc fam
281 assocInClassErr :: Name -> SDoc
283 = ptext (sLit "Associated type") <+> quotes (ppr name) <+>
284 ptext (sLit "must be inside a class instance")
288 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
291 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
292 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
293 do { -- check that the family declaration is for a synonym
294 checkTc (isFamilyTyCon family) (notFamily family)
295 ; checkTc (isSynTyCon family) (wrongKindOfFamily family)
297 ; -- (1) kind check the right-hand side of the type equation
298 ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) (EK resKind EkUnk)
299 -- ToDo: the ExpKind could be better
301 -- we need the exact same number of type parameters as the family
303 ; let famArity = tyConArity family
304 ; checkTc (length k_typats == famArity) $
305 wrongNumberOfParmsErr famArity
307 -- (2) type check type equation
308 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
309 ; t_typats <- mapM tcHsKindedType k_typats
310 ; t_rhs <- tcHsKindedType k_rhs
312 -- (3) check the well-formedness of the instance
313 ; checkValidTypeInst t_typats t_rhs
315 -- (4) construct representation tycon
316 ; rep_tc_name <- newFamInstTyConName tc_name t_typats loc
317 ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs)
319 NoParentTyCon (Just (family, t_typats))
322 -- "newtype instance" and "data instance"
323 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
325 = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
326 do { -- check that the family declaration is for the right kind
327 checkTc (isFamilyTyCon fam_tycon) (notFamily fam_tycon)
328 ; checkTc (isAlgTyCon fam_tycon) (wrongKindOfFamily fam_tycon)
330 ; -- (1) kind check the data declaration as usual
331 ; k_decl <- kcDataDecl decl k_tvs
332 ; let k_ctxt = tcdCtxt k_decl
333 k_cons = tcdCons k_decl
335 -- result kind must be '*' (otherwise, we have too few patterns)
336 ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
338 -- (2) type check indexed data type declaration
339 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
340 ; unbox_strict <- doptM Opt_UnboxStrictFields
342 -- kind check the type indexes and the context
343 ; t_typats <- mapM tcHsKindedType k_typats
344 ; stupid_theta <- tcHsKindedContext k_ctxt
347 -- (a) left-hand side contains no type family applications
348 -- (vanilla synonyms are fine, though, and we checked for
350 ; mapM_ checkTyFamFreeness t_typats
352 -- Check that we don't use GADT syntax in H98 world
353 ; gadt_ok <- xoptM Opt_GADTs
354 ; checkTc (gadt_ok || consUseH98Syntax cons) (badGadtDecl tc_name)
356 -- (b) a newtype has exactly one constructor
357 ; checkTc (new_or_data == DataType || isSingleton k_cons) $
358 newtypeConError tc_name (length k_cons)
360 -- (4) construct representation tycon
361 ; rep_tc_name <- newFamInstTyConName tc_name t_typats loc
362 ; let ex_ok = True -- Existentials ok for type families!
363 ; fixM (\ rep_tycon -> do
364 { let orig_res_ty = mkTyConApp fam_tycon t_typats
365 ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
366 (t_tvs, orig_res_ty) k_cons
369 DataType -> return (mkDataTyConRhs data_cons)
370 NewType -> ASSERT( not (null data_cons) )
371 mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
372 ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
373 False h98_syntax NoParentTyCon (Just (fam_tycon, t_typats))
374 -- We always assume that indexed types are recursive. Why?
375 -- (1) Due to their open nature, we can never be sure that a
376 -- further instance might not introduce a new recursive
377 -- dependency. (2) They are always valid loop breakers as
378 -- they involve a coercion.
382 h98_syntax = case cons of -- All constructors have same shape
383 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
386 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
388 -- Kind checking of indexed types
391 -- Kind check type patterns and kind annotate the embedded type variables.
393 -- * Here we check that a type instance matches its kind signature, but we do
394 -- not check whether there is a pattern for each type index; the latter
395 -- check is only required for type synonym instances.
397 kcIdxTyPats :: TyClDecl Name
398 -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
399 -- ^^kinded tvs ^^kinded ty pats ^^res kind
401 kcIdxTyPats decl thing_inside
402 = kcHsTyVars (tcdTyVars decl) $ \tvs ->
403 do { let tc_name = tcdLName decl
404 ; fam_tycon <- tcLookupLocatedTyCon tc_name
405 ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
406 ; hs_typats = fromJust $ tcdTyPats decl }
408 -- we may not have more parameters than the kind indicates
409 ; checkTc (length kinds >= length hs_typats) $
410 tooManyParmsErr (tcdLName decl)
412 -- type functions can have a higher-kinded result
413 ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
414 ; typats <- zipWithM kcCheckLHsType hs_typats
415 [ EK kind (EkArg (ppr tc_name) n)
416 | (kind,n) <- kinds `zip` [1..]]
417 ; thing_inside tvs typats resultKind fam_tycon
422 %************************************************************************
426 %************************************************************************
428 We need to kind check all types in the mutually recursive group
429 before we know the kind of the type variables. For example:
432 op :: D b => a -> b -> b
435 bop :: (Monad c) => ...
437 Here, the kind of the locally-polymorphic type variable "b"
438 depends on *all the uses of class D*. For example, the use of
439 Monad c in bop's type signature means that D must have kind Type->Type.
441 However type synonyms work differently. They can have kinds which don't
442 just involve (->) and *:
443 type R = Int# -- Kind #
444 type S a = Array# a -- Kind * -> #
445 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
446 So we must infer their kinds from their right-hand sides *first* and then
447 use them, whereas for the mutually recursive data types D we bring into
448 scope kind bindings D -> k, where k is a kind variable, and do inference.
452 This treatment of type synonyms only applies to Haskell 98-style synonyms.
453 General type functions can be recursive, and hence, appear in `alg_decls'.
455 The kind of a type family is solely determinded by its kind signature;
456 hence, only kind signatures participate in the construction of the initial
457 kind environment (as constructed by `getInitialKind'). In fact, we ignore
458 instances of families altogether in the following. However, we need to
459 include the kinds of associated families into the construction of the
460 initial kind environment. (This is handled by `allDecls').
463 kcTyClDecls :: [LTyClDecl Name] -> [Located (TyClDecl Name)]
464 -> TcM ([LTyClDecl Name], [Located (TyClDecl Name)])
465 kcTyClDecls syn_decls alg_decls
466 = do { -- First extend the kind env with each data type, class, and
467 -- indexed type, mapping them to a type variable
468 let initialKindDecls = concat [allDecls decl | L _ decl <- alg_decls]
469 ; alg_kinds <- mapM getInitialKind initialKindDecls
470 ; tcExtendKindEnv alg_kinds $ do
472 -- Now kind-check the type synonyms, in dependency order
473 -- We do these differently to data type and classes,
474 -- because a type synonym can be an unboxed type
476 -- and a kind variable can't unify with UnboxedTypeKind
477 -- So we infer their kinds in dependency order
478 { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
479 ; tcExtendKindEnv syn_kinds $ do
481 -- Now kind-check the data type, class, and kind signatures,
482 -- returning kind-annotated decls; we don't kind-check
483 -- instances of indexed types yet, but leave this to
485 { kc_alg_decls <- mapM (wrapLocM kcTyClDecl)
486 (filter (not . isFamInstDecl . unLoc) alg_decls)
488 ; return (kc_syn_decls, kc_alg_decls) }}}
490 -- get all declarations relevant for determining the initial kind
492 allDecls (decl@ClassDecl {tcdATs = ats}) = decl : [ at
495 allDecls decl | isFamInstDecl decl = []
498 ------------------------------------------------------------------------
499 getInitialKind :: TyClDecl Name -> TcM (Name, TcKind)
500 -- Only for data type, class, and indexed type declarations
501 -- Get as much info as possible from the data, class, or indexed type decl,
502 -- so as to maximise usefulness of error messages
504 = do { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
505 ; res_kind <- mk_res_kind decl
506 ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
508 mk_arg_kind (UserTyVar _ _) = newKindVar
509 mk_arg_kind (KindedTyVar _ kind) = return kind
511 mk_res_kind (TyFamily { tcdKind = Just kind }) = return kind
512 mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
513 -- On GADT-style declarations we allow a kind signature
514 -- data T :: *->* where { ... }
515 mk_res_kind _ = return liftedTypeKind
519 kcSynDecls :: [SCC (LTyClDecl Name)]
520 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
521 [(Name,TcKind)]) -- Kind bindings
524 kcSynDecls (group : groups)
525 = do { (decl, nk) <- kcSynDecl group
526 ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
527 ; return (decl:decls, nk:nks) }
530 kcSynDecl :: SCC (LTyClDecl Name)
531 -> TcM (LTyClDecl Name, -- Kind-annotated decls
532 (Name,TcKind)) -- Kind bindings
533 kcSynDecl (AcyclicSCC (L loc decl))
534 = tcAddDeclCtxt decl $
535 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
536 do { traceTc "kcd1" (ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
537 <+> brackets (ppr k_tvs))
538 ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
539 ; traceTc "kcd2" (ppr (unLoc (tcdLName decl)))
540 ; let tc_kind = foldr (mkArrowKind . hsTyVarKind . unLoc) rhs_kind k_tvs
541 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
542 (unLoc (tcdLName decl), tc_kind)) })
544 kcSynDecl (CyclicSCC decls)
545 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
546 -- of out-of-scope tycons
548 ------------------------------------------------------------------------
549 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
550 -- Not used for type synonyms (see kcSynDecl)
552 kcTyClDecl decl@(TyData {})
553 = ASSERT( not . isFamInstDecl $ decl ) -- must not be a family instance
554 kcTyClDeclBody decl $
557 kcTyClDecl decl@(TyFamily {})
558 = kcFamilyDecl [] decl -- the empty list signals a toplevel decl
560 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
561 = kcTyClDeclBody decl $ \ tvs' ->
562 do { ctxt' <- kcHsContext ctxt
563 ; ats' <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
564 ; sigs' <- mapM (wrapLocM kc_sig) sigs
565 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
568 kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
569 ; return (TypeSig nm op_ty') }
570 kc_sig other_sig = return other_sig
572 kcTyClDecl decl@(ForeignType {})
575 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
577 kcTyClDeclBody :: TyClDecl Name
578 -> ([LHsTyVarBndr Name] -> TcM a)
580 -- getInitialKind has made a suitably-shaped kind for the type or class
581 -- Unpack it, and attribute those kinds to the type variables
582 -- Extend the env with bindings for the tyvars, taken from
583 -- the kind of the tycon/class. Give it to the thing inside, and
584 -- check the result kind matches
585 kcTyClDeclBody decl thing_inside
586 = tcAddDeclCtxt decl $
587 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
588 ; let tc_kind = case tc_ty_thing of
590 _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
591 (kinds, _) = splitKindFunTys tc_kind
592 hs_tvs = tcdTyVars decl
593 kinded_tvs = ASSERT( length kinds >= length hs_tvs )
594 zipWith add_kind hs_tvs kinds
595 ; tcExtendKindEnvTvs kinded_tvs thing_inside }
597 add_kind (L loc (UserTyVar n _)) k = L loc (UserTyVar n k)
598 add_kind (L loc (KindedTyVar n _)) k = L loc (KindedTyVar n k)
600 -- Kind check a data declaration, assuming that we already extended the
601 -- kind environment with the type variables of the left-hand side (these
602 -- kinded type variables are also passed as the second parameter).
604 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
605 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
607 = do { ctxt' <- kcHsContext ctxt
608 ; cons' <- mapM (wrapLocM kc_con_decl) cons
609 ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
611 -- doc comments are typechecked to Nothing here
612 kc_con_decl con_decl@(ConDecl { con_name = name, con_qvars = ex_tvs
613 , con_cxt = ex_ctxt, con_details = details, con_res = res })
614 = addErrCtxt (dataConCtxt name) $
615 kcHsTyVars ex_tvs $ \ex_tvs' -> do
616 do { ex_ctxt' <- kcHsContext ex_ctxt
617 ; details' <- kc_con_details details
618 ; res' <- case res of
619 ResTyH98 -> return ResTyH98
620 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
621 ; return (con_decl { con_qvars = ex_tvs', con_cxt = ex_ctxt'
622 , con_details = details', con_res = res' }) }
624 kc_con_details (PrefixCon btys)
625 = do { btys' <- mapM kc_larg_ty btys
626 ; return (PrefixCon btys') }
627 kc_con_details (InfixCon bty1 bty2)
628 = do { bty1' <- kc_larg_ty bty1
629 ; bty2' <- kc_larg_ty bty2
630 ; return (InfixCon bty1' bty2') }
631 kc_con_details (RecCon fields)
632 = do { fields' <- mapM kc_field fields
633 ; return (RecCon fields') }
635 kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
636 ; return (ConDeclField fld bty' d) }
638 kc_larg_ty bty = case new_or_data of
639 DataType -> kcHsSigType bty
640 NewType -> kcHsLiftedSigType bty
641 -- Can't allow an unlifted type for newtypes, because we're effectively
642 -- going to remove the constructor while coercing it to a lifted type.
643 -- And newtypes can't be bang'd
644 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
646 -- Kind check a family declaration or type family default declaration.
648 kcFamilyDecl :: [LHsTyVarBndr Name] -- tyvars of enclosing class decl if any
649 -> TyClDecl Name -> TcM (TyClDecl Name)
650 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
651 = kcTyClDeclBody decl $ \tvs' ->
652 do { mapM_ unifyClassParmKinds tvs'
653 ; return (decl {tcdTyVars = tvs',
654 tcdKind = kind `mplus` Just liftedTypeKind})
655 -- default result kind is '*'
658 unifyClassParmKinds (L _ tv)
659 | (n,k) <- hsTyVarNameKind tv
660 , Just classParmKind <- lookup n classTyKinds
661 = unifyKind k classParmKind
662 | otherwise = return ()
663 classTyKinds = [hsTyVarNameKind tv | L _ tv <- classTvs]
665 kcFamilyDecl _ (TySynonym {}) -- type family defaults
666 = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
667 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
671 %************************************************************************
673 \subsection{Type checking}
675 %************************************************************************
678 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
679 tcSynDecls [] = return []
680 tcSynDecls (decl : decls)
681 = do { syn_tc <- addLocM tcSynDecl decl
682 ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
683 ; return (syn_tc : syn_tcs) }
686 tcSynDecl :: TyClDecl Name -> TcM TyThing
688 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
689 = tcTyVarBndrs tvs $ \ tvs' -> do
690 { traceTc "tcd1" (ppr tc_name)
691 ; rhs_ty' <- tcHsKindedType rhs_ty
692 ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty')
693 (typeKind rhs_ty') NoParentTyCon Nothing
694 ; return (ATyCon tycon)
696 tcSynDecl d = pprPanic "tcSynDecl" (ppr d)
699 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
701 tcTyClDecl calc_isrec decl
702 = tcAddDeclCtxt decl (tcTyClDecl1 NoParentTyCon calc_isrec decl)
704 -- "type family" declarations
705 tcTyClDecl1 :: TyConParent -> (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
706 tcTyClDecl1 parent _calc_isrec
707 (TyFamily {tcdFlavour = TypeFamily,
708 tcdLName = L _ tc_name, tcdTyVars = tvs,
709 tcdKind = Just kind}) -- NB: kind at latest added during kind checking
710 = tcTyVarBndrs tvs $ \ tvs' -> do
711 { traceTc "type family:" (ppr tc_name)
713 -- Check that we don't use families without -XTypeFamilies
714 ; idx_tys <- xoptM Opt_TypeFamilies
715 ; checkTc idx_tys $ badFamInstDecl tc_name
717 ; tycon <- buildSynTyCon tc_name tvs' SynFamilyTyCon kind parent Nothing
718 ; return [ATyCon tycon]
721 -- "data family" declaration
722 tcTyClDecl1 parent _calc_isrec
723 (TyFamily {tcdFlavour = DataFamily,
724 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
725 = tcTyVarBndrs tvs $ \ tvs' -> do
726 { traceTc "data family:" (ppr tc_name)
727 ; extra_tvs <- tcDataKindSig mb_kind
728 ; let final_tvs = tvs' ++ extra_tvs -- we may not need these
731 -- Check that we don't use families without -XTypeFamilies
732 ; idx_tys <- xoptM Opt_TypeFamilies
733 ; checkTc idx_tys $ badFamInstDecl tc_name
735 ; tycon <- buildAlgTyCon tc_name final_tvs []
736 DataFamilyTyCon Recursive False True
738 ; return [ATyCon tycon]
741 -- "newtype" and "data"
742 -- NB: not used for newtype/data instances (whether associated or not)
743 tcTyClDecl1 parent calc_isrec
744 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
745 tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
746 = tcTyVarBndrs tvs $ \ tvs' -> do
747 { extra_tvs <- tcDataKindSig mb_ksig
748 ; let final_tvs = tvs' ++ extra_tvs
749 ; stupid_theta <- tcHsKindedContext ctxt
750 ; want_generic <- xoptM Opt_Generics
751 ; unbox_strict <- doptM Opt_UnboxStrictFields
752 ; empty_data_decls <- xoptM Opt_EmptyDataDecls
753 ; kind_signatures <- xoptM Opt_KindSignatures
754 ; existential_ok <- xoptM Opt_ExistentialQuantification
755 ; gadt_ok <- xoptM Opt_GADTs
756 ; gadtSyntax_ok <- xoptM Opt_GADTSyntax
757 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
758 ; let ex_ok = existential_ok || gadt_ok -- Data cons can have existential context
760 -- Check that we don't use GADT syntax in H98 world
761 ; checkTc (gadtSyntax_ok || h98_syntax) (badGadtDecl tc_name)
763 -- Check that we don't use kind signatures without Glasgow extensions
764 ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
766 -- Check that the stupid theta is empty for a GADT-style declaration
767 ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
769 -- Check that a newtype has exactly one constructor
770 -- Do this before checking for empty data decls, so that
771 -- we don't suggest -XEmptyDataDecls for newtypes
772 ; checkTc (new_or_data == DataType || isSingleton cons)
773 (newtypeConError tc_name (length cons))
775 -- Check that there's at least one condecl,
776 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
777 ; checkTc (not (null cons) || empty_data_decls || is_boot)
778 (emptyConDeclsErr tc_name)
780 ; tycon <- fixM (\ tycon -> do
781 { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
782 ; data_cons <- tcConDecls unbox_strict ex_ok
783 tycon (final_tvs, res_ty) cons
785 if null cons && is_boot -- In a hs-boot file, empty cons means
786 then return AbstractTyCon -- "don't know"; hence Abstract
787 else case new_or_data of
788 DataType -> return (mkDataTyConRhs data_cons)
789 NewType -> ASSERT( not (null data_cons) )
790 mkNewTyConRhs tc_name tycon (head data_cons)
791 ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
792 (want_generic && canDoGenerics data_cons) (not h98_syntax)
795 ; return [ATyCon tycon]
798 is_rec = calc_isrec tc_name
799 h98_syntax = consUseH98Syntax cons
801 tcTyClDecl1 _parent calc_isrec
802 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
803 tcdCtxt = ctxt, tcdMeths = meths,
804 tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
805 = tcTyVarBndrs tvs $ \ tvs' -> do
806 { ctxt' <- tcHsKindedContext ctxt
807 ; fds' <- mapM (addLocM tc_fundep) fundeps
808 ; sig_stuff <- tcClassSigs class_name sigs meths
809 ; clas <- fixM $ \ clas -> do
810 { let -- This little knot is just so we can get
811 -- hold of the name of the class TyCon, which we
812 -- need to look up its recursiveness
813 tycon_name = tyConName (classTyCon clas)
814 tc_isrec = calc_isrec tycon_name
815 ; atss' <- mapM (addLocM $ tcTyClDecl1 (AssocFamilyTyCon clas) (const Recursive)) ats
816 -- NB: 'ats' only contains "type family" and "data family"
817 -- declarations as well as type family defaults
818 ; buildClass False {- Must include unfoldings for selectors -}
819 class_name tvs' ctxt' fds' (concat atss')
821 ; return (AClass clas : map ATyCon (classATs clas))
822 -- NB: Order is important due to the call to `mkGlobalThings' when
823 -- tying the the type and class declaration type checking knot.
826 tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
827 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
828 ; return (tvs1', tvs2') }
831 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
832 = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
834 tcTyClDecl1 _ _ d = pprPanic "tcTyClDecl1" (ppr d)
836 -----------------------------------
837 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
838 -> [LConDecl Name] -> TcM [DataCon]
839 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
840 = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
842 tcConDecl :: Bool -- True <=> -funbox-strict_fields
843 -> Bool -- True <=> -XExistentialQuantificaton or -XGADTs
844 -> TyCon -- Representation tycon
845 -> ([TyVar], Type) -- Return type template (with its template tyvars)
849 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl -- Data types
850 con@(ConDecl {con_name = name, con_qvars = tvs, con_cxt = ctxt
851 , con_details = details, con_res = res_ty })
852 = addErrCtxt (dataConCtxt name) $
853 tcTyVarBndrs tvs $ \ tvs' -> do
854 { ctxt' <- tcHsKindedContext ctxt
855 ; checkTc (existential_ok || conRepresentibleWithH98Syntax con)
856 (badExistential name)
857 ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
859 tc_datacon is_infix field_lbls btys
860 = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
861 ; buildDataCon (unLoc name) is_infix
863 univ_tvs ex_tvs eq_preds ctxt' arg_tys
865 -- NB: we put data_tc, the type constructor gotten from the
866 -- constructor type signature into the data constructor;
867 -- that way checkValidDataCon can complain if it's wrong.
870 PrefixCon btys -> tc_datacon False [] btys
871 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
872 RecCon fields -> tc_datacon False field_names btys
874 field_names = map (unLoc . cd_fld_name) fields
875 btys = map cd_fld_type fields
879 -- data instance T (b,c) where
880 -- TI :: forall e. e -> T (e,e)
882 -- The representation tycon looks like this:
883 -- data :R7T b c where
884 -- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
885 -- In this case orig_res_ty = T (e,e)
887 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
888 -- data instance T [a] b c = ...
889 -- gives template ([a,b,c], T [a] b c)
890 -> [TyVar] -- where MkT :: forall x y z. ...
892 -> TcM ([TyVar], -- Universal
893 [TyVar], -- Existential (distinct OccNames from univs)
894 [(TyVar,Type)], -- Equality predicates
895 Type) -- Typechecked return type
896 -- We don't check that the TyCon given in the ResTy is
897 -- the same as the parent tycon, becuase we are in the middle
898 -- of a recursive knot; so it's postponed until checkValidDataCon
900 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
901 = return (tmpl_tvs, dc_tvs, [], res_ty)
902 -- In H98 syntax the dc_tvs are the existential ones
903 -- data T a b c = forall d e. MkT ...
904 -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
906 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
907 -- E.g. data T [a] b c where
908 -- MkT :: forall x y z. T [(x,y)] z z
910 -- Univ tyvars Eq-spec
914 -- Existentials are the leftover type vars: [x,y]
915 -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
916 = do { res_ty' <- tcHsKindedType res_ty
917 ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
919 -- /Lazily/ figure out the univ_tvs etc
920 -- Each univ_tv is either a dc_tv or a tmpl_tv
921 (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
922 choose tmpl (univs, eqs)
923 | Just ty <- lookupTyVar subst tmpl
924 = case tcGetTyVar_maybe ty of
925 Just tv | not (tv `elem` univs)
927 _other -> (tmpl:univs, (tmpl,ty):eqs)
928 | otherwise = pprPanic "tcResultType" (ppr res_ty)
929 ex_tvs = dc_tvs `minusList` univ_tvs
931 ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
933 -- NB: tmpl_tvs and dc_tvs are distinct, but
934 -- we want them to be *visibly* distinct, both for
935 -- interface files and general confusion. So rename
936 -- the tc_tvs, since they are not used yet (no
937 -- consequential renaming needed)
938 (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
939 init_occ_env = initTidyOccEnv (map getOccName dc_tvs)
940 tidy_one env tv = (env', setTyVarName tv (tidyNameOcc name occ'))
943 (env', occ') = tidyOccName env (getOccName name)
945 consUseH98Syntax :: [LConDecl a] -> Bool
946 consUseH98Syntax (L _ (ConDecl { con_res = ResTyGADT _ }) : _) = False
947 consUseH98Syntax _ = True
948 -- All constructors have same shape
950 conRepresentibleWithH98Syntax :: ConDecl Name -> Bool
951 conRepresentibleWithH98Syntax
952 (ConDecl {con_qvars = tvs, con_cxt = ctxt, con_res = ResTyH98 })
953 = null tvs && null (unLoc ctxt)
954 conRepresentibleWithH98Syntax
955 (ConDecl {con_qvars = tvs, con_cxt = ctxt, con_res = ResTyGADT (L _ t) })
956 = null (unLoc ctxt) && f t (map (hsTyVarName . unLoc) tvs)
957 where -- Each type variable should be used exactly once in the
958 -- result type, and the result type must just be the type
959 -- constructor applied to type variables
960 f (HsAppTy (L _ t1) (L _ (HsTyVar v2))) vs
961 = (v2 `elem` vs) && f t1 (delete v2 vs)
962 f (HsTyVar _) [] = True
966 tcConArg :: Bool -- True <=> -funbox-strict_fields
968 -> TcM (TcType, HsBang)
969 tcConArg unbox_strict bty
970 = do { arg_ty <- tcHsBangType bty
971 ; let bang = getBangStrictness bty
972 ; let strict_mark = chooseBoxingStrategy unbox_strict arg_ty bang
973 ; return (arg_ty, strict_mark) }
975 -- We attempt to unbox/unpack a strict field when either:
976 -- (i) The field is marked '!!', or
977 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
979 -- We have turned off unboxing of newtypes because coercions make unboxing
980 -- and reboxing more complicated
981 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> HsBang
982 chooseBoxingStrategy unbox_strict_fields arg_ty bang
985 HsUnpack -> can_unbox HsUnpackFailed arg_ty
986 HsStrict | unbox_strict_fields -> can_unbox HsStrict arg_ty
987 | otherwise -> HsStrict
988 HsUnpackFailed -> pprPanic "chooseBoxingStrategy" (ppr arg_ty)
989 -- Source code never has shtes
991 can_unbox :: HsBang -> TcType -> HsBang
992 -- Returns HsUnpack if we can unpack arg_ty
993 -- fail_bang if we know what arg_ty is but we can't unpack it
994 -- HsStrict if it's abstract, so we don't know whether or not we can unbox it
995 can_unbox fail_bang arg_ty
996 = case splitTyConApp_maybe arg_ty of
999 Just (arg_tycon, tycon_args)
1000 | isAbstractTyCon arg_tycon -> HsStrict
1001 -- See Note [Don't complain about UNPACK on abstract TyCons]
1002 | not (isRecursiveTyCon arg_tycon) -- Note [Recusive unboxing]
1003 , isProductTyCon arg_tycon
1004 -- We can unbox if the type is a chain of newtypes
1005 -- with a product tycon at the end
1006 -> if isNewTyCon arg_tycon
1007 then can_unbox fail_bang (newTyConInstRhs arg_tycon tycon_args)
1010 | otherwise -> fail_bang
1013 Note [Don't complain about UNPACK on abstract TyCons]
1014 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1015 We are going to complain about UnpackFailed, but if we say
1016 data T = MkT {-# UNPACK #-} !Wobble
1017 and Wobble is a newtype imported from a module that was compiled
1018 without optimisation, we don't want to complain. Because it might
1019 be fine when optimsation is on. I think this happens when Haddock
1020 is working over (say) GHC souce files.
1022 Note [Recursive unboxing]
1023 ~~~~~~~~~~~~~~~~~~~~~~~~~
1024 Be careful not to try to unbox this!
1026 But it's the *argument* type that matters. This is fine:
1028 because Int is non-recursive.
1031 %************************************************************************
1035 %************************************************************************
1037 Validity checking is done once the mutually-recursive knot has been
1038 tied, so we can look at things freely.
1041 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
1042 checkCycleErrs tyclss
1046 = do { mapM_ recClsErr cls_cycles
1047 ; failM } -- Give up now, because later checkValidTyCl
1048 -- will loop if the synonym is recursive
1050 cls_cycles = calcClassCycles tyclss
1052 checkValidTyCl :: TyClDecl Name -> TcM ()
1053 -- We do the validity check over declarations, rather than TyThings
1054 -- only so that we can add a nice context with tcAddDeclCtxt
1056 = tcAddDeclCtxt decl $
1057 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
1058 ; traceTc "Validity of" (ppr thing)
1060 ATyCon tc -> checkValidTyCon tc
1061 AClass cl -> checkValidClass cl
1062 _ -> panic "checkValidTyCl"
1063 ; traceTc "Done validity of" (ppr thing)
1066 -------------------------
1067 -- For data types declared with record syntax, we require
1068 -- that each constructor that has a field 'f'
1069 -- (a) has the same result type
1070 -- (b) has the same type for 'f'
1071 -- module alpha conversion of the quantified type variables
1072 -- of the constructor.
1074 -- Note that we allow existentials to match becuase the
1075 -- fields can never meet. E.g
1077 -- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
1078 -- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
1079 -- Here we do not complain about f1,f2 because they are existential
1081 checkValidTyCon :: TyCon -> TcM ()
1084 = case synTyConRhs tc of
1085 SynFamilyTyCon {} -> return ()
1086 SynonymTyCon ty -> checkValidType syn_ctxt ty
1088 = do -- Check the context on the data decl
1089 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1091 -- Check arg types of data constructors
1092 mapM_ (checkValidDataCon tc) data_cons
1094 -- Check that fields with the same name share a type
1095 mapM_ check_fields groups
1098 syn_ctxt = TySynCtxt name
1100 data_cons = tyConDataCons tc
1102 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1103 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1104 get_fields con = dataConFieldLabels con `zip` repeat con
1105 -- dataConFieldLabels may return the empty list, which is fine
1107 -- See Note [GADT record selectors] in MkId.lhs
1108 -- We must check (a) that the named field has the same
1109 -- type in each constructor
1110 -- (b) that those constructors have the same result type
1112 -- However, the constructors may have differently named type variable
1113 -- and (worse) we don't know how the correspond to each other. E.g.
1114 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
1115 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
1117 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1118 -- result type against other candidates' types BOTH WAYS ROUND.
1119 -- If they magically agrees, take the substitution and
1120 -- apply them to the latter ones, and see if they match perfectly.
1121 check_fields ((label, con1) : other_fields)
1122 -- These fields all have the same name, but are from
1123 -- different constructors in the data type
1124 = recoverM (return ()) $ mapM_ checkOne other_fields
1125 -- Check that all the fields in the group have the same type
1126 -- NB: this check assumes that all the constructors of a given
1127 -- data type use the same type variables
1129 (tvs1, _, _, res1) = dataConSig con1
1131 fty1 = dataConFieldType con1 label
1133 checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
1134 = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1135 ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1137 (tvs2, _, _, res2) = dataConSig con2
1139 fty2 = dataConFieldType con2 label
1140 check_fields [] = panic "checkValidTyCon/check_fields []"
1142 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1143 -> Type -> Type -> Type -> Type -> TcM ()
1144 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1145 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1146 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1148 mb_subst1 = tcMatchTy tvs1 res1 res2
1149 mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1151 -------------------------------
1152 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1153 checkValidDataCon tc con
1154 = setSrcSpan (srcLocSpan (getSrcLoc con)) $
1155 addErrCtxt (dataConCtxt con) $
1156 do { traceTc "Validity of data con" (ppr con)
1157 ; let tc_tvs = tyConTyVars tc
1158 res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1159 actual_res_ty = dataConOrigResTy con
1160 ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1163 (badDataConTyCon con res_ty_tmpl actual_res_ty)
1164 ; checkValidMonoType (dataConOrigResTy con)
1165 -- Disallow MkT :: T (forall a. a->a)
1166 -- Reason: it's really the argument of an equality constraint
1167 ; checkValidType ctxt (dataConUserType con)
1168 ; when (isNewTyCon tc) (checkNewDataCon con)
1169 ; mapM_ check_bang (dataConStrictMarks con `zip` [1..])
1172 ctxt = ConArgCtxt (dataConName con)
1173 check_bang (HsUnpackFailed, n) = addWarnTc (cant_unbox_msg n)
1174 check_bang _ = return ()
1176 cant_unbox_msg n = sep [ ptext (sLit "Ignoring unusable UNPACK pragma on the")
1177 , speakNth n <+> ptext (sLit "argument of") <+> quotes (ppr con)]
1179 -------------------------------
1180 checkNewDataCon :: DataCon -> TcM ()
1181 -- Checks for the data constructor of a newtype
1183 = do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1185 ; checkTc (null eq_spec) (newtypePredError con)
1186 -- Return type is (T a b c)
1187 ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1189 ; checkTc (not (any isBanged (dataConStrictMarks con)))
1190 (newtypeStrictError con)
1194 (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1196 -------------------------------
1197 checkValidClass :: Class -> TcM ()
1199 = do { constrained_class_methods <- xoptM Opt_ConstrainedClassMethods
1200 ; multi_param_type_classes <- xoptM Opt_MultiParamTypeClasses
1201 ; fundep_classes <- xoptM Opt_FunctionalDependencies
1203 -- Check that the class is unary, unless GlaExs
1204 ; checkTc (notNull tyvars) (nullaryClassErr cls)
1205 ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1206 ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1208 -- Check the super-classes
1209 ; checkValidTheta (ClassSCCtxt (className cls)) theta
1211 -- Check the class operations
1212 ; mapM_ (check_op constrained_class_methods) op_stuff
1214 -- Check that if the class has generic methods, then the
1215 -- class has only one parameter. We can't do generic
1216 -- multi-parameter type classes!
1217 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1220 (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1221 unary = isSingleton tyvars
1222 no_generics = null [() | (_, GenDefMeth) <- op_stuff]
1224 check_op constrained_class_methods (sel_id, dm)
1225 = addErrCtxt (classOpCtxt sel_id tau) $ do
1226 { checkValidTheta SigmaCtxt (tail theta)
1227 -- The 'tail' removes the initial (C a) from the
1228 -- class itself, leaving just the method type
1230 ; traceTc "class op type" (ppr op_ty <+> ppr tau)
1231 ; checkValidType (FunSigCtxt op_name) tau
1233 -- Check that the type mentions at least one of
1234 -- the class type variables...or at least one reachable
1235 -- from one of the class variables. Example: tc223
1236 -- class Error e => Game b mv e | b -> mv e where
1237 -- newBoard :: MonadState b m => m ()
1238 -- Here, MonadState has a fundep m->b, so newBoard is fine
1239 ; let grown_tyvars = growThetaTyVars theta (mkVarSet tyvars)
1240 ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1241 (noClassTyVarErr cls sel_id)
1243 -- Check that for a generic method, the type of
1244 -- the method is sufficiently simple
1245 ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1246 (badGenericMethodType op_name op_ty)
1249 op_name = idName sel_id
1250 op_ty = idType sel_id
1251 (_,theta1,tau1) = tcSplitSigmaTy op_ty
1252 (_,theta2,tau2) = tcSplitSigmaTy tau1
1253 (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1254 | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1255 -- Ugh! The function might have a type like
1256 -- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1257 -- With -XConstrainedClassMethods, we want to allow this, even though the inner
1258 -- forall has an (Eq a) constraint. Whereas in general, each constraint
1259 -- in the context of a for-all must mention at least one quantified
1260 -- type variable. What a mess!
1264 %************************************************************************
1266 Building record selectors
1268 %************************************************************************
1271 mkDefaultMethodIds :: [TyThing] -> [Id]
1272 -- See Note [Default method Ids and Template Haskell]
1273 mkDefaultMethodIds things
1274 = [ mkDefaultMethodId sel_id dm_name
1275 | AClass cls <- things
1276 , (sel_id, DefMeth dm_name) <- classOpItems cls ]
1279 Note [Default method Ids and Template Haskell]
1280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1281 Consider this (Trac #4169):
1282 class Numeric a where
1284 fromIntegerNum = ...
1287 ast = [d| instance Numeric Int |]
1289 When we typecheck 'ast' we have done the first pass over the class decl
1290 (in tcTyClDecls), but we have not yet typechecked the default-method
1291 declarations (becuase they can mention value declarations). So we
1292 must bring the default method Ids into scope first (so they can be seen
1293 when typechecking the [d| .. |] quote, and typecheck them later.
1296 mkRecSelBinds :: [TyThing] -> HsValBinds Name
1297 -- NB We produce *un-typechecked* bindings, rather like 'deriving'
1298 -- This makes life easier, because the later type checking will add
1299 -- all necessary type abstractions and applications
1300 mkRecSelBinds ty_things
1301 = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1303 (sigs, binds) = unzip rec_sels
1304 rec_sels = map mkRecSelBind [ (tc,fld)
1305 | ATyCon tc <- ty_things
1306 , fld <- tyConFields tc ]
1308 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1309 mkRecSelBind (tycon, sel_name)
1310 = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1312 loc = getSrcSpan tycon
1313 sel_id = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1314 rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1316 -- Find a representative constructor, con1
1317 all_cons = tyConDataCons tycon
1318 cons_w_field = [ con | con <- all_cons
1319 , sel_name `elem` dataConFieldLabels con ]
1320 con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1322 -- Selector type; Note [Polymorphic selectors]
1323 field_ty = dataConFieldType con1 sel_name
1324 data_ty = dataConOrigResTy con1
1325 data_tvs = tyVarsOfType data_ty
1326 is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)
1327 (field_tvs, field_theta, field_tau) = tcSplitSigmaTy field_ty
1328 sel_ty | is_naughty = unitTy -- See Note [Naughty record selectors]
1329 | otherwise = mkForAllTys (varSetElems data_tvs ++ field_tvs) $
1330 mkPhiTy (dataConStupidTheta con1) $ -- Urgh!
1331 mkPhiTy field_theta $ -- Urgh!
1332 mkFunTy data_ty field_tau
1334 -- Make the binding: sel (C2 { fld = x }) = x
1335 -- sel (C7 { fld = x }) = x
1336 -- where cons_w_field = [C2,C7]
1337 sel_bind | is_naughty = mkFunBind sel_lname [mkSimpleMatch [] unit_rhs]
1338 | otherwise = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1339 mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)]
1340 (L loc (HsVar field_var))
1341 mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1342 rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1343 rec_field = HsRecField { hsRecFieldId = sel_lname
1344 , hsRecFieldArg = nlVarPat field_var
1345 , hsRecPun = False }
1346 sel_lname = L loc sel_name
1347 field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1349 -- Add catch-all default case unless the case is exhaustive
1350 -- We do this explicitly so that we get a nice error message that
1351 -- mentions this particular record selector
1352 deflt | not (any is_unused all_cons) = []
1353 | otherwise = [mkSimpleMatch [nlWildPat]
1354 (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1357 -- Do not add a default case unless there are unmatched
1358 -- constructors. We must take account of GADTs, else we
1359 -- get overlap warning messages from the pattern-match checker
1360 is_unused con = not (con `elem` cons_w_field
1361 || dataConCannotMatch inst_tys con)
1362 inst_tys = tyConAppArgs data_ty
1364 unit_rhs = mkLHsTupleExpr []
1365 msg_lit = HsStringPrim $ mkFastString $
1366 occNameString (getOccName sel_name)
1369 tyConFields :: TyCon -> [FieldLabel]
1371 | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1375 Note [Polymorphic selectors]
1376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1377 When a record has a polymorphic field, we pull the foralls out to the front.
1378 data T = MkT { f :: forall a. [a] -> a }
1379 Then f :: forall a. T -> [a] -> a
1380 NOT f :: T -> forall a. [a] -> a
1382 This is horrid. It's only needed in deeply obscure cases, which I hate.
1383 The only case I know is test tc163, which is worth looking at. It's far
1384 from clear that this test should succeed at all!
1386 Note [Naughty record selectors]
1387 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1388 A "naughty" field is one for which we can't define a record
1389 selector, because an existential type variable would escape. For example:
1390 data T = forall a. MkT { x,y::a }
1391 We obviously can't define
1393 Nevertheless we *do* put a RecSelId into the type environment
1394 so that if the user tries to use 'x' as a selector we can bleat
1395 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1396 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1398 In general, a field is "naughty" if its type mentions a type variable that
1399 isn't in the result type of the constructor. Note that this *allows*
1400 GADT record selectors (Note [GADT record selectors]) whose types may look
1401 like sel :: T [a] -> a
1403 For naughty selectors we make a dummy binding
1405 for naughty selectors, so that the later type-check will add them to the
1406 environment, and they'll be exported. The function is never called, because
1407 the tyepchecker spots the sel_naughty field.
1409 Note [GADT record selectors]
1410 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1411 For GADTs, we require that all constructors with a common field 'f' have the same
1412 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
1415 T1 { f :: Maybe a } :: T [a]
1416 T2 { f :: Maybe a, y :: b } :: T [a]
1418 and now the selector takes that result type as its argument:
1419 f :: forall a. T [a] -> Maybe a
1421 Details: the "real" types of T1,T2 are:
1422 T1 :: forall r a. (r~[a]) => a -> T r
1423 T2 :: forall r a b. (r~[a]) => a -> b -> T r
1425 So the selector loooks like this:
1426 f :: forall a. T [a] -> Maybe a
1429 T1 c (g:[a]~[c]) (v:Maybe c) -> v `cast` Maybe (right (sym g))
1430 T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1432 Note the forall'd tyvars of the selector are just the free tyvars
1433 of the result type; there may be other tyvars in the constructor's
1434 type (e.g. 'b' in T2).
1436 Note the need for casts in the result!
1438 Note [Selector running example]
1439 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1440 It's OK to combine GADTs and type families. Here's a running example:
1442 data instance T [a] where
1443 T1 { fld :: b } :: T [Maybe b]
1445 The representation type looks like this
1447 T1 { fld :: b } :: :R7T (Maybe b)
1449 and there's coercion from the family type to the representation type
1450 :CoR7T a :: T [a] ~ :R7T a
1452 The selector we want for fld looks like this:
1454 fld :: forall b. T [Maybe b] -> b
1455 fld = /\b. \(d::T [Maybe b]).
1456 case d `cast` :CoR7T (Maybe b) of
1459 The scrutinee of the case has type :R7T (Maybe b), which can be
1460 gotten by appying the eq_spec to the univ_tvs of the data con.
1462 %************************************************************************
1466 %************************************************************************
1469 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1470 resultTypeMisMatch field_name con1 con2
1471 = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1472 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1473 nest 2 $ ptext (sLit "but have different result types")]
1475 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1476 fieldTypeMisMatch field_name con1 con2
1477 = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1478 ptext (sLit "give different types for field"), quotes (ppr field_name)]
1480 dataConCtxt :: Outputable a => a -> SDoc
1481 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1483 classOpCtxt :: Var -> Type -> SDoc
1484 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1485 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1487 nullaryClassErr :: Class -> SDoc
1489 = ptext (sLit "No parameters for class") <+> quotes (ppr cls)
1491 classArityErr :: Class -> SDoc
1493 = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1494 parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1496 classFunDepsErr :: Class -> SDoc
1498 = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1499 parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1501 noClassTyVarErr :: Class -> Var -> SDoc
1502 noClassTyVarErr clas op
1503 = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1504 ptext (sLit "mentions none of the type variables of the class") <+>
1505 ppr clas <+> hsep (map ppr (classTyVars clas))]
1507 genericMultiParamErr :: Class -> SDoc
1508 genericMultiParamErr clas
1509 = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+>
1510 ptext (sLit "cannot have generic methods")
1512 badGenericMethodType :: Name -> Kind -> SDoc
1513 badGenericMethodType op op_ty
1514 = hang (ptext (sLit "Generic method type is too complex"))
1515 2 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1516 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1518 recSynErr :: [LTyClDecl Name] -> TcRn ()
1520 = setSrcSpan (getLoc (head sorted_decls)) $
1521 addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1522 nest 2 (vcat (map ppr_decl sorted_decls))])
1524 sorted_decls = sortLocated syn_decls
1525 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1527 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1529 = setSrcSpan (getLoc (head sorted_decls)) $
1530 addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1531 nest 2 (vcat (map ppr_decl sorted_decls))])
1533 sorted_decls = sortLocated cls_decls
1534 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1536 sortLocated :: [Located a] -> [Located a]
1537 sortLocated things = sortLe le things
1539 le (L l1 _) (L l2 _) = l1 <= l2
1541 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1542 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1543 = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1544 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1545 2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1547 badGadtDecl :: Name -> SDoc
1549 = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1550 , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1552 badExistential :: Located Name -> SDoc
1553 badExistential con_name
1554 = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1555 ptext (sLit "has existential type variables, a context, or a specialised result type"))
1556 2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1558 badStupidTheta :: Name -> SDoc
1559 badStupidTheta tc_name
1560 = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1562 newtypeConError :: Name -> Int -> SDoc
1563 newtypeConError tycon n
1564 = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1565 nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1567 newtypeExError :: DataCon -> SDoc
1569 = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1570 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1572 newtypeStrictError :: DataCon -> SDoc
1573 newtypeStrictError con
1574 = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1575 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1577 newtypePredError :: DataCon -> SDoc
1578 newtypePredError con
1579 = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1580 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1582 newtypeFieldErr :: DataCon -> Int -> SDoc
1583 newtypeFieldErr con_name n_flds
1584 = sep [ptext (sLit "The constructor of a newtype must have exactly one field"),
1585 nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1587 badSigTyDecl :: Name -> SDoc
1588 badSigTyDecl tc_name
1589 = vcat [ ptext (sLit "Illegal kind signature") <+>
1590 quotes (ppr tc_name)
1591 , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1593 badFamInstDecl :: Outputable a => a -> SDoc
1594 badFamInstDecl tc_name
1595 = vcat [ ptext (sLit "Illegal family instance for") <+>
1596 quotes (ppr tc_name)
1597 , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1599 tooManyParmsErr :: Located Name -> SDoc
1600 tooManyParmsErr tc_name
1601 = ptext (sLit "Family instance has too many parameters:") <+>
1602 quotes (ppr tc_name)
1604 tooFewParmsErr :: Arity -> SDoc
1605 tooFewParmsErr arity
1606 = ptext (sLit "Family instance has too few parameters; expected") <+>
1609 wrongNumberOfParmsErr :: Arity -> SDoc
1610 wrongNumberOfParmsErr exp_arity
1611 = ptext (sLit "Number of parameters must match family declaration; expected")
1614 badBootFamInstDeclErr :: SDoc
1615 badBootFamInstDeclErr
1616 = ptext (sLit "Illegal family instance in hs-boot file")
1618 notFamily :: TyCon -> SDoc
1620 = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1621 , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1623 wrongKindOfFamily :: TyCon -> SDoc
1624 wrongKindOfFamily family
1625 = ptext (sLit "Wrong category of family instance; declaration was for a")
1628 kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1629 | isAlgTyCon family = ptext (sLit "data type")
1630 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1632 emptyConDeclsErr :: Name -> SDoc
1633 emptyConDeclsErr tycon
1634 = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1635 nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]