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 MkCore ( rEC_SEL_ERROR_ID )
47 import Unique ( mkBuiltinUnique )
56 %************************************************************************
58 \subsection{Type checking for type and class declarations}
60 %************************************************************************
64 tcTyAndClassDecls :: ModDetails
65 -> [[LTyClDecl Name]] -- Mutually-recursive groups in dependency order
66 -> TcM (TcGblEnv, -- Input env extended by types and classes
67 -- and their implicit Ids,DataCons
68 HsValBinds Name, -- Renamed bindings for record selectors
69 [Id], -- Default method ids
70 [LTyClDecl Name]) -- Kind-checked declarations
71 -- Fails if there are any errors
73 tcTyAndClassDecls boot_details decls_s
74 = checkNoErrs $ -- The code recovers internally, but if anything gave rise to
75 -- an error we'd better stop now, to avoid a cascade
76 do { let tyclds_s = map (filterOut (isFamInstDecl . unLoc)) decls_s
77 -- Remove family instance decls altogether
78 -- They are dealt with by TcInstDcls
80 ; tyclss <- fixM $ \ rec_tyclss ->
81 tcExtendRecEnv (zipRecTyClss tyclds_s rec_tyclss) $
82 -- We must populate the environment with the loop-tied
83 -- T's right away (even before kind checking), because
84 -- the kind checker may "fault in" some type constructors
85 -- that recursively mention T
87 do { -- Kind-check in dependency order
88 -- See Note [Kind checking for type and class decls]
89 kc_decls <- kcTyClDecls tyclds_s
91 -- And now build the TyCons/Classes
92 ; let rec_flags = calcRecFlags boot_details rec_tyclss
93 ; concatMapM (tcTyClDecl rec_flags) kc_decls }
95 ; tcExtendGlobalEnv tyclss $ do
96 { -- Perform the validity check
97 -- We can do this now because we are done with the recursive knot
98 traceTc "ready for validity check" empty
99 ; mapM_ (addLocM checkValidTyCl) (concat tyclds_s)
100 ; traceTc "done" empty
102 -- Add the implicit things;
103 -- we want them in the environment because
104 -- they may be mentioned in interface files
105 -- NB: All associated types and their implicit things will be added a
106 -- second time here. This doesn't matter as the definitions are
108 ; let { implicit_things = concatMap implicitTyThings tyclss
109 ; rec_sel_binds = mkRecSelBinds tyclss
110 ; dm_ids = mkDefaultMethodIds tyclss }
112 ; env <- tcExtendGlobalEnv implicit_things getGblEnv
113 -- We need the kind-checked declarations later, so we return them
115 ; kc_decls <- kcTyClDecls tyclds_s
116 ; return (env, rec_sel_binds, dm_ids, kc_decls) } }
118 zipRecTyClss :: [[LTyClDecl Name]]
119 -> [TyThing] -- Knot-tied
121 -- Build a name-TyThing mapping for the things bound by decls
122 -- being careful not to look at the [TyThing]
123 -- The TyThings in the result list must have a visible ATyCon/AClass,
124 -- because typechecking types (in, say, tcTyClDecl) looks at this outer constructor
125 zipRecTyClss decls_s rec_things
126 = [ get decl | decls <- decls_s, L _ decl <- flattenATs decls ]
128 rec_type_env :: TypeEnv
129 rec_type_env = mkTypeEnv rec_things
131 get :: TyClDecl Name -> (Name, TyThing)
132 get (ClassDecl {tcdLName = L _ name}) = (name, AClass cl)
134 Just (AClass cl) = lookupTypeEnv rec_type_env name
135 get decl = (name, ATyCon tc)
138 Just (ATyCon tc) = lookupTypeEnv rec_type_env name
142 %************************************************************************
144 Type checking family instances
146 %************************************************************************
148 Family instances are somewhat of a hybrid. They are processed together with
149 class instance heads, but can contain data constructors and hence they share a
150 lot of kinding and type checking code with ordinary algebraic data types (and
154 tcFamInstDecl :: TopLevelFlag -> LTyClDecl Name -> TcM TyThing
155 tcFamInstDecl top_lvl (L loc decl)
156 = -- Prime error recovery, set source location
159 do { -- type family instances require -XTypeFamilies
160 -- and can't (currently) be in an hs-boot file
161 ; type_families <- xoptM Opt_TypeFamilies
162 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
163 ; checkTc type_families $ badFamInstDecl (tcdLName decl)
164 ; checkTc (not is_boot) $ badBootFamInstDeclErr
166 -- Perform kind and type checking
167 ; tc <- tcFamInstDecl1 decl
168 ; checkValidTyCon tc -- Remember to check validity;
169 -- no recursion to worry about here
171 -- Check that toplevel type instances are not for associated types.
172 ; when (isTopLevel top_lvl && isAssocFamily tc)
173 (addErr $ assocInClassErr (tcdName decl))
175 ; return (ATyCon tc) }
177 isAssocFamily :: TyCon -> Bool -- Is an assocaited type
179 = case tyConFamInst_maybe tycon of
180 Nothing -> panic "isAssocFamily: no family?!?"
181 Just (fam, _) -> isTyConAssoc fam
183 assocInClassErr :: Name -> SDoc
185 = ptext (sLit "Associated type") <+> quotes (ppr name) <+>
186 ptext (sLit "must be inside a class instance")
190 tcFamInstDecl1 :: TyClDecl Name -> TcM TyCon
193 tcFamInstDecl1 (decl@TySynonym {tcdLName = L loc tc_name})
194 = kcIdxTyPats decl $ \k_tvs k_typats resKind family ->
195 do { -- check that the family declaration is for a synonym
196 checkTc (isFamilyTyCon family) (notFamily family)
197 ; checkTc (isSynTyCon family) (wrongKindOfFamily family)
199 ; -- (1) kind check the right-hand side of the type equation
200 ; k_rhs <- kcCheckLHsType (tcdSynRhs decl) (EK resKind EkUnk)
201 -- ToDo: the ExpKind could be better
203 -- we need the exact same number of type parameters as the family
205 ; let famArity = tyConArity family
206 ; checkTc (length k_typats == famArity) $
207 wrongNumberOfParmsErr famArity
209 -- (2) type check type equation
210 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
211 ; t_typats <- mapM tcHsKindedType k_typats
212 ; t_rhs <- tcHsKindedType k_rhs
214 -- (3) check the well-formedness of the instance
215 ; checkValidTypeInst t_typats t_rhs
217 -- (4) construct representation tycon
218 ; rep_tc_name <- newFamInstTyConName tc_name t_typats loc
219 ; buildSynTyCon rep_tc_name t_tvs (SynonymTyCon t_rhs)
221 NoParentTyCon (Just (family, t_typats))
224 -- "newtype instance" and "data instance"
225 tcFamInstDecl1 (decl@TyData {tcdND = new_or_data, tcdLName = L loc tc_name,
227 = kcIdxTyPats decl $ \k_tvs k_typats resKind fam_tycon ->
228 do { -- check that the family declaration is for the right kind
229 checkTc (isFamilyTyCon fam_tycon) (notFamily fam_tycon)
230 ; checkTc (isAlgTyCon fam_tycon) (wrongKindOfFamily fam_tycon)
232 ; -- (1) kind check the data declaration as usual
233 ; k_decl <- kcDataDecl decl k_tvs
234 ; let k_ctxt = tcdCtxt k_decl
235 k_cons = tcdCons k_decl
237 -- result kind must be '*' (otherwise, we have too few patterns)
238 ; checkTc (isLiftedTypeKind resKind) $ tooFewParmsErr (tyConArity fam_tycon)
240 -- (2) type check indexed data type declaration
241 ; tcTyVarBndrs k_tvs $ \t_tvs -> do { -- turn kinded into proper tyvars
242 ; unbox_strict <- doptM Opt_UnboxStrictFields
244 -- kind check the type indexes and the context
245 ; t_typats <- mapM tcHsKindedType k_typats
246 ; stupid_theta <- tcHsKindedContext k_ctxt
249 -- (a) left-hand side contains no type family applications
250 -- (vanilla synonyms are fine, though, and we checked for
252 ; mapM_ checkTyFamFreeness t_typats
254 -- Check that we don't use GADT syntax in H98 world
255 ; gadt_ok <- xoptM Opt_GADTs
256 ; checkTc (gadt_ok || consUseH98Syntax cons) (badGadtDecl tc_name)
258 -- (b) a newtype has exactly one constructor
259 ; checkTc (new_or_data == DataType || isSingleton k_cons) $
260 newtypeConError tc_name (length k_cons)
262 -- (4) construct representation tycon
263 ; rep_tc_name <- newFamInstTyConName tc_name t_typats loc
264 ; let ex_ok = True -- Existentials ok for type families!
265 ; fixM (\ rep_tycon -> do
266 { let orig_res_ty = mkTyConApp fam_tycon t_typats
267 ; data_cons <- tcConDecls unbox_strict ex_ok rep_tycon
268 (t_tvs, orig_res_ty) k_cons
271 DataType -> return (mkDataTyConRhs data_cons)
272 NewType -> ASSERT( not (null data_cons) )
273 mkNewTyConRhs rep_tc_name rep_tycon (head data_cons)
274 ; buildAlgTyCon rep_tc_name t_tvs stupid_theta tc_rhs Recursive
275 False h98_syntax NoParentTyCon (Just (fam_tycon, t_typats))
276 -- We always assume that indexed types are recursive. Why?
277 -- (1) Due to their open nature, we can never be sure that a
278 -- further instance might not introduce a new recursive
279 -- dependency. (2) They are always valid loop breakers as
280 -- they involve a coercion.
284 h98_syntax = case cons of -- All constructors have same shape
285 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
288 tcFamInstDecl1 d = pprPanic "tcFamInstDecl1" (ppr d)
290 -- Kind checking of indexed types
293 -- Kind check type patterns and kind annotate the embedded type variables.
295 -- * Here we check that a type instance matches its kind signature, but we do
296 -- not check whether there is a pattern for each type index; the latter
297 -- check is only required for type synonym instances.
299 kcIdxTyPats :: TyClDecl Name
300 -> ([LHsTyVarBndr Name] -> [LHsType Name] -> Kind -> TyCon -> TcM a)
301 -- ^^kinded tvs ^^kinded ty pats ^^res kind
303 kcIdxTyPats decl thing_inside
304 = kcHsTyVars (tcdTyVars decl) $ \tvs ->
305 do { let tc_name = tcdLName decl
306 ; fam_tycon <- tcLookupLocatedTyCon tc_name
307 ; let { (kinds, resKind) = splitKindFunTys (tyConKind fam_tycon)
308 ; hs_typats = fromJust $ tcdTyPats decl }
310 -- we may not have more parameters than the kind indicates
311 ; checkTc (length kinds >= length hs_typats) $
312 tooManyParmsErr (tcdLName decl)
314 -- type functions can have a higher-kinded result
315 ; let resultKind = mkArrowKinds (drop (length hs_typats) kinds) resKind
316 ; typats <- zipWithM kcCheckLHsType hs_typats
317 [ EK kind (EkArg (ppr tc_name) n)
318 | (kind,n) <- kinds `zip` [1..]]
319 ; thing_inside tvs typats resultKind fam_tycon
324 %************************************************************************
328 %************************************************************************
330 Note [Kind checking for type and class decls]
331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
332 Kind checking is done thus:
334 1. Make up a kind variable for each parameter of the *data* type,
335 and class, decls, and extend the kind environment (which is in
338 2. Dependency-analyse the type *synonyms* (which must be non-recursive),
339 and kind-check them in dependency order. Extend the kind envt.
341 3. Kind check the data type and class decls
343 Synonyms are treated differently to data type and classes,
344 because a type synonym can be an unboxed type
346 and a kind variable can't unify with UnboxedTypeKind
347 So we infer their kinds in dependency order
349 We need to kind check all types in the mutually recursive group
350 before we know the kind of the type variables. For example:
353 op :: D b => a -> b -> b
356 bop :: (Monad c) => ...
358 Here, the kind of the locally-polymorphic type variable "b"
359 depends on *all the uses of class D*. For example, the use of
360 Monad c in bop's type signature means that D must have kind Type->Type.
362 However type synonyms work differently. They can have kinds which don't
363 just involve (->) and *:
364 type R = Int# -- Kind #
365 type S a = Array# a -- Kind * -> #
366 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
367 So we must infer their kinds from their right-hand sides *first* and then
368 use them, whereas for the mutually recursive data types D we bring into
369 scope kind bindings D -> k, where k is a kind variable, and do inference.
373 This treatment of type synonyms only applies to Haskell 98-style synonyms.
374 General type functions can be recursive, and hence, appear in `alg_decls'.
376 The kind of a type family is solely determinded by its kind signature;
377 hence, only kind signatures participate in the construction of the initial
378 kind environment (as constructed by `getInitialKind'). In fact, we ignore
379 instances of families altogether in the following. However, we need to
380 include the kinds of associated families into the construction of the
381 initial kind environment. (This is handled by `allDecls').
385 kcTyClDecls :: [[LTyClDecl Name]] -> TcM [LTyClDecl Name]
386 kcTyClDecls [] = return []
387 kcTyClDecls (decls : decls_s) = do { (tcl_env, kc_decls1) <- kcTyClDecls1 decls
388 ; kc_decls2 <- setLclEnv tcl_env (kcTyClDecls decls_s)
389 ; return (kc_decls1 ++ kc_decls2) }
391 kcTyClDecls1 :: [LTyClDecl Name] -> TcM (TcLclEnv, [LTyClDecl Name])
393 = do { -- Omit instances of type families; they are handled together
394 -- with the *heads* of class instances
395 ; let (syn_decls, alg_decls) = partition (isSynDecl . unLoc) decls
396 alg_at_decls = flattenATs alg_decls
399 ; traceTc "tcTyAndCl" (ptext (sLit "module") <+> ppr mod $$ vcat (map ppr decls))
401 -- First check for cyclic classes
402 ; checkClassCycleErrs alg_decls
404 -- Kind checking; see Note [Kind checking for type and class decls]
405 ; alg_kinds <- mapM getInitialKind alg_at_decls
406 ; tcExtendKindEnv alg_kinds $ do
408 { (kc_syn_decls, tcl_env) <- kcSynDecls (calcSynCycles syn_decls)
409 ; setLclEnv tcl_env $ do
410 { kc_alg_decls <- mapM (wrapLocM kcTyClDecl) alg_decls
412 -- Kind checking done for this group, so zonk the kind variables
413 -- See Note [Kind checking for type and class decls]
414 ; mapM_ (zonkTcKindToKind . snd) alg_kinds
416 ; return (tcl_env, kc_syn_decls ++ kc_alg_decls) } } }
418 flattenATs :: [LTyClDecl Name] -> [LTyClDecl Name]
419 flattenATs decls = concatMap flatten decls
421 flatten decl@(L _ (ClassDecl {tcdATs = ats})) = decl : ats
422 flatten decl = [decl]
424 getInitialKind :: LTyClDecl Name -> TcM (Name, TcKind)
425 -- Only for data type, class, and indexed type declarations
426 -- Get as much info as possible from the data, class, or indexed type decl,
427 -- so as to maximise usefulness of error messages
428 getInitialKind (L _ decl)
429 = do { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
430 ; res_kind <- mk_res_kind decl
431 ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
433 mk_arg_kind (UserTyVar _ _) = newKindVar
434 mk_arg_kind (KindedTyVar _ kind) = return kind
436 mk_res_kind (TyFamily { tcdKind = Just kind }) = return kind
437 mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
438 -- On GADT-style declarations we allow a kind signature
439 -- data T :: *->* where { ... }
440 mk_res_kind _ = return liftedTypeKind
444 kcSynDecls :: [SCC (LTyClDecl Name)]
445 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
446 TcLclEnv) -- Kind bindings
448 = do { tcl_env <- getLclEnv; return ([], tcl_env) }
449 kcSynDecls (group : groups)
450 = do { (decl, nk) <- kcSynDecl group
451 ; (decls, tcl_env) <- tcExtendKindEnv [nk] (kcSynDecls groups)
452 ; return (decl:decls, tcl_env) }
455 kcSynDecl :: SCC (LTyClDecl Name)
456 -> TcM (LTyClDecl Name, -- Kind-annotated decls
457 (Name,TcKind)) -- Kind bindings
458 kcSynDecl (AcyclicSCC (L loc decl))
459 = tcAddDeclCtxt decl $
460 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
461 do { traceTc "kcd1" (ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
462 <+> brackets (ppr k_tvs))
463 ; (k_rhs, rhs_kind) <- kcLHsType (tcdSynRhs decl)
464 ; traceTc "kcd2" (ppr (unLoc (tcdLName decl)))
465 ; let tc_kind = foldr (mkArrowKind . hsTyVarKind . unLoc) rhs_kind k_tvs
466 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
467 (unLoc (tcdLName decl), tc_kind)) })
469 kcSynDecl (CyclicSCC decls)
470 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
471 -- of out-of-scope tycons
473 ------------------------------------------------------------------------
474 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
475 -- Not used for type synonyms (see kcSynDecl)
477 kcTyClDecl decl@(TyData {})
478 = ASSERT( not . isFamInstDecl $ decl ) -- must not be a family instance
479 kcTyClDeclBody decl $
482 kcTyClDecl decl@(TyFamily {})
483 = kcFamilyDecl [] decl -- the empty list signals a toplevel decl
485 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs, tcdATs = ats})
486 = kcTyClDeclBody decl $ \ tvs' ->
487 do { ctxt' <- kcHsContext ctxt
488 ; ats' <- mapM (wrapLocM (kcFamilyDecl tvs')) ats
489 ; sigs' <- mapM (wrapLocM kc_sig) sigs
490 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs',
493 kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
494 ; return (TypeSig nm op_ty') }
495 kc_sig (GenericSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
496 ; return (GenericSig nm op_ty') }
497 kc_sig other_sig = return other_sig
499 kcTyClDecl decl@(ForeignType {})
502 kcTyClDecl (TySynonym {}) = panic "kcTyClDecl TySynonym"
504 kcTyClDeclBody :: TyClDecl Name
505 -> ([LHsTyVarBndr Name] -> TcM a)
507 -- getInitialKind has made a suitably-shaped kind for the type or class
508 -- Unpack it, and attribute those kinds to the type variables
509 -- Extend the env with bindings for the tyvars, taken from
510 -- the kind of the tycon/class. Give it to the thing inside, and
511 -- check the result kind matches
512 kcTyClDeclBody decl thing_inside
513 = tcAddDeclCtxt decl $
514 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
515 ; let tc_kind = case tc_ty_thing of
517 _ -> pprPanic "kcTyClDeclBody" (ppr tc_ty_thing)
518 (kinds, _) = splitKindFunTys tc_kind
519 hs_tvs = tcdTyVars decl
520 kinded_tvs = ASSERT( length kinds >= length hs_tvs )
521 zipWith add_kind hs_tvs kinds
522 ; tcExtendKindEnvTvs kinded_tvs thing_inside }
524 add_kind (L loc (UserTyVar n _)) k = L loc (UserTyVar n k)
525 add_kind (L loc (KindedTyVar n _)) k = L loc (KindedTyVar n k)
527 -- Kind check a data declaration, assuming that we already extended the
528 -- kind environment with the type variables of the left-hand side (these
529 -- kinded type variables are also passed as the second parameter).
531 kcDataDecl :: TyClDecl Name -> [LHsTyVarBndr Name] -> TcM (TyClDecl Name)
532 kcDataDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
534 = do { ctxt' <- kcHsContext ctxt
535 ; cons' <- mapM (wrapLocM kc_con_decl) cons
536 ; return (decl {tcdTyVars = tvs, tcdCtxt = ctxt', tcdCons = cons'}) }
538 -- doc comments are typechecked to Nothing here
539 kc_con_decl con_decl@(ConDecl { con_name = name, con_qvars = ex_tvs
540 , con_cxt = ex_ctxt, con_details = details, con_res = res })
541 = addErrCtxt (dataConCtxt name) $
542 kcHsTyVars ex_tvs $ \ex_tvs' -> do
543 do { ex_ctxt' <- kcHsContext ex_ctxt
544 ; details' <- kc_con_details details
545 ; res' <- case res of
546 ResTyH98 -> return ResTyH98
547 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
548 ; return (con_decl { con_qvars = ex_tvs', con_cxt = ex_ctxt'
549 , con_details = details', con_res = res' }) }
551 kc_con_details (PrefixCon btys)
552 = do { btys' <- mapM kc_larg_ty btys
553 ; return (PrefixCon btys') }
554 kc_con_details (InfixCon bty1 bty2)
555 = do { bty1' <- kc_larg_ty bty1
556 ; bty2' <- kc_larg_ty bty2
557 ; return (InfixCon bty1' bty2') }
558 kc_con_details (RecCon fields)
559 = do { fields' <- mapM kc_field fields
560 ; return (RecCon fields') }
562 kc_field (ConDeclField fld bty d) = do { bty' <- kc_larg_ty bty
563 ; return (ConDeclField fld bty' d) }
565 kc_larg_ty bty = case new_or_data of
566 DataType -> kcHsSigType bty
567 NewType -> kcHsLiftedSigType bty
568 -- Can't allow an unlifted type for newtypes, because we're effectively
569 -- going to remove the constructor while coercing it to a lifted type.
570 -- And newtypes can't be bang'd
571 kcDataDecl d _ = pprPanic "kcDataDecl" (ppr d)
573 -- Kind check a family declaration or type family default declaration.
575 kcFamilyDecl :: [LHsTyVarBndr Name] -- tyvars of enclosing class decl if any
576 -> TyClDecl Name -> TcM (TyClDecl Name)
577 kcFamilyDecl classTvs decl@(TyFamily {tcdKind = kind})
578 = kcTyClDeclBody decl $ \tvs' ->
579 do { mapM_ unifyClassParmKinds tvs'
580 ; return (decl {tcdTyVars = tvs',
581 tcdKind = kind `mplus` Just liftedTypeKind})
582 -- default result kind is '*'
585 unifyClassParmKinds (L _ tv)
586 | (n,k) <- hsTyVarNameKind tv
587 , Just classParmKind <- lookup n classTyKinds
588 = unifyKind k classParmKind
589 | otherwise = return ()
590 classTyKinds = [hsTyVarNameKind tv | L _ tv <- classTvs]
592 kcFamilyDecl _ (TySynonym {}) -- type family defaults
593 = panic "TcTyClsDecls.kcFamilyDecl: not implemented yet"
594 kcFamilyDecl _ d = pprPanic "kcFamilyDecl" (ppr d)
598 %************************************************************************
600 \subsection{Type checking}
602 %************************************************************************
605 tcTyClDecl :: (Name -> RecFlag) -> LTyClDecl Name -> TcM [TyThing]
607 tcTyClDecl calc_isrec (L loc decl)
608 = setSrcSpan loc $ tcAddDeclCtxt decl $
609 tcTyClDecl1 NoParentTyCon calc_isrec decl
611 -- "type family" declarations
612 tcTyClDecl1 :: TyConParent -> (Name -> RecFlag) -> TyClDecl Name -> TcM [TyThing]
613 tcTyClDecl1 parent _calc_isrec
614 (TyFamily {tcdFlavour = TypeFamily,
615 tcdLName = L _ tc_name, tcdTyVars = tvs,
616 tcdKind = Just kind}) -- NB: kind at latest added during kind checking
617 = tcTyVarBndrs tvs $ \ tvs' -> do
618 { traceTc "type family:" (ppr tc_name)
620 -- Check that we don't use families without -XTypeFamilies
621 ; idx_tys <- xoptM Opt_TypeFamilies
622 ; checkTc idx_tys $ badFamInstDecl tc_name
624 ; tycon <- buildSynTyCon tc_name tvs' SynFamilyTyCon kind parent Nothing
625 ; return [ATyCon tycon]
628 -- "data family" declaration
629 tcTyClDecl1 parent _calc_isrec
630 (TyFamily {tcdFlavour = DataFamily,
631 tcdLName = L _ tc_name, tcdTyVars = tvs, tcdKind = mb_kind})
632 = tcTyVarBndrs tvs $ \ tvs' -> do
633 { traceTc "data family:" (ppr tc_name)
634 ; extra_tvs <- tcDataKindSig mb_kind
635 ; let final_tvs = tvs' ++ extra_tvs -- we may not need these
638 -- Check that we don't use families without -XTypeFamilies
639 ; idx_tys <- xoptM Opt_TypeFamilies
640 ; checkTc idx_tys $ badFamInstDecl tc_name
642 ; tycon <- buildAlgTyCon tc_name final_tvs []
643 DataFamilyTyCon Recursive False True
645 ; return [ATyCon tycon]
649 tcTyClDecl1 _parent _calc_isrec
650 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
651 = ASSERT( isNoParent _parent )
652 tcTyVarBndrs tvs $ \ tvs' -> do
653 { traceTc "tcd1" (ppr tc_name)
654 ; rhs_ty' <- tcHsKindedType rhs_ty
655 ; tycon <- buildSynTyCon tc_name tvs' (SynonymTyCon rhs_ty')
656 (typeKind rhs_ty') NoParentTyCon Nothing
657 ; return [ATyCon tycon] }
659 -- "newtype" and "data"
660 -- NB: not used for newtype/data instances (whether associated or not)
661 tcTyClDecl1 _parent calc_isrec
662 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
663 tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
664 = ASSERT( isNoParent _parent )
665 tcTyVarBndrs tvs $ \ tvs' -> do
666 { extra_tvs <- tcDataKindSig mb_ksig
667 ; let final_tvs = tvs' ++ extra_tvs
668 ; stupid_theta <- tcHsKindedContext ctxt
669 ; want_generic <- xoptM Opt_Generics
670 ; unbox_strict <- doptM Opt_UnboxStrictFields
671 ; empty_data_decls <- xoptM Opt_EmptyDataDecls
672 ; kind_signatures <- xoptM Opt_KindSignatures
673 ; existential_ok <- xoptM Opt_ExistentialQuantification
674 ; gadt_ok <- xoptM Opt_GADTs
675 ; gadtSyntax_ok <- xoptM Opt_GADTSyntax
676 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
677 ; let ex_ok = existential_ok || gadt_ok -- Data cons can have existential context
679 -- Check that we don't use GADT syntax in H98 world
680 ; checkTc (gadtSyntax_ok || h98_syntax) (badGadtDecl tc_name)
682 -- Check that we don't use kind signatures without Glasgow extensions
683 ; checkTc (kind_signatures || isNothing mb_ksig) (badSigTyDecl tc_name)
685 -- Check that the stupid theta is empty for a GADT-style declaration
686 ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
688 -- Check that a newtype has exactly one constructor
689 -- Do this before checking for empty data decls, so that
690 -- we don't suggest -XEmptyDataDecls for newtypes
691 ; checkTc (new_or_data == DataType || isSingleton cons)
692 (newtypeConError tc_name (length cons))
694 -- Check that there's at least one condecl,
695 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
696 ; checkTc (not (null cons) || empty_data_decls || is_boot)
697 (emptyConDeclsErr tc_name)
699 ; tycon <- fixM (\ tycon -> do
700 { let res_ty = mkTyConApp tycon (mkTyVarTys final_tvs)
701 ; data_cons <- tcConDecls unbox_strict ex_ok
702 tycon (final_tvs, res_ty) cons
704 if null cons && is_boot -- In a hs-boot file, empty cons means
705 then return AbstractTyCon -- "don't know"; hence Abstract
706 else case new_or_data of
707 DataType -> return (mkDataTyConRhs data_cons)
708 NewType -> ASSERT( not (null data_cons) )
709 mkNewTyConRhs tc_name tycon (head data_cons)
710 ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
711 (want_generic && canDoGenerics stupid_theta data_cons) (not h98_syntax)
712 NoParentTyCon Nothing
714 ; return [ATyCon tycon]
717 is_rec = calc_isrec tc_name
718 h98_syntax = consUseH98Syntax cons
720 tcTyClDecl1 _parent calc_isrec
721 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
722 tcdCtxt = ctxt, tcdMeths = meths,
723 tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
724 = ASSERT( isNoParent _parent )
725 tcTyVarBndrs tvs $ \ tvs' -> do
726 { ctxt' <- tcHsKindedContext ctxt
727 ; fds' <- mapM (addLocM tc_fundep) fundeps
728 ; sig_stuff <- tcClassSigs class_name sigs meths
729 ; clas <- fixM $ \ clas -> do
730 { let -- This little knot is just so we can get
731 -- hold of the name of the class TyCon, which we
732 -- need to look up its recursiveness
733 tycon_name = tyConName (classTyCon clas)
734 tc_isrec = calc_isrec tycon_name
735 ; atss' <- mapM (addLocM $ tcTyClDecl1 (AssocFamilyTyCon clas) (const Recursive)) ats
736 -- NB: 'ats' only contains "type family" and "data family"
737 -- declarations as well as type family defaults
738 ; buildClass False {- Must include unfoldings for selectors -}
739 class_name tvs' ctxt' fds' (concat atss')
741 ; return (AClass clas : map ATyCon (classATs clas))
742 -- NB: Order is important due to the call to `mkGlobalThings' when
743 -- tying the the type and class declaration type checking knot.
746 tc_fundep (tvs1, tvs2) = do { tvs1' <- mapM tcLookupTyVar tvs1 ;
747 ; tvs2' <- mapM tcLookupTyVar tvs2 ;
748 ; return (tvs1', tvs2') }
751 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
752 = return [ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0)]
754 tcTyClDecl1 _ _ d = pprPanic "tcTyClDecl1" (ppr d)
756 -----------------------------------
757 tcConDecls :: Bool -> Bool -> TyCon -> ([TyVar], Type)
758 -> [LConDecl Name] -> TcM [DataCon]
759 tcConDecls unbox ex_ok rep_tycon res_tmpl cons
760 = mapM (addLocM (tcConDecl unbox ex_ok rep_tycon res_tmpl)) cons
762 tcConDecl :: Bool -- True <=> -funbox-strict_fields
763 -> Bool -- True <=> -XExistentialQuantificaton or -XGADTs
764 -> TyCon -- Representation tycon
765 -> ([TyVar], Type) -- Return type template (with its template tyvars)
769 tcConDecl unbox_strict existential_ok rep_tycon res_tmpl -- Data types
770 con@(ConDecl {con_name = name, con_qvars = tvs, con_cxt = ctxt
771 , con_details = details, con_res = res_ty })
772 = addErrCtxt (dataConCtxt name) $
773 tcTyVarBndrs tvs $ \ tvs' -> do
774 { ctxt' <- tcHsKindedContext ctxt
775 ; checkTc (existential_ok || conRepresentibleWithH98Syntax con)
776 (badExistential name)
777 ; (univ_tvs, ex_tvs, eq_preds, res_ty') <- tcResultType res_tmpl tvs' res_ty
779 tc_datacon is_infix field_lbls btys
780 = do { (arg_tys, stricts) <- mapAndUnzipM (tcConArg unbox_strict) btys
781 ; buildDataCon (unLoc name) is_infix
783 univ_tvs ex_tvs eq_preds ctxt' arg_tys
785 -- NB: we put data_tc, the type constructor gotten from the
786 -- constructor type signature into the data constructor;
787 -- that way checkValidDataCon can complain if it's wrong.
790 PrefixCon btys -> tc_datacon False [] btys
791 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
792 RecCon fields -> tc_datacon False field_names btys
794 field_names = map (unLoc . cd_fld_name) fields
795 btys = map cd_fld_type fields
799 -- data instance T (b,c) where
800 -- TI :: forall e. e -> T (e,e)
802 -- The representation tycon looks like this:
803 -- data :R7T b c where
804 -- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
805 -- In this case orig_res_ty = T (e,e)
807 tcResultType :: ([TyVar], Type) -- Template for result type; e.g.
808 -- data instance T [a] b c = ...
809 -- gives template ([a,b,c], T [a] b c)
810 -> [TyVar] -- where MkT :: forall x y z. ...
812 -> TcM ([TyVar], -- Universal
813 [TyVar], -- Existential (distinct OccNames from univs)
814 [(TyVar,Type)], -- Equality predicates
815 Type) -- Typechecked return type
816 -- We don't check that the TyCon given in the ResTy is
817 -- the same as the parent tycon, becuase we are in the middle
818 -- of a recursive knot; so it's postponed until checkValidDataCon
820 tcResultType (tmpl_tvs, res_ty) dc_tvs ResTyH98
821 = return (tmpl_tvs, dc_tvs, [], res_ty)
822 -- In H98 syntax the dc_tvs are the existential ones
823 -- data T a b c = forall d e. MkT ...
824 -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
826 tcResultType (tmpl_tvs, res_tmpl) dc_tvs (ResTyGADT res_ty)
827 -- E.g. data T [a] b c where
828 -- MkT :: forall x y z. T [(x,y)] z z
830 -- Univ tyvars Eq-spec
834 -- Existentials are the leftover type vars: [x,y]
835 -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], T [(x,y)] z z)
836 = do { res_ty' <- tcHsKindedType res_ty
837 ; let Just subst = tcMatchTy (mkVarSet tmpl_tvs) res_tmpl res_ty'
839 -- /Lazily/ figure out the univ_tvs etc
840 -- Each univ_tv is either a dc_tv or a tmpl_tv
841 (univ_tvs, eq_spec) = foldr choose ([], []) tidy_tmpl_tvs
842 choose tmpl (univs, eqs)
843 | Just ty <- lookupTyVar subst tmpl
844 = case tcGetTyVar_maybe ty of
845 Just tv | not (tv `elem` univs)
847 _other -> (tmpl:univs, (tmpl,ty):eqs)
848 | otherwise = pprPanic "tcResultType" (ppr res_ty)
849 ex_tvs = dc_tvs `minusList` univ_tvs
851 ; return (univ_tvs, ex_tvs, eq_spec, res_ty') }
853 -- NB: tmpl_tvs and dc_tvs are distinct, but
854 -- we want them to be *visibly* distinct, both for
855 -- interface files and general confusion. So rename
856 -- the tc_tvs, since they are not used yet (no
857 -- consequential renaming needed)
858 (_, tidy_tmpl_tvs) = mapAccumL tidy_one init_occ_env tmpl_tvs
859 init_occ_env = initTidyOccEnv (map getOccName dc_tvs)
860 tidy_one env tv = (env', setTyVarName tv (tidyNameOcc name occ'))
863 (env', occ') = tidyOccName env (getOccName name)
865 consUseH98Syntax :: [LConDecl a] -> Bool
866 consUseH98Syntax (L _ (ConDecl { con_res = ResTyGADT _ }) : _) = False
867 consUseH98Syntax _ = True
868 -- All constructors have same shape
870 conRepresentibleWithH98Syntax :: ConDecl Name -> Bool
871 conRepresentibleWithH98Syntax
872 (ConDecl {con_qvars = tvs, con_cxt = ctxt, con_res = ResTyH98 })
873 = null tvs && null (unLoc ctxt)
874 conRepresentibleWithH98Syntax
875 (ConDecl {con_qvars = tvs, con_cxt = ctxt, con_res = ResTyGADT (L _ t) })
876 = null (unLoc ctxt) && f t (map (hsTyVarName . unLoc) tvs)
877 where -- Each type variable should be used exactly once in the
878 -- result type, and the result type must just be the type
879 -- constructor applied to type variables
880 f (HsAppTy (L _ t1) (L _ (HsTyVar v2))) vs
881 = (v2 `elem` vs) && f t1 (delete v2 vs)
882 f (HsTyVar _) [] = True
886 tcConArg :: Bool -- True <=> -funbox-strict_fields
888 -> TcM (TcType, HsBang)
889 tcConArg unbox_strict bty
890 = do { arg_ty <- tcHsBangType bty
891 ; let bang = getBangStrictness bty
892 ; let strict_mark = chooseBoxingStrategy unbox_strict arg_ty bang
893 ; return (arg_ty, strict_mark) }
895 -- We attempt to unbox/unpack a strict field when either:
896 -- (i) The field is marked '!!', or
897 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
899 -- We have turned off unboxing of newtypes because coercions make unboxing
900 -- and reboxing more complicated
901 chooseBoxingStrategy :: Bool -> TcType -> HsBang -> HsBang
902 chooseBoxingStrategy unbox_strict_fields arg_ty bang
905 HsUnpack -> can_unbox HsUnpackFailed arg_ty
906 HsStrict | unbox_strict_fields -> can_unbox HsStrict arg_ty
907 | otherwise -> HsStrict
908 HsUnpackFailed -> pprPanic "chooseBoxingStrategy" (ppr arg_ty)
909 -- Source code never has shtes
911 can_unbox :: HsBang -> TcType -> HsBang
912 -- Returns HsUnpack if we can unpack arg_ty
913 -- fail_bang if we know what arg_ty is but we can't unpack it
914 -- HsStrict if it's abstract, so we don't know whether or not we can unbox it
915 can_unbox fail_bang arg_ty
916 = case splitTyConApp_maybe arg_ty of
919 Just (arg_tycon, tycon_args)
920 | isAbstractTyCon arg_tycon -> HsStrict
921 -- See Note [Don't complain about UNPACK on abstract TyCons]
922 | not (isRecursiveTyCon arg_tycon) -- Note [Recusive unboxing]
923 , isProductTyCon arg_tycon
924 -- We can unbox if the type is a chain of newtypes
925 -- with a product tycon at the end
926 -> if isNewTyCon arg_tycon
927 then can_unbox fail_bang (newTyConInstRhs arg_tycon tycon_args)
930 | otherwise -> fail_bang
933 Note [Don't complain about UNPACK on abstract TyCons]
934 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
935 We are going to complain about UnpackFailed, but if we say
936 data T = MkT {-# UNPACK #-} !Wobble
937 and Wobble is a newtype imported from a module that was compiled
938 without optimisation, we don't want to complain. Because it might
939 be fine when optimsation is on. I think this happens when Haddock
940 is working over (say) GHC souce files.
942 Note [Recursive unboxing]
943 ~~~~~~~~~~~~~~~~~~~~~~~~~
944 Be careful not to try to unbox this!
946 But it's the *argument* type that matters. This is fine:
948 because Int is non-recursive.
951 %************************************************************************
955 %************************************************************************
957 Validity checking is done once the mutually-recursive knot has been
958 tied, so we can look at things freely.
961 checkClassCycleErrs :: [LTyClDecl Name] -> TcM ()
962 checkClassCycleErrs tyclss
966 = do { mapM_ recClsErr cls_cycles
967 ; failM } -- Give up now, because later checkValidTyCl
968 -- will loop if the synonym is recursive
970 cls_cycles = calcClassCycles tyclss
972 checkValidTyCl :: TyClDecl Name -> TcM ()
973 -- We do the validity check over declarations, rather than TyThings
974 -- only so that we can add a nice context with tcAddDeclCtxt
976 = tcAddDeclCtxt decl $
977 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
978 ; traceTc "Validity of" (ppr thing)
980 ATyCon tc -> checkValidTyCon tc
981 AClass cl -> do { checkValidClass cl
982 ; mapM_ (addLocM checkValidTyCl) (tcdATs decl) }
983 _ -> panic "checkValidTyCl"
984 ; traceTc "Done validity of" (ppr thing)
987 -------------------------
988 -- For data types declared with record syntax, we require
989 -- that each constructor that has a field 'f'
990 -- (a) has the same result type
991 -- (b) has the same type for 'f'
992 -- module alpha conversion of the quantified type variables
993 -- of the constructor.
995 -- Note that we allow existentials to match becuase the
996 -- fields can never meet. E.g
998 -- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
999 -- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
1000 -- Here we do not complain about f1,f2 because they are existential
1002 checkValidTyCon :: TyCon -> TcM ()
1005 = case synTyConRhs tc of
1006 SynFamilyTyCon {} -> return ()
1007 SynonymTyCon ty -> checkValidType syn_ctxt ty
1009 = do -- Check the context on the data decl
1010 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc)
1012 -- Check arg types of data constructors
1013 mapM_ (checkValidDataCon tc) data_cons
1015 -- Check that fields with the same name share a type
1016 mapM_ check_fields groups
1019 syn_ctxt = TySynCtxt name
1021 data_cons = tyConDataCons tc
1023 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
1024 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
1025 get_fields con = dataConFieldLabels con `zip` repeat con
1026 -- dataConFieldLabels may return the empty list, which is fine
1028 -- See Note [GADT record selectors] in MkId.lhs
1029 -- We must check (a) that the named field has the same
1030 -- type in each constructor
1031 -- (b) that those constructors have the same result type
1033 -- However, the constructors may have differently named type variable
1034 -- and (worse) we don't know how the correspond to each other. E.g.
1035 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
1036 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
1038 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
1039 -- result type against other candidates' types BOTH WAYS ROUND.
1040 -- If they magically agrees, take the substitution and
1041 -- apply them to the latter ones, and see if they match perfectly.
1042 check_fields ((label, con1) : other_fields)
1043 -- These fields all have the same name, but are from
1044 -- different constructors in the data type
1045 = recoverM (return ()) $ mapM_ checkOne other_fields
1046 -- Check that all the fields in the group have the same type
1047 -- NB: this check assumes that all the constructors of a given
1048 -- data type use the same type variables
1050 (tvs1, _, _, res1) = dataConSig con1
1052 fty1 = dataConFieldType con1 label
1054 checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
1055 = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
1056 ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
1058 (tvs2, _, _, res2) = dataConSig con2
1060 fty2 = dataConFieldType con2 label
1061 check_fields [] = panic "checkValidTyCon/check_fields []"
1063 checkFieldCompat :: Name -> DataCon -> DataCon -> TyVarSet
1064 -> Type -> Type -> Type -> Type -> TcM ()
1065 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
1066 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
1067 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
1069 mb_subst1 = tcMatchTy tvs1 res1 res2
1070 mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
1072 -------------------------------
1073 checkValidDataCon :: TyCon -> DataCon -> TcM ()
1074 checkValidDataCon tc con
1075 = setSrcSpan (srcLocSpan (getSrcLoc con)) $
1076 addErrCtxt (dataConCtxt con) $
1077 do { traceTc "Validity of data con" (ppr con)
1078 ; let tc_tvs = tyConTyVars tc
1079 res_ty_tmpl = mkFamilyTyConApp tc (mkTyVarTys tc_tvs)
1080 actual_res_ty = dataConOrigResTy con
1081 ; checkTc (isJust (tcMatchTy (mkVarSet tc_tvs)
1084 (badDataConTyCon con res_ty_tmpl actual_res_ty)
1085 ; checkValidMonoType (dataConOrigResTy con)
1086 -- Disallow MkT :: T (forall a. a->a)
1087 -- Reason: it's really the argument of an equality constraint
1088 ; checkValidType ctxt (dataConUserType con)
1089 ; when (isNewTyCon tc) (checkNewDataCon con)
1090 ; mapM_ check_bang (dataConStrictMarks con `zip` [1..])
1093 ctxt = ConArgCtxt (dataConName con)
1094 check_bang (HsUnpackFailed, n) = addWarnTc (cant_unbox_msg n)
1095 check_bang _ = return ()
1097 cant_unbox_msg n = sep [ ptext (sLit "Ignoring unusable UNPACK pragma on the")
1098 , speakNth n <+> ptext (sLit "argument of") <+> quotes (ppr con)]
1100 -------------------------------
1101 checkNewDataCon :: DataCon -> TcM ()
1102 -- Checks for the data constructor of a newtype
1104 = do { checkTc (isSingleton arg_tys) (newtypeFieldErr con (length arg_tys))
1106 ; checkTc (null eq_spec) (newtypePredError con)
1107 -- Return type is (T a b c)
1108 ; checkTc (null ex_tvs && null eq_theta && null dict_theta) (newtypeExError con)
1110 ; checkTc (not (any isBanged (dataConStrictMarks con)))
1111 (newtypeStrictError con)
1115 (_univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, _res_ty) = dataConFullSig con
1117 -------------------------------
1118 checkValidClass :: Class -> TcM ()
1120 = do { constrained_class_methods <- xoptM Opt_ConstrainedClassMethods
1121 ; multi_param_type_classes <- xoptM Opt_MultiParamTypeClasses
1122 ; fundep_classes <- xoptM Opt_FunctionalDependencies
1124 -- Check that the class is unary, unless GlaExs
1125 ; checkTc (notNull tyvars) (nullaryClassErr cls)
1126 ; checkTc (multi_param_type_classes || unary) (classArityErr cls)
1127 ; checkTc (fundep_classes || null fundeps) (classFunDepsErr cls)
1129 -- Check the super-classes
1130 ; checkValidTheta (ClassSCCtxt (className cls)) theta
1132 -- Check the class operations
1133 ; mapM_ (check_op constrained_class_methods) op_stuff
1135 -- Check that if the class has generic methods, then the
1136 -- class has only one parameter. We can't do generic
1137 -- multi-parameter type classes!
1138 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
1141 (tyvars, fundeps, theta, _, _, op_stuff) = classExtraBigSig cls
1142 unary = isSingleton tyvars
1143 no_generics = null [() | (_, (GenDefMeth _)) <- op_stuff]
1145 check_op constrained_class_methods (sel_id, _)
1146 = addErrCtxt (classOpCtxt sel_id tau) $ do
1147 { checkValidTheta SigmaCtxt (tail theta)
1148 -- The 'tail' removes the initial (C a) from the
1149 -- class itself, leaving just the method type
1151 ; traceTc "class op type" (ppr op_ty <+> ppr tau)
1152 ; checkValidType (FunSigCtxt op_name) tau
1154 -- Check that the type mentions at least one of
1155 -- the class type variables...or at least one reachable
1156 -- from one of the class variables. Example: tc223
1157 -- class Error e => Game b mv e | b -> mv e where
1158 -- newBoard :: MonadState b m => m ()
1159 -- Here, MonadState has a fundep m->b, so newBoard is fine
1160 ; let grown_tyvars = growThetaTyVars theta (mkVarSet tyvars)
1161 ; checkTc (tyVarsOfType tau `intersectsVarSet` grown_tyvars)
1162 (noClassTyVarErr cls sel_id)
1164 -- Check that for a generic method, the type of
1165 -- the method is sufficiently simple
1166 {- -- JPM TODO (when reinstating, remove commenting-out of badGenericMethodType
1167 ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
1168 (badGenericMethodType op_name op_ty)
1172 op_name = idName sel_id
1173 op_ty = idType sel_id
1174 (_,theta1,tau1) = tcSplitSigmaTy op_ty
1175 (_,theta2,tau2) = tcSplitSigmaTy tau1
1176 (theta,tau) | constrained_class_methods = (theta1 ++ theta2, tau2)
1177 | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
1178 -- Ugh! The function might have a type like
1179 -- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
1180 -- With -XConstrainedClassMethods, we want to allow this, even though the inner
1181 -- forall has an (Eq a) constraint. Whereas in general, each constraint
1182 -- in the context of a for-all must mention at least one quantified
1183 -- type variable. What a mess!
1187 %************************************************************************
1189 Building record selectors
1191 %************************************************************************
1194 mkDefaultMethodIds :: [TyThing] -> [Id]
1195 -- See Note [Default method Ids and Template Haskell]
1196 mkDefaultMethodIds things
1197 = [ mkExportedLocalId dm_name (idType sel_id)
1198 | AClass cls <- things
1199 , (sel_id, DefMeth dm_name) <- classOpItems cls ]
1202 Note [Default method Ids and Template Haskell]
1203 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1204 Consider this (Trac #4169):
1205 class Numeric a where
1207 fromIntegerNum = ...
1210 ast = [d| instance Numeric Int |]
1212 When we typecheck 'ast' we have done the first pass over the class decl
1213 (in tcTyClDecls), but we have not yet typechecked the default-method
1214 declarations (becuase they can mention value declarations). So we
1215 must bring the default method Ids into scope first (so they can be seen
1216 when typechecking the [d| .. |] quote, and typecheck them later.
1219 mkRecSelBinds :: [TyThing] -> HsValBinds Name
1220 -- NB We produce *un-typechecked* bindings, rather like 'deriving'
1221 -- This makes life easier, because the later type checking will add
1222 -- all necessary type abstractions and applications
1223 mkRecSelBinds ty_things
1224 = ValBindsOut [(NonRecursive, b) | b <- binds] sigs
1226 (sigs, binds) = unzip rec_sels
1227 rec_sels = map mkRecSelBind [ (tc,fld)
1228 | ATyCon tc <- ty_things
1229 , fld <- tyConFields tc ]
1231 mkRecSelBind :: (TyCon, FieldLabel) -> (LSig Name, LHsBinds Name)
1232 mkRecSelBind (tycon, sel_name)
1233 = (L loc (IdSig sel_id), unitBag (L loc sel_bind))
1235 loc = getSrcSpan tycon
1236 sel_id = Var.mkLocalVar rec_details sel_name sel_ty vanillaIdInfo
1237 rec_details = RecSelId { sel_tycon = tycon, sel_naughty = is_naughty }
1239 -- Find a representative constructor, con1
1240 all_cons = tyConDataCons tycon
1241 cons_w_field = [ con | con <- all_cons
1242 , sel_name `elem` dataConFieldLabels con ]
1243 con1 = ASSERT( not (null cons_w_field) ) head cons_w_field
1245 -- Selector type; Note [Polymorphic selectors]
1246 field_ty = dataConFieldType con1 sel_name
1247 data_ty = dataConOrigResTy con1
1248 data_tvs = tyVarsOfType data_ty
1249 is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tvs)
1250 (field_tvs, field_theta, field_tau) = tcSplitSigmaTy field_ty
1251 sel_ty | is_naughty = unitTy -- See Note [Naughty record selectors]
1252 | otherwise = mkForAllTys (varSetElems data_tvs ++ field_tvs) $
1253 mkPhiTy (dataConStupidTheta con1) $ -- Urgh!
1254 mkPhiTy field_theta $ -- Urgh!
1255 mkFunTy data_ty field_tau
1257 -- Make the binding: sel (C2 { fld = x }) = x
1258 -- sel (C7 { fld = x }) = x
1259 -- where cons_w_field = [C2,C7]
1260 sel_bind | is_naughty = mkFunBind sel_lname [mkSimpleMatch [] unit_rhs]
1261 | otherwise = mkFunBind sel_lname (map mk_match cons_w_field ++ deflt)
1262 mk_match con = mkSimpleMatch [L loc (mk_sel_pat con)]
1263 (L loc (HsVar field_var))
1264 mk_sel_pat con = ConPatIn (L loc (getName con)) (RecCon rec_fields)
1265 rec_fields = HsRecFields { rec_flds = [rec_field], rec_dotdot = Nothing }
1266 rec_field = HsRecField { hsRecFieldId = sel_lname
1267 , hsRecFieldArg = nlVarPat field_var
1268 , hsRecPun = False }
1269 sel_lname = L loc sel_name
1270 field_var = mkInternalName (mkBuiltinUnique 1) (getOccName sel_name) loc
1272 -- Add catch-all default case unless the case is exhaustive
1273 -- We do this explicitly so that we get a nice error message that
1274 -- mentions this particular record selector
1275 deflt | not (any is_unused all_cons) = []
1276 | otherwise = [mkSimpleMatch [nlWildPat]
1277 (nlHsApp (nlHsVar (getName rEC_SEL_ERROR_ID))
1280 -- Do not add a default case unless there are unmatched
1281 -- constructors. We must take account of GADTs, else we
1282 -- get overlap warning messages from the pattern-match checker
1283 is_unused con = not (con `elem` cons_w_field
1284 || dataConCannotMatch inst_tys con)
1285 inst_tys = tyConAppArgs data_ty
1287 unit_rhs = mkLHsTupleExpr []
1288 msg_lit = HsStringPrim $ mkFastString $
1289 occNameString (getOccName sel_name)
1292 tyConFields :: TyCon -> [FieldLabel]
1294 | isAlgTyCon tc = nub (concatMap dataConFieldLabels (tyConDataCons tc))
1298 Note [Polymorphic selectors]
1299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1300 When a record has a polymorphic field, we pull the foralls out to the front.
1301 data T = MkT { f :: forall a. [a] -> a }
1302 Then f :: forall a. T -> [a] -> a
1303 NOT f :: T -> forall a. [a] -> a
1305 This is horrid. It's only needed in deeply obscure cases, which I hate.
1306 The only case I know is test tc163, which is worth looking at. It's far
1307 from clear that this test should succeed at all!
1309 Note [Naughty record selectors]
1310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1311 A "naughty" field is one for which we can't define a record
1312 selector, because an existential type variable would escape. For example:
1313 data T = forall a. MkT { x,y::a }
1314 We obviously can't define
1316 Nevertheless we *do* put a RecSelId into the type environment
1317 so that if the user tries to use 'x' as a selector we can bleat
1318 helpfully, rather than saying unhelpfully that 'x' is not in scope.
1319 Hence the sel_naughty flag, to identify record selectors that don't really exist.
1321 In general, a field is "naughty" if its type mentions a type variable that
1322 isn't in the result type of the constructor. Note that this *allows*
1323 GADT record selectors (Note [GADT record selectors]) whose types may look
1324 like sel :: T [a] -> a
1326 For naughty selectors we make a dummy binding
1328 for naughty selectors, so that the later type-check will add them to the
1329 environment, and they'll be exported. The function is never called, because
1330 the tyepchecker spots the sel_naughty field.
1332 Note [GADT record selectors]
1333 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1334 For GADTs, we require that all constructors with a common field 'f' have the same
1335 result type (modulo alpha conversion). [Checked in TcTyClsDecls.checkValidTyCon]
1338 T1 { f :: Maybe a } :: T [a]
1339 T2 { f :: Maybe a, y :: b } :: T [a]
1341 and now the selector takes that result type as its argument:
1342 f :: forall a. T [a] -> Maybe a
1344 Details: the "real" types of T1,T2 are:
1345 T1 :: forall r a. (r~[a]) => a -> T r
1346 T2 :: forall r a b. (r~[a]) => a -> b -> T r
1348 So the selector loooks like this:
1349 f :: forall a. T [a] -> Maybe a
1352 T1 c (g:[a]~[c]) (v:Maybe c) -> v `cast` Maybe (right (sym g))
1353 T2 c d (g:[a]~[c]) (v:Maybe c) (w:d) -> v `cast` Maybe (right (sym g))
1355 Note the forall'd tyvars of the selector are just the free tyvars
1356 of the result type; there may be other tyvars in the constructor's
1357 type (e.g. 'b' in T2).
1359 Note the need for casts in the result!
1361 Note [Selector running example]
1362 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1363 It's OK to combine GADTs and type families. Here's a running example:
1365 data instance T [a] where
1366 T1 { fld :: b } :: T [Maybe b]
1368 The representation type looks like this
1370 T1 { fld :: b } :: :R7T (Maybe b)
1372 and there's coercion from the family type to the representation type
1373 :CoR7T a :: T [a] ~ :R7T a
1375 The selector we want for fld looks like this:
1377 fld :: forall b. T [Maybe b] -> b
1378 fld = /\b. \(d::T [Maybe b]).
1379 case d `cast` :CoR7T (Maybe b) of
1382 The scrutinee of the case has type :R7T (Maybe b), which can be
1383 gotten by appying the eq_spec to the univ_tvs of the data con.
1385 %************************************************************************
1389 %************************************************************************
1392 resultTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1393 resultTypeMisMatch field_name con1 con2
1394 = vcat [sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1395 ptext (sLit "have a common field") <+> quotes (ppr field_name) <> comma],
1396 nest 2 $ ptext (sLit "but have different result types")]
1398 fieldTypeMisMatch :: Name -> DataCon -> DataCon -> SDoc
1399 fieldTypeMisMatch field_name con1 con2
1400 = sep [ptext (sLit "Constructors") <+> ppr con1 <+> ptext (sLit "and") <+> ppr con2,
1401 ptext (sLit "give different types for field"), quotes (ppr field_name)]
1403 dataConCtxt :: Outputable a => a -> SDoc
1404 dataConCtxt con = ptext (sLit "In the definition of data constructor") <+> quotes (ppr con)
1406 classOpCtxt :: Var -> Type -> SDoc
1407 classOpCtxt sel_id tau = sep [ptext (sLit "When checking the class method:"),
1408 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
1410 nullaryClassErr :: Class -> SDoc
1412 = ptext (sLit "No parameters for class") <+> quotes (ppr cls)
1414 classArityErr :: Class -> SDoc
1416 = vcat [ptext (sLit "Too many parameters for class") <+> quotes (ppr cls),
1417 parens (ptext (sLit "Use -XMultiParamTypeClasses to allow multi-parameter classes"))]
1419 classFunDepsErr :: Class -> SDoc
1421 = vcat [ptext (sLit "Fundeps in class") <+> quotes (ppr cls),
1422 parens (ptext (sLit "Use -XFunctionalDependencies to allow fundeps"))]
1424 noClassTyVarErr :: Class -> Var -> SDoc
1425 noClassTyVarErr clas op
1426 = sep [ptext (sLit "The class method") <+> quotes (ppr op),
1427 ptext (sLit "mentions none of the type variables of the class") <+>
1428 ppr clas <+> hsep (map ppr (classTyVars clas))]
1430 genericMultiParamErr :: Class -> SDoc
1431 genericMultiParamErr clas
1432 = ptext (sLit "The multi-parameter class") <+> quotes (ppr clas) <+>
1433 ptext (sLit "cannot have generic methods")
1435 {- Commented out until the call is reinstated
1436 badGenericMethodType :: Name -> Kind -> SDoc
1437 badGenericMethodType op op_ty
1438 = hang (ptext (sLit "Generic method type is too complex"))
1439 2 (vcat [ppr op <+> dcolon <+> ppr op_ty,
1440 ptext (sLit "You can only use type variables, arrows, lists, and tuples")])
1443 recSynErr :: [LTyClDecl Name] -> TcRn ()
1445 = setSrcSpan (getLoc (head sorted_decls)) $
1446 addErr (sep [ptext (sLit "Cycle in type synonym declarations:"),
1447 nest 2 (vcat (map ppr_decl sorted_decls))])
1449 sorted_decls = sortLocated syn_decls
1450 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
1452 recClsErr :: [Located (TyClDecl Name)] -> TcRn ()
1454 = setSrcSpan (getLoc (head sorted_decls)) $
1455 addErr (sep [ptext (sLit "Cycle in class declarations (via superclasses):"),
1456 nest 2 (vcat (map ppr_decl sorted_decls))])
1458 sorted_decls = sortLocated cls_decls
1459 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
1461 sortLocated :: [Located a] -> [Located a]
1462 sortLocated things = sortLe le things
1464 le (L l1 _) (L l2 _) = l1 <= l2
1466 badDataConTyCon :: DataCon -> Type -> Type -> SDoc
1467 badDataConTyCon data_con res_ty_tmpl actual_res_ty
1468 = hang (ptext (sLit "Data constructor") <+> quotes (ppr data_con) <+>
1469 ptext (sLit "returns type") <+> quotes (ppr actual_res_ty))
1470 2 (ptext (sLit "instead of an instance of its parent type") <+> quotes (ppr res_ty_tmpl))
1472 badGadtDecl :: Name -> SDoc
1474 = vcat [ ptext (sLit "Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
1475 , nest 2 (parens $ ptext (sLit "Use -XGADTs to allow GADTs")) ]
1477 badExistential :: Located Name -> SDoc
1478 badExistential con_name
1479 = hang (ptext (sLit "Data constructor") <+> quotes (ppr con_name) <+>
1480 ptext (sLit "has existential type variables, a context, or a specialised result type"))
1481 2 (parens $ ptext (sLit "Use -XExistentialQuantification or -XGADTs to allow this"))
1483 badStupidTheta :: Name -> SDoc
1484 badStupidTheta tc_name
1485 = ptext (sLit "A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
1487 newtypeConError :: Name -> Int -> SDoc
1488 newtypeConError tycon n
1489 = sep [ptext (sLit "A newtype must have exactly one constructor,"),
1490 nest 2 $ ptext (sLit "but") <+> quotes (ppr tycon) <+> ptext (sLit "has") <+> speakN n ]
1492 newtypeExError :: DataCon -> SDoc
1494 = sep [ptext (sLit "A newtype constructor cannot have an existential context,"),
1495 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1497 newtypeStrictError :: DataCon -> SDoc
1498 newtypeStrictError con
1499 = sep [ptext (sLit "A newtype constructor cannot have a strictness annotation,"),
1500 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does")]
1502 newtypePredError :: DataCon -> SDoc
1503 newtypePredError con
1504 = sep [ptext (sLit "A newtype constructor must have a return type of form T a1 ... an"),
1505 nest 2 $ ptext (sLit "but") <+> quotes (ppr con) <+> ptext (sLit "does not")]
1507 newtypeFieldErr :: DataCon -> Int -> SDoc
1508 newtypeFieldErr con_name n_flds
1509 = sep [ptext (sLit "The constructor of a newtype must have exactly one field"),
1510 nest 2 $ ptext (sLit "but") <+> quotes (ppr con_name) <+> ptext (sLit "has") <+> speakN n_flds]
1512 badSigTyDecl :: Name -> SDoc
1513 badSigTyDecl tc_name
1514 = vcat [ ptext (sLit "Illegal kind signature") <+>
1515 quotes (ppr tc_name)
1516 , nest 2 (parens $ ptext (sLit "Use -XKindSignatures to allow kind signatures")) ]
1518 badFamInstDecl :: Outputable a => a -> SDoc
1519 badFamInstDecl tc_name
1520 = vcat [ ptext (sLit "Illegal family instance for") <+>
1521 quotes (ppr tc_name)
1522 , nest 2 (parens $ ptext (sLit "Use -XTypeFamilies to allow indexed type families")) ]
1524 tooManyParmsErr :: Located Name -> SDoc
1525 tooManyParmsErr tc_name
1526 = ptext (sLit "Family instance has too many parameters:") <+>
1527 quotes (ppr tc_name)
1529 tooFewParmsErr :: Arity -> SDoc
1530 tooFewParmsErr arity
1531 = ptext (sLit "Family instance has too few parameters; expected") <+>
1534 wrongNumberOfParmsErr :: Arity -> SDoc
1535 wrongNumberOfParmsErr exp_arity
1536 = ptext (sLit "Number of parameters must match family declaration; expected")
1539 badBootFamInstDeclErr :: SDoc
1540 badBootFamInstDeclErr
1541 = ptext (sLit "Illegal family instance in hs-boot file")
1543 notFamily :: TyCon -> SDoc
1545 = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon)
1546 , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))]
1548 wrongKindOfFamily :: TyCon -> SDoc
1549 wrongKindOfFamily family
1550 = ptext (sLit "Wrong category of family instance; declaration was for a")
1553 kindOfFamily | isSynTyCon family = ptext (sLit "type synonym")
1554 | isAlgTyCon family = ptext (sLit "data type")
1555 | otherwise = pprPanic "wrongKindOfFamily" (ppr family)
1557 emptyConDeclsErr :: Name -> SDoc
1558 emptyConDeclsErr tycon
1559 = sep [quotes (ppr tycon) <+> ptext (sLit "has no constructors"),
1560 nest 2 $ ptext (sLit "(-XEmptyDataDecls permits this)")]