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(..), ResType(..),
15 tyClDeclTyVars, isSynDecl, isClassDecl, hsConArgs,
16 LTyClDecl, tcdName, hsTyVarName, LHsTyVarBndr
18 import HsTypes ( HsBang(..), getBangStrictness )
19 import BasicTypes ( RecFlag(..), StrictnessMark(..) )
20 import HscTypes ( implicitTyThings, ModDetails )
21 import BuildTyCl ( buildClass, buildAlgTyCon, buildSynTyCon, buildDataCon,
22 mkDataTyConRhs, mkNewTyConRhs )
24 import TcEnv ( TyThing(..),
25 tcLookupLocated, tcLookupLocatedGlobal,
26 tcExtendGlobalEnv, tcExtendKindEnv, tcExtendKindEnvTvs,
27 tcExtendRecEnv, tcLookupTyVar, InstInfo )
28 import TcTyDecls ( calcRecFlags, calcClassCycles, calcSynCycles )
29 import TcClassDcl ( tcClassSigs, tcAddDeclCtxt )
30 import TcHsType ( kcHsTyVars, kcHsLiftedSigType, kcHsType,
31 kcHsContext, tcTyVarBndrs, tcHsKindedType, tcHsKindedContext,
32 kcHsSigType, tcHsBangType, tcLHsConResTy, tcDataKindSig )
33 import TcMType ( newKindVar, checkValidTheta, checkValidType,
35 UserTypeCtxt(..), SourceTyCtxt(..) )
36 import TcType ( TcKind, TcType, Type, tyVarsOfType, mkPhiTy,
37 mkArrowKind, liftedTypeKind, mkTyVarTys,
38 tcSplitSigmaTy, tcEqTypes, tcGetTyVar_maybe )
39 import Type ( PredType(..), splitTyConApp_maybe, mkTyVarTy
40 -- pprParendType, pprThetaArrow
42 import Generics ( validGenericMethodType, canDoGenerics )
43 import Class ( Class, className, classTyCon, DefMeth(..), classBigSig, classTyVars )
44 import TyCon ( TyCon, AlgTyConRhs( AbstractTyCon ),
45 tyConDataCons, mkForeignTyCon, isProductTyCon, isRecursiveTyCon,
46 tyConStupidTheta, synTyConRhs, isSynTyCon, tyConName )
47 import DataCon ( DataCon, dataConUserType, dataConName,
48 dataConFieldLabels, dataConTyCon, dataConAllTyVars,
49 dataConFieldType, dataConResTys )
50 import Var ( TyVar, idType, idName )
51 import VarSet ( elemVarSet, mkVarSet )
52 import Name ( Name, getSrcLoc )
54 import Maybe ( isJust )
55 import Maybes ( expectJust )
56 import Unify ( tcMatchTys, tcMatchTyX )
57 import Util ( zipLazy, isSingleton, notNull, sortLe )
58 import List ( partition )
59 import SrcLoc ( Located(..), unLoc, getLoc, srcLocSpan )
60 import ListSetOps ( equivClasses, minusList )
61 import List ( delete )
62 import Digraph ( SCC(..) )
63 import DynFlags ( DynFlag( Opt_GlasgowExts, Opt_Generics,
64 Opt_UnboxStrictFields ) )
68 %************************************************************************
70 \subsection{Type checking for type and class declarations}
72 %************************************************************************
76 Consider a mutually-recursive group, binding
77 a type constructor T and a class C.
79 Step 1: getInitialKind
80 Construct a KindEnv by binding T and C to a kind variable
83 In that environment, do a kind check
85 Step 3: Zonk the kinds
87 Step 4: buildTyConOrClass
88 Construct an environment binding T to a TyCon and C to a Class.
89 a) Their kinds comes from zonking the relevant kind variable
90 b) Their arity (for synonyms) comes direct from the decl
91 c) The funcional dependencies come from the decl
92 d) The rest comes a knot-tied binding of T and C, returned from Step 4
93 e) The variances of the tycons in the group is calculated from
97 In this environment, walk over the decls, constructing the TyCons and Classes.
98 This uses in a strict way items (a)-(c) above, which is why they must
99 be constructed in Step 4. Feed the results back to Step 4.
100 For this step, pass the is-recursive flag as the wimp-out flag
104 Step 6: Extend environment
105 We extend the type environment with bindings not only for the TyCons and Classes,
106 but also for their "implicit Ids" like data constructors and class selectors
108 Step 7: checkValidTyCl
109 For a recursive group only, check all the decls again, just
110 to check all the side conditions on validity. We could not
111 do this before because we were in a mutually recursive knot.
113 Identification of recursive TyCons
114 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
115 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
118 Identifying a TyCon as recursive serves two purposes
120 1. Avoid infinite types. Non-recursive newtypes are treated as
121 "transparent", like type synonyms, after the type checker. If we did
122 this for all newtypes, we'd get infinite types. So we figure out for
123 each newtype whether it is "recursive", and add a coercion if so. In
124 effect, we are trying to "cut the loops" by identifying a loop-breaker.
126 2. Avoid infinite unboxing. This is nothing to do with newtypes.
130 Well, this function diverges, but we don't want the strictness analyser
131 to diverge. But the strictness analyser will diverge because it looks
132 deeper and deeper into the structure of T. (I believe there are
133 examples where the function does something sane, and the strictness
134 analyser still diverges, but I can't see one now.)
136 Now, concerning (1), the FC2 branch currently adds a coercion for ALL
137 newtypes. I did this as an experiment, to try to expose cases in which
138 the coercions got in the way of optimisations. If it turns out that we
139 can indeed always use a coercion, then we don't risk recursive types,
140 and don't need to figure out what the loop breakers are.
142 For newtype *families* though, we will always have a coercion, so they
143 are always loop breakers! So you can easily adjust the current
144 algorithm by simply treating all newtype families as loop breakers (and
145 indeed type families). I think.
148 tcTyAndClassDecls :: ModDetails -> [LTyClDecl Name]
149 -> TcM TcGblEnv -- Input env extended by types and classes
150 -- and their implicit Ids,DataCons
151 tcTyAndClassDecls boot_details decls
152 = do { -- First check for cyclic type synonysm or classes
153 -- See notes with checkCycleErrs
156 ; traceTc (text "tcTyAndCl" <+> ppr mod)
157 ; (syn_tycons, alg_tyclss) <- fixM (\ ~(rec_syn_tycons, rec_alg_tyclss) ->
158 do { let { -- Calculate variances and rec-flag
159 ; (syn_decls, alg_decls) = partition (isSynDecl . unLoc)
161 -- Extend the global env with the knot-tied results
162 -- for data types and classes
164 -- We must populate the environment with the loop-tied T's right
165 -- away, because the kind checker may "fault in" some type
166 -- constructors that recursively mention T
167 ; let { gbl_things = mkGlobalThings alg_decls rec_alg_tyclss }
168 ; tcExtendRecEnv gbl_things $ do
170 -- Kind-check the declarations
171 { (kc_syn_decls, kc_alg_decls) <- kcTyClDecls syn_decls alg_decls
173 ; let { calc_rec = calcRecFlags boot_details rec_alg_tyclss
174 ; tc_decl = addLocM (tcTyClDecl calc_rec) }
175 -- Type-check the type synonyms, and extend the envt
176 ; syn_tycons <- tcSynDecls kc_syn_decls
177 ; tcExtendGlobalEnv syn_tycons $ do
179 -- Type-check the data types and classes
180 { alg_tyclss <- mappM tc_decl kc_alg_decls
181 ; return (syn_tycons, alg_tyclss)
183 -- Finished with knot-tying now
184 -- Extend the environment with the finished things
185 ; tcExtendGlobalEnv (syn_tycons ++ alg_tyclss) $ do
187 -- Perform the validity check
188 { traceTc (text "ready for validity check")
189 ; mappM_ (addLocM checkValidTyCl) decls
190 ; traceTc (text "done")
192 -- Add the implicit things;
193 -- we want them in the environment because
194 -- they may be mentioned in interface files
195 ; let { implicit_things = concatMap implicitTyThings alg_tyclss }
196 ; traceTc ((text "Adding" <+> ppr alg_tyclss) $$ (text "and" <+> ppr implicit_things))
197 ; tcExtendGlobalEnv implicit_things getGblEnv
200 mkGlobalThings :: [LTyClDecl Name] -- The decls
201 -> [TyThing] -- Knot-tied, in 1-1 correspondence with the decls
203 -- Driven by the Decls, and treating the TyThings lazily
204 -- make a TypeEnv for the new things
205 mkGlobalThings decls things
206 = map mk_thing (decls `zipLazy` things)
208 mk_thing (L _ (ClassDecl {tcdLName = L _ name}), ~(AClass cl))
210 mk_thing (L _ decl, ~(ATyCon tc))
211 = (tcdName decl, ATyCon tc)
215 %************************************************************************
219 %************************************************************************
221 We need to kind check all types in the mutually recursive group
222 before we know the kind of the type variables. For example:
225 op :: D b => a -> b -> b
228 bop :: (Monad c) => ...
230 Here, the kind of the locally-polymorphic type variable "b"
231 depends on *all the uses of class D*. For example, the use of
232 Monad c in bop's type signature means that D must have kind Type->Type.
234 However type synonyms work differently. They can have kinds which don't
235 just involve (->) and *:
236 type R = Int# -- Kind #
237 type S a = Array# a -- Kind * -> #
238 type T a b = (# a,b #) -- Kind * -> * -> (# a,b #)
239 So we must infer their kinds from their right-hand sides *first* and then
240 use them, whereas for the mutually recursive data types D we bring into
241 scope kind bindings D -> k, where k is a kind variable, and do inference.
244 kcTyClDecls syn_decls alg_decls
245 = do { -- First extend the kind env with each data
246 -- type and class, mapping them to a type variable
247 alg_kinds <- mappM getInitialKind alg_decls
248 ; tcExtendKindEnv alg_kinds $ do
250 -- Now kind-check the type synonyms, in dependency order
251 -- We do these differently to data type and classes,
252 -- because a type synonym can be an unboxed type
254 -- and a kind variable can't unify with UnboxedTypeKind
255 -- So we infer their kinds in dependency order
256 { (kc_syn_decls, syn_kinds) <- kcSynDecls (calcSynCycles syn_decls)
257 ; tcExtendKindEnv syn_kinds $ do
259 -- Now kind-check the data type and class declarations,
260 -- returning kind-annotated decls
261 { kc_alg_decls <- mappM (wrapLocM kcTyClDecl) alg_decls
263 ; return (kc_syn_decls, kc_alg_decls) }}}
265 ------------------------------------------------------------------------
266 getInitialKind :: LTyClDecl Name -> TcM (Name, TcKind)
267 -- Only for data type and class declarations
268 -- Get as much info as possible from the data or class decl,
269 -- so as to maximise usefulness of error messages
270 getInitialKind (L _ decl)
271 = do { arg_kinds <- mapM (mk_arg_kind . unLoc) (tyClDeclTyVars decl)
272 ; res_kind <- mk_res_kind decl
273 ; return (tcdName decl, mkArrowKinds arg_kinds res_kind) }
275 mk_arg_kind (UserTyVar _) = newKindVar
276 mk_arg_kind (KindedTyVar _ kind) = return kind
278 mk_res_kind (TyData { tcdKindSig = Just kind }) = return kind
279 -- On GADT-style declarations we allow a kind signature
280 -- data T :: *->* where { ... }
281 mk_res_kind other = return liftedTypeKind
285 kcSynDecls :: [SCC (LTyClDecl Name)]
286 -> TcM ([LTyClDecl Name], -- Kind-annotated decls
287 [(Name,TcKind)]) -- Kind bindings
290 kcSynDecls (group : groups)
291 = do { (decl, nk) <- kcSynDecl group
292 ; (decls, nks) <- tcExtendKindEnv [nk] (kcSynDecls groups)
293 ; return (decl:decls, nk:nks) }
296 kcSynDecl :: SCC (LTyClDecl Name)
297 -> TcM (LTyClDecl Name, -- Kind-annotated decls
298 (Name,TcKind)) -- Kind bindings
299 kcSynDecl (AcyclicSCC ldecl@(L loc decl))
300 = tcAddDeclCtxt decl $
301 kcHsTyVars (tcdTyVars decl) (\ k_tvs ->
302 do { traceTc (text "kcd1" <+> ppr (unLoc (tcdLName decl)) <+> brackets (ppr (tcdTyVars decl))
303 <+> brackets (ppr k_tvs))
304 ; (k_rhs, rhs_kind) <- kcHsType (tcdSynRhs decl)
305 ; traceTc (text "kcd2" <+> ppr (unLoc (tcdLName decl)))
306 ; let tc_kind = foldr (mkArrowKind . kindedTyVarKind) rhs_kind k_tvs
307 ; return (L loc (decl { tcdTyVars = k_tvs, tcdSynRhs = k_rhs }),
308 (unLoc (tcdLName decl), tc_kind)) })
310 kcSynDecl (CyclicSCC decls)
311 = do { recSynErr decls; failM } -- Fail here to avoid error cascade
312 -- of out-of-scope tycons
314 kindedTyVarKind (L _ (KindedTyVar _ k)) = k
316 ------------------------------------------------------------------------
317 kcTyClDecl :: TyClDecl Name -> TcM (TyClDecl Name)
318 -- Not used for type synonyms (see kcSynDecl)
320 kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdCons = cons})
321 = kcTyClDeclBody decl $ \ tvs' ->
322 do { ctxt' <- kcHsContext ctxt
323 ; cons' <- mappM (wrapLocM kc_con_decl) cons
324 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdCons = cons'}) }
326 kc_con_decl (ConDecl name expl ex_tvs ex_ctxt details res) = do
327 kcHsTyVars ex_tvs $ \ex_tvs' -> do
328 ex_ctxt' <- kcHsContext ex_ctxt
329 details' <- kc_con_details details
331 ResTyH98 -> return ResTyH98
332 ResTyGADT ty -> do { ty' <- kcHsSigType ty; return (ResTyGADT ty') }
333 return (ConDecl name expl ex_tvs' ex_ctxt' details' res')
335 kc_con_details (PrefixCon btys)
336 = do { btys' <- mappM kc_larg_ty btys ; return (PrefixCon btys') }
337 kc_con_details (InfixCon bty1 bty2)
338 = do { bty1' <- kc_larg_ty bty1; bty2' <- kc_larg_ty bty2; return (InfixCon bty1' bty2') }
339 kc_con_details (RecCon fields)
340 = do { fields' <- mappM kc_field fields; return (RecCon fields') }
342 kc_field (fld, bty) = do { bty' <- kc_larg_ty bty ; return (fld, bty') }
344 kc_larg_ty bty = case new_or_data of
345 DataType -> kcHsSigType bty
346 NewType -> kcHsLiftedSigType bty
347 -- Can't allow an unlifted type for newtypes, because we're effectively
348 -- going to remove the constructor while coercing it to a lifted type.
349 -- And newtypes can't be bang'd
352 kcTyClDecl decl@(ClassDecl {tcdCtxt = ctxt, tcdSigs = sigs})
353 = kcTyClDeclBody decl $ \ tvs' ->
354 do { is_boot <- tcIsHsBoot
355 ; ctxt' <- kcHsContext ctxt
356 ; sigs' <- mappM (wrapLocM kc_sig) sigs
357 ; return (decl {tcdTyVars = tvs', tcdCtxt = ctxt', tcdSigs = sigs'}) }
359 kc_sig (TypeSig nm op_ty) = do { op_ty' <- kcHsLiftedSigType op_ty
360 ; return (TypeSig nm op_ty') }
361 kc_sig other_sig = return other_sig
363 kcTyClDecl decl@(ForeignType {})
366 kcTyClDeclBody :: TyClDecl Name
367 -> ([LHsTyVarBndr Name] -> TcM a)
369 -- getInitialKind has made a suitably-shaped kind for the type or class
370 -- Unpack it, and attribute those kinds to the type variables
371 -- Extend the env with bindings for the tyvars, taken from
372 -- the kind of the tycon/class. Give it to the thing inside, and
373 -- check the result kind matches
374 kcTyClDeclBody decl thing_inside
375 = tcAddDeclCtxt decl $
376 do { tc_ty_thing <- tcLookupLocated (tcdLName decl)
377 ; let tc_kind = case tc_ty_thing of { AThing k -> k }
378 (kinds, _) = splitKindFunTys tc_kind
379 hs_tvs = tcdTyVars decl
380 kinded_tvs = ASSERT( length kinds >= length hs_tvs )
381 [ L loc (KindedTyVar (hsTyVarName tv) k)
382 | (L loc tv, k) <- zip hs_tvs kinds]
383 ; tcExtendKindEnvTvs kinded_tvs (thing_inside kinded_tvs) }
387 %************************************************************************
389 \subsection{Type checking}
391 %************************************************************************
394 tcSynDecls :: [LTyClDecl Name] -> TcM [TyThing]
395 tcSynDecls [] = return []
396 tcSynDecls (decl : decls)
397 = do { syn_tc <- addLocM tcSynDecl decl
398 ; syn_tcs <- tcExtendGlobalEnv [syn_tc] (tcSynDecls decls)
399 ; return (syn_tc : syn_tcs) }
402 (TySynonym {tcdLName = L _ tc_name, tcdTyVars = tvs, tcdSynRhs = rhs_ty})
403 = tcTyVarBndrs tvs $ \ tvs' -> do
404 { traceTc (text "tcd1" <+> ppr tc_name)
405 ; rhs_ty' <- tcHsKindedType rhs_ty
406 ; return (ATyCon (buildSynTyCon tc_name tvs' rhs_ty')) }
409 tcTyClDecl :: (Name -> RecFlag) -> TyClDecl Name -> TcM TyThing
411 tcTyClDecl calc_isrec decl
412 = tcAddDeclCtxt decl (tcTyClDecl1 calc_isrec decl)
414 tcTyClDecl1 calc_isrec
415 (TyData {tcdND = new_or_data, tcdCtxt = ctxt, tcdTyVars = tvs,
416 tcdLName = L _ tc_name, tcdKindSig = mb_ksig, tcdCons = cons})
417 = tcTyVarBndrs tvs $ \ tvs' -> do
418 { extra_tvs <- tcDataKindSig mb_ksig
419 ; let final_tvs = tvs' ++ extra_tvs
420 ; stupid_theta <- tcHsKindedContext ctxt
421 ; want_generic <- doptM Opt_Generics
422 ; unbox_strict <- doptM Opt_UnboxStrictFields
423 ; gla_exts <- doptM Opt_GlasgowExts
424 ; is_boot <- tcIsHsBoot -- Are we compiling an hs-boot file?
426 -- Check that we don't use GADT syntax in H98 world
427 ; checkTc (gla_exts || h98_syntax) (badGadtDecl tc_name)
429 -- Check that the stupid theta is empty for a GADT-style declaration
430 ; checkTc (null stupid_theta || h98_syntax) (badStupidTheta tc_name)
432 -- Check that there's at least one condecl,
433 -- or else we're reading an hs-boot file, or -fglasgow-exts
434 ; checkTc (not (null cons) || gla_exts || is_boot)
435 (emptyConDeclsErr tc_name)
437 -- Check that a newtype has exactly one constructor
438 ; checkTc (new_or_data == DataType || isSingleton cons)
439 (newtypeConError tc_name (length cons))
441 ; tycon <- fixM (\ tycon -> do
442 { data_cons <- mappM (addLocM (tcConDecl unbox_strict new_or_data
446 if null cons && is_boot -- In a hs-boot file, empty cons means
447 then return AbstractTyCon -- "don't know"; hence Abstract
448 else case new_or_data of
449 DataType -> return (mkDataTyConRhs data_cons)
451 ASSERT( isSingleton data_cons )
452 mkNewTyConRhs tc_name tycon (head data_cons)
453 ; buildAlgTyCon tc_name final_tvs stupid_theta tc_rhs is_rec
454 (want_generic && canDoGenerics data_cons) h98_syntax
456 ; return (ATyCon tycon)
459 is_rec = calc_isrec tc_name
460 h98_syntax = case cons of -- All constructors have same shape
461 L _ (ConDecl { con_res = ResTyGADT _ }) : _ -> False
464 tcTyClDecl1 calc_isrec
465 (ClassDecl {tcdLName = L _ class_name, tcdTyVars = tvs,
466 tcdCtxt = ctxt, tcdMeths = meths,
467 tcdFDs = fundeps, tcdSigs = sigs, tcdATs = ats} )
468 = tcTyVarBndrs tvs $ \ tvs' -> do
469 { ctxt' <- tcHsKindedContext ctxt
470 ; fds' <- mappM (addLocM tc_fundep) fundeps
471 -- !!!TODO: process `ats`; what do we want to store in the `Class'? -=chak
472 ; sig_stuff <- tcClassSigs class_name sigs meths
473 ; clas <- fixM (\ clas ->
474 let -- This little knot is just so we can get
475 -- hold of the name of the class TyCon, which we
476 -- need to look up its recursiveness and variance
477 tycon_name = tyConName (classTyCon clas)
478 tc_isrec = calc_isrec tycon_name
480 buildClass class_name tvs' ctxt' fds'
482 ; return (AClass clas) }
484 tc_fundep (tvs1, tvs2) = do { tvs1' <- mappM tcLookupTyVar tvs1 ;
485 ; tvs2' <- mappM tcLookupTyVar tvs2 ;
486 ; return (tvs1', tvs2') }
489 tcTyClDecl1 calc_isrec
490 (ForeignType {tcdLName = L _ tc_name, tcdExtName = tc_ext_name})
491 = returnM (ATyCon (mkForeignTyCon tc_name tc_ext_name liftedTypeKind 0))
493 -----------------------------------
494 tcConDecl :: Bool -- True <=> -funbox-strict_fields
495 -> NewOrData -> TyCon -> [TyVar]
496 -> ConDecl Name -> TcM DataCon
498 tcConDecl unbox_strict NewType tycon tc_tvs -- Newtypes
499 (ConDecl name _ ex_tvs ex_ctxt details ResTyH98)
500 = do { let tc_datacon field_lbls arg_ty
501 = do { arg_ty' <- tcHsKindedType arg_ty -- No bang on newtype
502 ; buildDataCon (unLoc name) False {- Prefix -}
504 (map unLoc field_lbls)
505 tc_tvs [] -- No existentials
506 [] [] -- No equalities, predicates
510 -- Check that a newtype has no existential stuff
511 ; checkTc (null ex_tvs && null (unLoc ex_ctxt)) (newtypeExError name)
514 PrefixCon [arg_ty] -> tc_datacon [] arg_ty
515 RecCon [(field_lbl, arg_ty)] -> tc_datacon [field_lbl] arg_ty
516 other -> failWithTc (newtypeFieldErr name (length (hsConArgs details)))
517 -- Check that the constructor has exactly one field
520 tcConDecl unbox_strict DataType tycon tc_tvs -- Data types
521 (ConDecl name _ tvs ctxt details res_ty)
522 = tcTyVarBndrs tvs $ \ tvs' -> do
523 { ctxt' <- tcHsKindedContext ctxt
524 ; (univ_tvs, ex_tvs, eq_preds, data_tc) <- tcResultType tycon tc_tvs tvs' res_ty
526 tc_datacon is_infix field_lbls btys
527 = do { let bangs = map getBangStrictness btys
528 ; arg_tys <- mappM tcHsBangType btys
529 ; buildDataCon (unLoc name) is_infix
530 (argStrictness unbox_strict tycon bangs arg_tys)
531 (map unLoc field_lbls)
532 univ_tvs ex_tvs eq_preds ctxt' arg_tys
534 -- NB: we put data_tc, the type constructor gotten from the constructor
535 -- type signature into the data constructor; that way
536 -- checkValidDataCon can complain if it's wrong.
539 PrefixCon btys -> tc_datacon False [] btys
540 InfixCon bty1 bty2 -> tc_datacon True [] [bty1,bty2]
541 RecCon fields -> tc_datacon False field_names btys
543 (field_names, btys) = unzip fields
547 tcResultType :: TyCon
548 -> [TyVar] -- data T a b c = ...
549 -> [TyVar] -- where MkT :: forall a b c. ...
551 -> TcM ([TyVar], -- Universal
552 [TyVar], -- Existential
553 [(TyVar,Type)], -- Equality predicates
554 TyCon) -- TyCon given in the ResTy
555 -- We don't check that the TyCon given in the ResTy is
556 -- the same as the parent tycon, becuase we are in the middle
557 -- of a recursive knot; so it's postponed until checkValidDataCon
559 tcResultType decl_tycon tc_tvs dc_tvs ResTyH98
560 = return (tc_tvs, dc_tvs, [], decl_tycon)
561 -- In H98 syntax the dc_tvs are the existential ones
562 -- data T a b c = forall d e. MkT ...
563 -- The {a,b,c} are tc_tvs, and {d,e} are dc_tvs
565 tcResultType _ tc_tvs dc_tvs (ResTyGADT res_ty)
566 -- E.g. data T a b c where
567 -- MkT :: forall x y z. T (x,y) z z
569 -- ([a,z,c], [x,y], [a:=:(x,y), c:=:z], T)
571 = do { (dc_tycon, res_tys) <- tcLHsConResTy res_ty
572 -- NB: tc_tvs and dc_tvs are distinct
573 ; let univ_tvs = choose_univs [] tc_tvs res_tys
574 -- Each univ_tv is either a dc_tv or a tc_tv
575 ex_tvs = dc_tvs `minusList` univ_tvs
576 eq_spec = [ (tv, ty) | (tv,ty) <- univ_tvs `zip` res_tys,
578 ; return (univ_tvs, ex_tvs, eq_spec, dc_tycon) }
580 -- choose_univs uses the res_ty itself if it's a type variable
581 -- and hasn't already been used; otherwise it uses one of the tc_tvs
582 choose_univs used tc_tvs []
583 = ASSERT( null tc_tvs ) []
584 choose_univs used (tc_tv:tc_tvs) (res_ty:res_tys)
585 | Just tv <- tcGetTyVar_maybe res_ty, not (tv `elem` used)
586 = tv : choose_univs (tv:used) tc_tvs res_tys
588 = tc_tv : choose_univs used tc_tvs res_tys
591 argStrictness :: Bool -- True <=> -funbox-strict_fields
593 -> [TcType] -> [StrictnessMark]
594 argStrictness unbox_strict tycon bangs arg_tys
595 = ASSERT( length bangs == length arg_tys )
596 zipWith (chooseBoxingStrategy unbox_strict tycon) arg_tys bangs
598 -- We attempt to unbox/unpack a strict field when either:
599 -- (i) The field is marked '!!', or
600 -- (ii) The field is marked '!', and the -funbox-strict-fields flag is on.
602 chooseBoxingStrategy :: Bool -> TyCon -> TcType -> HsBang -> StrictnessMark
603 chooseBoxingStrategy unbox_strict_fields tycon arg_ty bang
605 HsNoBang -> NotMarkedStrict
606 HsStrict | unbox_strict_fields && can_unbox -> MarkedUnboxed
607 HsUnbox | can_unbox -> MarkedUnboxed
608 other -> MarkedStrict
610 can_unbox = case splitTyConApp_maybe arg_ty of
612 Just (arg_tycon, _) -> not (isRecursiveTyCon tycon) &&
613 isProductTyCon arg_tycon
616 %************************************************************************
618 \subsection{Dependency analysis}
620 %************************************************************************
622 Validity checking is done once the mutually-recursive knot has been
623 tied, so we can look at things freely.
626 checkCycleErrs :: [LTyClDecl Name] -> TcM ()
627 checkCycleErrs tyclss
631 = do { mappM_ recClsErr cls_cycles
632 ; failM } -- Give up now, because later checkValidTyCl
633 -- will loop if the synonym is recursive
635 cls_cycles = calcClassCycles tyclss
637 checkValidTyCl :: TyClDecl Name -> TcM ()
638 -- We do the validity check over declarations, rather than TyThings
639 -- only so that we can add a nice context with tcAddDeclCtxt
641 = tcAddDeclCtxt decl $
642 do { thing <- tcLookupLocatedGlobal (tcdLName decl)
643 ; traceTc (text "Validity of" <+> ppr thing)
645 ATyCon tc -> checkValidTyCon tc
646 AClass cl -> checkValidClass cl
647 ; traceTc (text "Done validity of" <+> ppr thing)
650 -------------------------
651 -- For data types declared with record syntax, we require
652 -- that each constructor that has a field 'f'
653 -- (a) has the same result type
654 -- (b) has the same type for 'f'
655 -- module alpha conversion of the quantified type variables
656 -- of the constructor.
658 checkValidTyCon :: TyCon -> TcM ()
661 = checkValidType syn_ctxt syn_rhs
663 = -- Check the context on the data decl
664 checkValidTheta (DataTyCtxt name) (tyConStupidTheta tc) `thenM_`
666 -- Check arg types of data constructors
667 mappM_ (checkValidDataCon tc) data_cons `thenM_`
669 -- Check that fields with the same name share a type
670 mappM_ check_fields groups
673 syn_ctxt = TySynCtxt name
675 syn_rhs = synTyConRhs tc
676 data_cons = tyConDataCons tc
678 groups = equivClasses cmp_fld (concatMap get_fields data_cons)
679 cmp_fld (f1,_) (f2,_) = f1 `compare` f2
680 get_fields con = dataConFieldLabels con `zip` repeat con
681 -- dataConFieldLabels may return the empty list, which is fine
683 -- See Note [GADT record selectors] in MkId.lhs
684 -- We must check (a) that the named field has the same
685 -- type in each constructor
686 -- (b) that those constructors have the same result type
688 -- However, the constructors may have differently named type variable
689 -- and (worse) we don't know how the correspond to each other. E.g.
690 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
691 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
693 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
694 -- result type against other candidates' types BOTH WAYS ROUND.
695 -- If they magically agrees, take the substitution and
696 -- apply them to the latter ones, and see if they match perfectly.
697 check_fields fields@((label, con1) : other_fields)
698 -- These fields all have the same name, but are from
699 -- different constructors in the data type
700 = recoverM (return ()) $ mapM_ checkOne other_fields
701 -- Check that all the fields in the group have the same type
702 -- NB: this check assumes that all the constructors of a given
703 -- data type use the same type variables
705 tvs1 = mkVarSet (dataConAllTyVars con1)
706 res1 = dataConResTys con1
707 fty1 = dataConFieldType con1 label
709 checkOne (_, con2) -- Do it bothways to ensure they are structurally identical
710 = do { checkFieldCompat label con1 con2 tvs1 res1 res2 fty1 fty2
711 ; checkFieldCompat label con2 con1 tvs2 res2 res1 fty2 fty1 }
713 tvs2 = mkVarSet (dataConAllTyVars con2)
714 res2 = dataConResTys con2
715 fty2 = dataConFieldType con2 label
717 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
718 = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
719 ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
721 mb_subst1 = tcMatchTys tvs1 res1 res2
722 mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
724 -------------------------------
725 checkValidDataCon :: TyCon -> DataCon -> TcM ()
726 checkValidDataCon tc con
727 = setSrcSpan (srcLocSpan (getSrcLoc con)) $
728 addErrCtxt (dataConCtxt con) $
729 do { checkTc (dataConTyCon con == tc) (badDataConTyCon con)
730 ; checkValidType ctxt (dataConUserType con) }
732 ctxt = ConArgCtxt (dataConName con)
734 -------------------------------
735 checkValidClass :: Class -> TcM ()
737 = do { -- CHECK ARITY 1 FOR HASKELL 1.4
738 gla_exts <- doptM Opt_GlasgowExts
740 -- Check that the class is unary, unless GlaExs
741 ; checkTc (notNull tyvars) (nullaryClassErr cls)
742 ; checkTc (gla_exts || unary) (classArityErr cls)
744 -- Check the super-classes
745 ; checkValidTheta (ClassSCCtxt (className cls)) theta
747 -- Check the class operations
748 ; mappM_ (check_op gla_exts) op_stuff
750 -- Check that if the class has generic methods, then the
751 -- class has only one parameter. We can't do generic
752 -- multi-parameter type classes!
753 ; checkTc (unary || no_generics) (genericMultiParamErr cls)
755 -- Check that the class has no associated types, unless GlaExs
756 ; checkTc (gla_exts || no_ats) (badATDecl cls)
759 (tyvars, theta, _, op_stuff) = classBigSig cls
760 unary = isSingleton tyvars
761 no_generics = null [() | (_, GenDefMeth) <- op_stuff]
762 no_ats = True -- !!!TODO: determine whether the class has ATs -=chak
764 check_op gla_exts (sel_id, dm)
765 = addErrCtxt (classOpCtxt sel_id tau) $ do
766 { checkValidTheta SigmaCtxt (tail theta)
767 -- The 'tail' removes the initial (C a) from the
768 -- class itself, leaving just the method type
770 ; checkValidType (FunSigCtxt op_name) tau
772 -- Check that the type mentions at least one of
773 -- the class type variables
774 ; checkTc (any (`elemVarSet` tyVarsOfType tau) tyvars)
775 (noClassTyVarErr cls sel_id)
777 -- Check that for a generic method, the type of
778 -- the method is sufficiently simple
779 ; checkTc (dm /= GenDefMeth || validGenericMethodType tau)
780 (badGenericMethodType op_name op_ty)
783 op_name = idName sel_id
784 op_ty = idType sel_id
785 (_,theta1,tau1) = tcSplitSigmaTy op_ty
786 (_,theta2,tau2) = tcSplitSigmaTy tau1
787 (theta,tau) | gla_exts = (theta1 ++ theta2, tau2)
788 | otherwise = (theta1, mkPhiTy (tail theta1) tau1)
789 -- Ugh! The function might have a type like
790 -- op :: forall a. C a => forall b. (Eq b, Eq a) => tau2
791 -- With -fglasgow-exts, we want to allow this, even though the inner
792 -- forall has an (Eq a) constraint. Whereas in general, each constraint
793 -- in the context of a for-all must mention at least one quantified
794 -- type variable. What a mess!
797 ---------------------------------------------------------------------
798 resultTypeMisMatch field_name con1 con2
799 = vcat [sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2,
800 ptext SLIT("have a common field") <+> quotes (ppr field_name) <> comma],
801 nest 2 $ ptext SLIT("but have different result types")]
802 fieldTypeMisMatch field_name con1 con2
803 = sep [ptext SLIT("Constructors") <+> ppr con1 <+> ptext SLIT("and") <+> ppr con2,
804 ptext SLIT("give different types for field"), quotes (ppr field_name)]
806 dataConCtxt con = ptext SLIT("In the definition of data constructor") <+> quotes (ppr con)
808 classOpCtxt sel_id tau = sep [ptext SLIT("When checking the class method:"),
809 nest 2 (ppr sel_id <+> dcolon <+> ppr tau)]
812 = ptext SLIT("No parameters for class") <+> quotes (ppr cls)
815 = vcat [ptext SLIT("Too many parameters for class") <+> quotes (ppr cls),
816 parens (ptext SLIT("Use -fglasgow-exts to allow multi-parameter classes"))]
818 noClassTyVarErr clas op
819 = sep [ptext SLIT("The class method") <+> quotes (ppr op),
820 ptext SLIT("mentions none of the type variables of the class") <+>
821 ppr clas <+> hsep (map ppr (classTyVars clas))]
823 genericMultiParamErr clas
824 = ptext SLIT("The multi-parameter class") <+> quotes (ppr clas) <+>
825 ptext SLIT("cannot have generic methods")
827 badGenericMethodType op op_ty
828 = hang (ptext SLIT("Generic method type is too complex"))
829 4 (vcat [ppr op <+> dcolon <+> ppr op_ty,
830 ptext SLIT("You can only use type variables, arrows, lists, and tuples")])
833 = setSrcSpan (getLoc (head sorted_decls)) $
834 addErr (sep [ptext SLIT("Cycle in type synonym declarations:"),
835 nest 2 (vcat (map ppr_decl sorted_decls))])
837 sorted_decls = sortLocated syn_decls
838 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr decl
841 = setSrcSpan (getLoc (head sorted_decls)) $
842 addErr (sep [ptext SLIT("Cycle in class declarations (via superclasses):"),
843 nest 2 (vcat (map ppr_decl sorted_decls))])
845 sorted_decls = sortLocated cls_decls
846 ppr_decl (L loc decl) = ppr loc <> colon <+> ppr (decl { tcdSigs = [] })
848 sortLocated :: [Located a] -> [Located a]
849 sortLocated things = sortLe le things
851 le (L l1 _) (L l2 _) = l1 <= l2
853 badDataConTyCon data_con
854 = hang (ptext SLIT("Data constructor") <+> quotes (ppr data_con) <+>
855 ptext SLIT("returns type") <+> quotes (ppr (dataConTyCon data_con)))
856 2 (ptext SLIT("instead of its parent type"))
859 = vcat [ ptext SLIT("Illegal generalised algebraic data declaration for") <+> quotes (ppr tc_name)
860 , nest 2 (parens $ ptext SLIT("Use -fglasgow-exts to allow GADTs")) ]
862 badStupidTheta tc_name
863 = ptext SLIT("A data type declared in GADT style cannot have a context:") <+> quotes (ppr tc_name)
865 newtypeConError tycon n
866 = sep [ptext SLIT("A newtype must have exactly one constructor,"),
867 nest 2 $ ptext SLIT("but") <+> quotes (ppr tycon) <+> ptext SLIT("has") <+> speakN n ]
870 = sep [ptext SLIT("A newtype constructor cannot have an existential context,"),
871 nest 2 $ ptext SLIT("but") <+> quotes (ppr con) <+> ptext SLIT("does")]
873 newtypeFieldErr con_name n_flds
874 = sep [ptext SLIT("The constructor of a newtype must have exactly one field"),
875 nest 2 $ ptext SLIT("but") <+> quotes (ppr con_name) <+> ptext SLIT("has") <+> speakN n_flds]
878 = vcat [ ptext SLIT("Illegal associated type declaration in") <+> quotes (ppr cl_name)
879 , nest 2 (parens $ ptext SLIT("Use -fglasgow-exts to allow ATs")) ]
881 emptyConDeclsErr tycon
882 = sep [quotes (ppr tycon) <+> ptext SLIT("has no constructors"),
883 nest 2 $ ptext SLIT("(-fglasgow-exts permits this)")]