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