2 % (c) The AQUA Project, Glasgow University, 1996-1998
4 \section[TcTyClsDecls]{Typecheck type and class declarations}
11 #include "HsVersions.h"
13 import HsSyn ( TyClDecl(..), HsConDetails(..), HsTyVarBndr(..),
14 ConDecl(..), Sig(..), , NewOrData(..),
15 tyClDeclTyVars, isSynDecl, LConDecl,
16 LTyClDecl, tcdName, LHsTyVarBndr, LHsContext
18 import HsTypes ( HsBang(..), getBangStrictness )
19 import BasicTypes ( RecFlag(..), StrictnessMark(..) )
20 import HscTypes ( implicitTyThings )
21 import BuildTyCl ( buildClass, buildAlgTyCon, buildSynTyCon, buildDataCon,
22 mkDataTyConRhs, mkNewTyConRhs )
24 import TcEnv ( TcTyThing(..), TyThing(..),
25 tcLookupLocated, tcLookupLocatedGlobal,
26 tcExtendGlobalEnv, tcExtendKindEnv,
27 tcExtendRecEnv, tcLookupTyVar )
28 import TcTyDecls ( calcTyConArgVrcs, calcRecFlags, calcClassCycles, calcSynCycles )
29 import TcClassDcl ( tcClassSigs, tcAddDeclCtxt )
30 import TcHsType ( kcHsTyVars, kcHsLiftedSigType, kcHsType,
31 kcHsContext, tcTyVarBndrs, tcHsKindedType, tcHsKindedContext,
32 kcHsSigType, tcHsBangType, tcLHsConSig )
33 import TcMType ( newKindVar, checkValidTheta, checkValidType, checkFreeness,
34 UserTypeCtxt(..), SourceTyCtxt(..) )
35 import TcUnify ( unifyKind )
36 import TcType ( TcKind, ThetaType, TcType, tyVarsOfType,
37 mkArrowKind, liftedTypeKind, mkTyVarTys, tcEqTypes,
38 tcSplitSigmaTy, tcEqType )
39 import Type ( splitTyConApp_maybe, pprThetaArrow, pprParendType )
40 import Generics ( validGenericMethodType, canDoGenerics )
41 import Class ( Class, className, classTyCon, DefMeth(..), classBigSig, classTyVars )
42 import TyCon ( TyCon, ArgVrcs,
43 tyConDataCons, mkForeignTyCon, isProductTyCon, isRecursiveTyCon,
44 tyConStupidTheta, getSynTyConDefn, tyConDataCons, isSynTyCon, tyConName )
45 import DataCon ( DataCon, dataConWrapId, dataConName, dataConSig,
46 dataConFieldLabels, dataConOrigArgTys, dataConTyCon )
47 import Type ( zipTopTvSubst, substTys )
48 import Var ( TyVar, idType, idName )
49 import VarSet ( elemVarSet )
52 import Util ( zipLazy, isSingleton, notNull, sortLe )
53 import List ( partition )
54 import SrcLoc ( Located(..), unLoc, getLoc )
55 import ListSetOps ( equivClasses )
56 import Digraph ( SCC(..) )
57 import CmdLineOpts ( DynFlag( Opt_GlasgowExts, Opt_Generics, Opt_UnboxStrictFields ) )
61 %************************************************************************
63 \subsection{Type checking for type and class declarations}
65 %************************************************************************
69 Consider a mutually-recursive group, binding
70 a type constructor T and a class C.
72 Step 1: getInitialKind
73 Construct a KindEnv by binding T and C to a kind variable
76 In that environment, do a kind check
78 Step 3: Zonk the kinds
80 Step 4: buildTyConOrClass
81 Construct an environment binding T to a TyCon and C to a Class.
82 a) Their kinds comes from zonking the relevant kind variable
83 b) Their arity (for synonyms) comes direct from the decl
84 c) The funcional dependencies come from the decl
85 d) The rest comes a knot-tied binding of T and C, returned from Step 4
86 e) The variances of the tycons in the group is calculated from
90 In this environment, walk over the decls, constructing the TyCons and Classes.
91 This uses in a strict way items (a)-(c) above, which is why they must
92 be constructed in Step 4. Feed the results back to Step 4.
93 For this step, pass the is-recursive flag as the wimp-out flag
97 Step 6: Extend environment
98 We extend the type environment with bindings not only for the TyCons and Classes,
99 but also for their "implicit Ids" like data constructors and class selectors
101 Step 7: checkValidTyCl
102 For a recursive group only, check all the decls again, just
103 to check all the side conditions on validity. We could not
104 do this before because we were in a mutually recursive knot.
107 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
108 @TyThing@s. @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
111 tcTyAndClassDecls :: [Name] -> [LTyClDecl Name]
112 -> TcM TcGblEnv -- Input env extended by types and classes
113 -- and their implicit Ids,DataCons
114 tcTyAndClassDecls boot_names decls
115 = do { -- First check for cyclic type synonysm or classes
116 -- See notes with checkCycleErrs
119 ; (syn_tycons, alg_tyclss) <- fixM (\ ~(rec_syn_tycons, rec_alg_tyclss) ->
120 do { let { -- Calculate variances and rec-flag
121 ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc) decls }
123 -- Extend the global env with the knot-tied results
124 -- for data types and classes
126 -- We must populate the environment with the loop-tied T's right
127 -- away, because the kind checker may "fault in" some type
128 -- constructors that recursively mention T
129 ; let { gbl_things = mkGlobalThings alg_decls rec_alg_tyclss }
130 ; tcExtendRecEnv gbl_things $ do
132 -- Kind-check the declarations
133 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
135 ; let { calc_vrcs = calcTyConArgVrcs (rec_syn_tycons ++ rec_alg_tyclss)
136 ; calc_rec = calcRecFlags boot_names rec_alg_tyclss
137 ; tc_decl = addLocM (tcTyClDecl calc_vrcs calc_rec) }
138 -- Type-check the type synonyms, and extend the envt
139 ; syn_tycons <- tcSynDecls calc_vrcs kc_syn_decls
140 ; tcExtendGlobalEnv syn_tycons $ do
142 -- Type-check the data types and classes
143 { alg_tyclss <- mappM tc_decl kc_alg_decls
144 ; return (syn_tycons, alg_tyclss)
146 -- Finished with knot-tying now
147 -- Extend the environment with the finished things
148 ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
150 -- Perform the validity check
151 { traceTc (text "ready for validity check")
152 ; mappM_ (addLocM checkValidTyCl) decls
153 ; traceTc (text "done")
155 -- Add the implicit things;
156 -- we want them in the environment because
157 -- they may be mentioned in interface files
158 ; let { implicit_things = concatMap implicitTyThings alg_tyclss }
159 ; traceTc ((text "Adding" <+> ppr alg_tyclss) $$ (text "and" <+> ppr implicit_things))
160 ; tcExtendGlobalEnv implicit_things getGblEnv
163 mkGlobalThings :: [LTyClDecl Name] -- The decls
164 -> [TyThing] -- Knot-tied, in 1-1 correspondence with the decls
166 -- Driven by the Decls, and treating the TyThings lazily
167 -- make a TypeEnv for the new things
168 mkGlobalThings decls things
169 = map mk_thing (decls `zipLazy` things)
171 mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
173 mk_thing (L _ decl, ~(ATyCon tc))
174 = (tcdName decl, ATyCon tc)
178 %************************************************************************
182 %************************************************************************
184 We need to kind check all types in the mutually recursive group
185 before we know the kind of the type variables. For example:
188 op :: D b => a -> b -> b
191 bop :: (Monad c) => ...
193 Here, the kind of the locally-polymorphic type variable "b"
194 depends on *all the uses of class D*. For example, the use of
195 Monad c in bop's type signature means that D must have kind Type->Type.
197 However type synonyms work differently. They can have kinds which don't
198 just involve (->) and *:
199 type R = Int# -- Kind #
200 type S a = Array# a -- Kind * -> #
201 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
202 So we must infer their kinds from their right-hand sides *first* and then
203 use them, whereas for the mutually recursive data types D we bring into
204 scope kind bindings D -> k, where k is a kind variable, and do inference.
207 kcTyClDecls syn_decls alg_decls
208 = do { -- First extend the kind env with each data
209 -- type and class, mapping them to a type variable
210 alg_kinds <- mappM getInitialKind alg_decls
211 ; tcExtendKindEnv alg_kinds $ do
213 -- Now kind-check the type synonyms, in dependency order
214 -- We do these differently to data type and classes,
215 -- because a type synonym can be an unboxed type
217 -- and a kind variable can't unify with UnboxedTypeKind
218 -- So we infer their kinds in dependency order
219 { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
220 ; tcExtendKindEnv syn_kinds $ do
222 -- Now kind-check the data type and class declarations,
223 -- returning kind-annotated decls
224 { kc_alg_decls <- mappM (wrapLocM kcTyClDecl) alg_decls
226 ; return (kc_syn_decls, kc_alg_decls) }}}
228 ------------------------------------------------------------------------
229 getInitialKind :: LTyClDecl Name -> TcM (Name, TcKind)
232 = newKindVar `thenM` \ kind ->
233 returnM (unLoc (tcdLName (unLoc decl)), kind)
236 kcSynDecls :: [SCC (LTyClDecl Name)]
237 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
238 [(Name,TcKind)]) -- Kind bindings
241 kcSynDecls (group : groups)
242 = do { (decl, nk) <- kcSynDecl group
243 ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
244 ; return (decl:decls, nk:nks) }
247 kcSynDecl :: SCC (LTyClDecl Name)
248 -> TcM (LTyClDecl Name, -- Kind-annotated decls
249 (Name,TcKind)) -- Kind bindings
250 kcSynDecl (AcyclicSCC ldecl@(L loc decl))
251 = tcAddDeclCtxt decl $
252 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
253 do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
254 <+> brackets (ppr k_tvs))
255 ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
256 ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
257 ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
258 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
259 (unLoc (tcdLName decl), tc_kind)) })
261 kcSynDecl (CyclicSCC decls)
262 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
263 -- of out-of-scope tycons
265 ------------------------------------------------------------------------
266 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
267 -- Not used for type synonyms (see kcSynDecl)
269 kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
270 = kcTyClDeclBody decl $ \ tvs' ->
271 do { ctxt' <- kcHsContext ctxt
272 ; cons' <- mappM (wrapLocM kc_con_decl) cons
273 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdCons = cons'}) }
275 kc_con_decl (ConDecl name ex_tvs ex_ctxt details)
276 = kcHsTyVars ex_tvs $ \ ex_tvs' ->
277 do { ex_ctxt' <- kcHsContext ex_ctxt
278 ; details' <- kc_con_details details
279 ; return (ConDecl name ex_tvs' ex_ctxt' details')}
280 kc_con_decl (GadtDecl name ty)
281 = do { ty' <- kcHsSigType ty
282 ; return (GadtDecl name ty') }
284 kc_con_details (PrefixCon btys)
285 = do { btys' <- mappM kc_larg_ty btys ; return (PrefixCon btys') }
286 kc_con_details (InfixCon bty1 bty2)
287 = do { bty1' <- kc_larg_ty bty1; bty2' <- kc_larg_ty bty2; return (InfixCon bty1' bty2') }
288 kc_con_details (RecCon fields)
289 = do { fields' <- mappM kc_field fields; return (RecCon fields') }
291 kc_field (fld, bty) = do { bty' <- kc_larg_ty bty ; return (fld, bty') }
293 kc_larg_ty bty = case new_or_data of
294 DataType -> kcHsSigType bty
295 NewType -> kcHsLiftedSigType bty
296 -- Can't allow an unlifted type for newtypes, because we're effectively
297 -- going to remove the constructor while coercing it to a lifted type.
298 -- And newtypes can't be bang'd
300 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs})
301 = kcTyClDeclBody decl $ \ tvs' ->
302 do { ctxt' <- kcHsContext ctxt
303 ; sigs' <- mappM (wrapLocM kc_sig) sigs
304 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs'}) }
306 kc_sig (Sig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
307 ; return (Sig nm op_ty') }
308 kc_sig other_sig = return other_sig
310 kcTyClDecl decl@(ForeignType {})
313 kcTyClDeclBody :: TyClDecl Name
314 -> ([LHsTyVarBndr Name] -> TcM a)
316 -- Extend the env with bindings for the tyvars, taken from
317 -- the kind of the tycon/class. Give it to the thing inside, and
318 -- check the result kind matches
319 kcTyClDeclBody decl thing_inside
320 = tcAddDeclCtxt decl $
321 kcHsTyVars (tyClDeclTyVars decl) $ \ kinded_tvs ->
322 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
323 ; let tc_kind = case tc_ty_thing of { AThing k -> k }
324 ; unifyKind tc_kind (foldr (mkArrowKind . kindedTyVarKind)
327 ; thing_inside kinded_tvs }
329 result_kind (TyData { tcdKindSig = Just kind }) = kind
330 result_kind other = liftedTypeKind
331 -- On GADT-style declarations we allow a kind signature
332 -- data T :: *->* where { ... }
334 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
338 %************************************************************************
340 \subsection{Type checking}
342 %************************************************************************
345 tcSynDecls :: (Name -> ArgVrcs) -> [LTyClDecl Name] -> TcM [TyThing]
346 tcSynDecls calc_vrcs [] = return []
347 tcSynDecls calc_vrcs (decl : decls)
348 = do { syn_tc <- addLocM (tcSynDecl calc_vrcs) decl
349 ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls calc_vrcs decls)
350 ; return (syn_tc : syn_tcs) }
353 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
354 = tcTyVarBndrs tvs $ \ tvs' -> do
355 { traceTc (text "tcd1" <+> ppr tc_name)
356 ; rhs_ty' <- tcHsKindedType rhs_ty
357 ; return (ATyCon (buildSynTyCon tc_name tvs' rhs_ty' (calc_vrcs tc_name))) }
360 tcTyClDecl :: (Name -> ArgVrcs) -> (Name -> RecFlag)
361 -> TyClDecl Name -> TcM TyThing
363 tcTyClDecl calc_vrcs calc_isrec decl
364 = tcAddDeclCtxt decl (tcTyClDecl1 calc_vrcs calc_isrec decl)
366 tcTyClDecl1 calc_vrcs calc_isrec
367 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
368 tcdLName = L _ tc_name, tcdCons = cons})
369 = tcTyVarBndrs tvs $ \ tvs' -> do
370 { stupid_theta <- tcStupidTheta ctxt cons
371 ; want_generic <- doptM Opt_Generics
372 ; tycon <- fixM (\ tycon -> do
373 { unbox_strict <- doptM Opt_UnboxStrictFields
374 ; data_cons <- mappM (addLocM (tcConDecl unbox_strict new_or_data tycon tvs')) cons
375 ; let tc_rhs = case new_or_data of
376 DataType -> mkDataTyConRhs stupid_theta data_cons
377 NewType -> ASSERT( isSingleton data_cons )
378 mkNewTyConRhs tycon (head data_cons)
379 ; buildAlgTyCon tc_name tvs' tc_rhs arg_vrcs is_rec
380 (want_generic && canDoGenerics data_cons)
382 ; return (ATyCon tycon)
385 arg_vrcs = calc_vrcs tc_name
386 is_rec = calc_isrec tc_name
388 tcTyClDecl1 calc_vrcs calc_isrec
389 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
390 tcdCtxt = ctxt, tcdMeths = meths,
391 tcdFDs = fundeps, tcdSigs = sigs} )
392 = tcTyVarBndrs tvs $ \ tvs' -> do
393 { ctxt' <- tcHsKindedContext ctxt
394 ; fds' <- mappM (addLocM tc_fundep) fundeps
395 ; sig_stuff <- tcClassSigs class_name sigs meths
396 ; clas <- fixM (\ clas ->
397 let -- This little knot is just so we can get
398 -- hold of the name of the class TyCon, which we
399 -- need to look up its recursiveness and variance
400 tycon_name = tyConName (classTyCon clas)
401 tc_isrec = calc_isrec tycon_name
402 tc_vrcs = calc_vrcs tycon_name
404 buildClass class_name tvs' ctxt' fds'
405 sig_stuff tc_isrec tc_vrcs)
406 ; return (AClass clas) }
408 tc_fundep (tvs1, tvs2) = do { tvs1' <- mappM tcLookupTyVar tvs1 ;
409 ; tvs2' <- mappM tcLookupTyVar tvs2 ;
410 ; return (tvs1', tvs2') }
413 tcTyClDecl1 calc_vrcs calc_isrec
414 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
415 = returnM (ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0 []))
417 -----------------------------------
418 tcConDecl :: Bool -- True <=> -funbox-strict_fields
419 -> NewOrData -> TyCon -> [TyVar]
420 -> ConDecl Name -> TcM DataCon
422 tcConDecl unbox_strict new_or_data tycon tc_tvs
423 (ConDecl name ex_tvs ex_ctxt details)
424 = tcTyVarBndrs ex_tvs $ \ ex_tvs' -> do
425 { ex_ctxt' <- tcHsKindedContext ex_ctxt
427 is_vanilla = null ex_tvs && null (unLoc ex_ctxt)
428 -- Vanilla iff no ex_tvs and no context
430 tc_datacon is_infix field_lbls btys
431 = do { let { bangs = map getBangStrictness btys }
432 ; arg_tys <- mappM tcHsBangType btys
433 ; buildDataCon (unLoc name) is_infix is_vanilla
434 (argStrictness unbox_strict tycon bangs arg_tys)
435 (map unLoc field_lbls)
439 tycon (mkTyVarTys tc_tvs) }
441 PrefixCon btys -> tc_datacon False [] btys
442 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
443 RecCon fields -> do { checkTc is_vanilla (exRecConErr name)
444 ; let { (field_names, btys) = unzip fields }
445 ; tc_datacon False field_names btys } }
447 tcConDecl unbox_strict new_or_data tycon tc_tvs
448 decl@(GadtDecl name con_ty)
449 = do { traceTc (text "tcConDecl" <+> ppr name)
450 ; (tvs, theta, bangs, arg_tys, tc, res_tys) <- tcLHsConSig con_ty
452 ; traceTc (text "tcConDecl1" <+> ppr name)
453 ; let -- Now dis-assemble the type, and check its form
454 is_vanilla = null theta && mkTyVarTys tvs `tcEqTypes` res_tys
456 -- Vanilla datacons guarantee to use the same
457 -- type variables as the parent tycon
458 (tvs', arg_tys', res_tys')
459 | is_vanilla = (tc_tvs, substTys subst arg_tys, substTys subst res_tys)
460 | otherwise = (tvs, arg_tys, res_tys)
461 subst = zipTopTvSubst tvs (mkTyVarTys tc_tvs)
463 ; traceTc (text "tcConDecl3" <+> ppr name)
464 ; buildDataCon (unLoc name) False {- Not infix -} is_vanilla
465 (argStrictness unbox_strict tycon bangs arg_tys)
466 [{- No field labels -}]
467 tvs' theta arg_tys' tycon res_tys' }
469 tcStupidTheta :: LHsContext Name -> [LConDecl Name] -> TcM (Maybe ThetaType)
470 -- For GADTs we don't allow a context on the data declaration
471 -- whereas for standard Haskell style data declarations, we do
472 tcStupidTheta ctxt (L _ (ConDecl _ _ _ _) : _)
473 = do { theta <- tcHsKindedContext ctxt; return (Just theta) }
474 tcStupidTheta ctxt other -- Includes an empty constructor list
475 = ASSERT( null (unLoc ctxt) ) return Nothing
478 argStrictness :: Bool -- True <=> -funbox-strict_fields
480 -> [TcType] -> [StrictnessMark]
481 argStrictness unbox_strict tycon bangs arg_tys
482 = ASSERT( length bangs == length arg_tys )
483 zipWith (chooseBoxingStrategy unbox_strict tycon) arg_tys bangs
485 -- We attempt to unbox/unpack a strict field when either:
486 -- (i) The field is marked '!!', or
487 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
489 chooseBoxingStrategy :: Bool -> TyCon -> TcType -> HsBang -> StrictnessMark
490 chooseBoxingStrategy unbox_strict_fields tycon arg_ty bang
492 HsNoBang -> NotMarkedStrict
493 HsStrict | unbox_strict_fields && can_unbox -> MarkedUnboxed
494 HsUnbox | can_unbox -> MarkedUnboxed
495 other -> MarkedStrict
497 can_unbox = case splitTyConApp_maybe arg_ty of
499 Just (arg_tycon, _) -> not (isRecursiveTyCon tycon) &&
500 isProductTyCon arg_tycon
503 %************************************************************************
505 \subsection{Dependency analysis}
507 %************************************************************************
509 Validity checking is done once the mutually-recursive knot has been
510 tied, so we can look at things freely.
513 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
514 checkCycleErrs tyclss
518 = do { mappM_ recClsErr cls_cycles
519 ; failM } -- Give up now, because later checkValidTyCl
520 -- will loop if the synonym is recursive
522 cls_cycles = calcClassCycles tyclss
524 checkValidTyCl :: TyClDecl Name -> TcM ()
525 -- We do the validity check over declarations, rather than TyThings
526 -- only so that we can add a nice context with tcAddDeclCtxt
528 = tcAddDeclCtxt decl $
529 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
530 ; traceTc (text "Validity of" <+> ppr thing)
532 ATyCon tc -> checkValidTyCon tc
533 AClass cl -> checkValidClass cl
534 ; traceTc (text "Done validity of" <+> ppr thing)
537 -------------------------
538 checkValidTyCon :: TyCon -> TcM ()
541 = checkValidType syn_ctxt syn_rhs
543 = -- Check the context on the data decl
544 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc) `thenM_`
546 -- Check arg types of data constructors
547 mappM_ (checkValidDataCon tc) data_cons `thenM_`
549 -- Check that fields with the same name share a type
550 mappM_ check_fields groups
553 syn_ctxt = TySynCtxt name
555 (_, syn_rhs) = getSynTyConDefn tc
556 data_cons = tyConDataCons tc
558 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
559 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
560 get_fields con = dataConFieldLabels con `zip` dataConOrigArgTys con
561 -- dataConFieldLabels may return the empty list, which is fine
563 check_fields fields@((first_field_label, field_ty) : other_fields)
564 -- These fields all have the same name, but are from
565 -- different constructors in the data type
566 = -- Check that all the fields in the group have the same type
567 -- NB: this check assumes that all the constructors of a given
568 -- data type use the same type variables
569 checkTc (all (tcEqType field_ty . snd) other_fields)
570 (fieldTypeMisMatch first_field_label)
572 -------------------------------
573 checkValidDataCon :: TyCon -> DataCon -> TcM ()
574 checkValidDataCon tc con
575 = addErrCtxt (dataConCtxt con) $
576 do { checkTc (dataConTyCon con == tc) (badDataConTyCon con)
577 ; checkValidType ctxt (idType (dataConWrapId con)) }
579 -- This checks the argument types and
580 -- ambiguity of the existential context (if any)
582 -- Note [Sept 04] Now that tvs is all the tvs, this
583 -- test doesn't actually check anything
584 -- ; checkFreeness tvs ex_theta }
586 ctxt = ConArgCtxt (dataConName con)
587 (tvs, ex_theta, _, _, _) = dataConSig con
590 -------------------------------
591 checkValidClass :: Class -> TcM ()
593 = do { -- CHECK ARITY 1 FOR HASKELL 1.4
594 gla_exts <- doptM Opt_GlasgowExts
596 -- Check that the class is unary, unless GlaExs
597 ; checkTc (notNull tyvars) (nullaryClassErr cls)
598 ; checkTc (gla_exts || unary) (classArityErr cls)
600 -- Check the super-classes
601 ; checkValidTheta (ClassSCCtxt (className cls)) theta
603 -- Check the class operations
604 ; mappM_ check_op op_stuff
606 -- Check that if the class has generic methods, then the
607 -- class has only one parameter. We can't do generic
608 -- multi-parameter type classes!
609 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
612 (tyvars, theta, _, op_stuff) = classBigSig cls
613 unary = isSingleton tyvars
614 no_generics = null [() | (_, GenDefMeth) <- op_stuff]
616 check_op (sel_id, dm)
617 = addErrCtxt (classOpCtxt sel_id tau) $ do
618 { checkValidTheta SigmaCtxt (tail theta)
619 -- The 'tail' removes the initial (C a) from the
620 -- class itself, leaving just the method type
622 ; checkValidType (FunSigCtxt op_name) tau
624 -- Check that the type mentions at least one of
625 -- the class type variables
626 ; checkTc (any (`elemVarSet` tyVarsOfType tau) tyvars)
627 (noClassTyVarErr cls sel_id)
629 -- Check that for a generic method, the type of
630 -- the method is sufficiently simple
631 ; checkTc (dm /= GenDefMeth || validGenericMethodType op_ty)
632 (badGenericMethodType op_name op_ty)
635 op_name = idName sel_id
636 op_ty = idType sel_id
637 (_,theta,tau) = tcSplitSigmaTy op_ty
641 ---------------------------------------------------------------------
642 fieldTypeMisMatch field_name
643 = sep [ptext SLIT("Different constructors give different types for field"), quotes (ppr field_name)]
645 dataConCtxt con = sep [ptext SLIT("When checking the data constructor:"),
646 nest 2 (ex_part <+> pprThetaArrow ex_theta <+> ppr con <+> arg_part)]
648 (ex_tvs, ex_theta, arg_tys, _, _) = dataConSig con
649 ex_part | null ex_tvs = empty
650 | otherwise = ptext SLIT("forall") <+> hsep (map ppr ex_tvs) <> dot
651 -- The 'ex_theta' part could be non-empty, if the user (bogusly) wrote
652 -- data T a = Eq a => T a a
653 -- So we make sure to print it
655 fields = dataConFieldLabels con
656 arg_part | null fields = sep (map pprParendType arg_tys)
657 | otherwise = braces (sep (punctuate comma
658 [ ppr n <+> dcolon <+> ppr ty
659 | (n,ty) <- fields `zip` arg_tys]))
661 classOpCtxt sel_id tau = sep [ptext SLIT("When checking the class method:"),
662 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
665 = ptext SLIT("No parameters for class") <+> quotes (ppr cls)
668 = vcat [ptext SLIT("Too many parameters for class") <+> quotes (ppr cls),
669 parens (ptext SLIT("Use -fglasgow-exts to allow multi-parameter classes"))]
671 noClassTyVarErr clas op
672 = sep [ptext SLIT("The class method") <+> quotes (ppr op),
673 ptext SLIT("mentions none of the type variables of the class") <+>
674 ppr clas <+> hsep (map ppr (classTyVars clas))]
676 genericMultiParamErr clas
677 = ptext SLIT("The multi-parameter class") <+> quotes (ppr clas) <+>
678 ptext SLIT("cannot have generic methods")
680 badGenericMethodType op op_ty
681 = hang (ptext SLIT("Generic method type is too complex"))
682 4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
683 ptext SLIT("You can only use type variables, arrows, and tuples")])
686 = setSrcSpan (getLoc (head sorted_decls)) $
687 addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
688 nest 2 (vcat (map ppr_decl sorted_decls))])
690 sorted_decls = sortLocated syn_decls
691 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
694 = setSrcSpan (getLoc (head sorted_decls)) $
695 addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
696 nest 2 (vcat (map ppr_decl sorted_decls))])
698 sorted_decls = sortLocated cls_decls
699 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
701 sortLocated :: [Located a] -> [Located a]
702 sortLocated things = sortLe le things
704 le (L l1 _) (L l2 _) = l1 <= l2
707 = ptext SLIT("Can't combine named fields with locally-quantified type variables or context")
709 (ptext SLIT("In the declaration of data constructor") <+> ppr name)
711 badDataConTyCon data_con
712 = hang (ptext SLIT("Data constructor does not return its parent type:"))