2 % (c) The AQUA Project, Glasgow University, 1996-1998
4 \section[TcTyClsDecls]{Typecheck type and class declarations}
11 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlags, DynFlag(..), dopt )
14 import HsSyn ( TyClDecl(..),
15 ConDecl(..), Sig(..), HsPred(..),
16 tyClDeclName, hsTyVarNames, tyClDeclTyVars,
17 isIfaceSigDecl, isClassDecl, isSynDecl, isClassOpSig
19 import RnHsSyn ( RenamedTyClDecl, tyClDeclFVs )
20 import BasicTypes ( RecFlag(..), NewOrData(..) )
21 import HscTypes ( implicitTyThingIds )
22 import Module ( Module )
25 import TcEnv ( TcEnv, RecTcEnv, TcTyThing(..), TyThing(..), TyThingDetails(..),
26 tcExtendKindEnv, tcLookup, tcExtendGlobalEnv, tcExtendGlobalValEnv,
28 import TcTyDecls ( tcTyDecl, kcConDetails, checkValidTyCon )
29 import TcClassDcl ( tcClassDecl1, checkValidClass )
30 import TcInstDcls ( tcAddDeclCtxt )
31 import TcMonoType ( kcHsTyVars, kcHsType, kcHsLiftedSigType, kcHsContext, mkTyClTyVars )
32 import TcMType ( unifyKind, newKindVar, zonkKindEnv )
33 import TcType ( Type, Kind, TcKind, mkArrowKind, liftedTypeKind, zipFunTys )
34 import Type ( splitTyConApp_maybe )
35 import Variance ( calcTyConArgVrcs )
36 import Class ( Class, mkClass, classTyCon )
37 import TyCon ( TyCon, ArgVrcs, AlgTyConFlavour(..),
38 tyConKind, tyConTyVars, tyConDataCons, isNewTyCon,
39 mkSynTyCon, mkAlgTyCon, mkClassTyCon, mkForeignTyCon,
41 import TysWiredIn ( unitTy )
42 import Subst ( substTyWith )
43 import DataCon ( dataConOrigArgTys )
44 import Var ( varName )
46 import Digraph ( stronglyConnComp, SCC(..) )
47 import Name ( Name, getSrcLoc, isTyVarName )
51 import Maybes ( mapMaybe )
52 import ErrUtils ( Message )
53 import HsDecls ( getClassDeclSysNames )
54 import Generics ( mkTyConGenInfo )
58 %************************************************************************
60 \subsection{Type checking for type and class declarations}
62 %************************************************************************
67 tcTyAndClassDecls :: RecTcEnv -- Knot tying stuff
68 -> Module -- Current module
72 tcTyAndClassDecls unf_env this_mod decls
73 = sortByDependency decls `thenTc` \ groups ->
74 tcGroups unf_env this_mod groups
76 tcGroups unf_env this_mod []
77 = tcGetEnv `thenNF_Tc` \ env ->
80 tcGroups unf_env this_mod (group:groups)
81 = tcGroup unf_env this_mod group `thenTc` \ env ->
83 tcGroups unf_env this_mod groups
88 Consider a mutually-recursive group, binding
89 a type constructor T and a class C.
91 Step 1: getInitialKind
92 Construct a KindEnv by binding T and C to a kind variable
95 In that environment, do a kind check
97 Step 3: Zonk the kinds
99 Step 4: buildTyConOrClass
100 Construct an environment binding T to a TyCon and C to a Class.
101 a) Their kinds comes from zonking the relevant kind variable
102 b) Their arity (for synonyms) comes direct from the decl
103 c) The funcional dependencies come from the decl
104 d) The rest comes a knot-tied binding of T and C, returned from Step 4
105 e) The variances of the tycons in the group is calculated from
109 In this environment, walk over the decls, constructing the TyCons and Classes.
110 This uses in a strict way items (a)-(c) above, which is why they must
111 be constructed in Step 4. Feed the results back to Step 4.
112 For this step, pass the is-recursive flag as the wimp-out flag
116 Step 6: Extend environment
117 We extend the type environment with bindings not only for the TyCons and Classes,
118 but also for their "implicit Ids" like data constructors and class selectors
120 Step 7: checkValidTyCl
121 For a recursive group only, check all the decls again, just
122 to check all the side conditions on validity. We could not
123 do this before because we were in a mutually recursive knot.
126 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
127 @TyThing@s. @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
130 tcGroup :: RecTcEnv -> Module -> SCC RenamedTyClDecl -> TcM TcEnv
131 tcGroup unf_env this_mod scc
132 = getDOptsTc `thenTc` \ dflags ->
134 mapNF_Tc getInitialKind decls `thenNF_Tc` \ initial_kinds ->
137 tcExtendKindEnv initial_kinds (mapTc kcTyClDecl decls) `thenTc_`
140 zonkKindEnv initial_kinds `thenNF_Tc` \ final_kinds ->
143 traceTc (text "starting" <+> ppr final_kinds) `thenTc_`
144 fixTc ( \ ~(rec_details_list, _, _) ->
147 kind_env = mkNameEnv final_kinds
148 rec_details = mkNameEnv rec_details_list
150 tyclss, all_tyclss :: [TyThing]
151 tyclss = map (buildTyConOrClass dflags is_rec kind_env
152 rec_vrcs rec_details) decls
154 -- Add the tycons that come from the classes
155 -- We want them in the environment because
156 -- they are mentioned in interface files
157 all_tyclss = [ ATyCon (classTyCon clas) | AClass clas <- tyclss]
160 -- Calculate variances, and (yes!) feed back into buildTyConOrClass.
161 rec_vrcs = calcTyConArgVrcs [tc | ATyCon tc <- all_tyclss]
164 -- Extend the environment with the final
165 -- TyCons/Classes and check the decls
166 tcExtendGlobalEnv all_tyclss $
167 mapTc (tcTyClDecl1 unf_env) decls `thenTc` \ tycls_details ->
170 -- Extend the environment with implicit Ids
171 tcExtendGlobalValEnv (implicitTyThingIds all_tyclss) $
174 tcGetEnv `thenNF_Tc` \ env ->
175 returnTc (tycls_details, tyclss, env)
176 ) `thenTc` \ (_, tyclss, env) ->
179 -- Step 7: Check validity
180 traceTc (text "ready for validity check") `thenTc_`
182 mapTc_ (checkValidTyCl this_mod) decls
184 traceTc (text "done") `thenTc_`
190 AcyclicSCC _ -> NonRecursive
191 CyclicSCC _ -> Recursive
194 AcyclicSCC decl -> [decl]
195 CyclicSCC decls -> decls
197 tcTyClDecl1 unf_env decl
198 | isClassDecl decl = tcAddDeclCtxt decl (tcClassDecl1 unf_env decl)
199 | otherwise = tcAddDeclCtxt decl (tcTyDecl unf_env decl)
201 checkValidTyCl this_mod decl
202 = tcLookup (tcdName decl) `thenNF_Tc` \ (AGlobal thing) ->
203 if not (isLocalThing this_mod thing) then
204 -- Don't bother to check validity for non-local things
209 ATyCon tc -> checkValidTyCon tc
210 AClass cl -> checkValidClass cl
214 %************************************************************************
216 \subsection{Step 1: Initial environment}
218 %************************************************************************
221 getInitialKind :: RenamedTyClDecl -> NF_TcM (Name, TcKind)
223 = kcHsTyVars (tyClDeclTyVars decl) `thenNF_Tc` \ arg_kinds ->
224 newKindVar `thenNF_Tc` \ result_kind ->
225 returnNF_Tc (tcdName decl, mk_kind arg_kinds result_kind)
227 mk_kind tvs_w_kinds res_kind = foldr (mkArrowKind . snd) res_kind tvs_w_kinds
231 %************************************************************************
233 \subsection{Step 2: Kind checking}
235 %************************************************************************
237 We need to kind check all types in the mutually recursive group
238 before we know the kind of the type variables. For example:
241 op :: D b => a -> b -> b
244 bop :: (Monad c) => ...
246 Here, the kind of the locally-polymorphic type variable "b"
247 depends on *all the uses of class D*. For example, the use of
248 Monad c in bop's type signature means that D must have kind Type->Type.
251 kcTyClDecl :: RenamedTyClDecl -> TcM ()
253 kcTyClDecl decl@(TySynonym {tcdSynRhs = rhs})
254 = kcTyClDeclBody decl $ \ result_kind ->
255 kcHsType rhs `thenTc` \ rhs_kind ->
256 unifyKind result_kind rhs_kind
258 kcTyClDecl (ForeignType {}) = returnTc ()
260 kcTyClDecl decl@(TyData {tcdND = new_or_data, tcdCtxt = context, tcdCons = con_decls})
261 = kcTyClDeclBody decl $ \ result_kind ->
262 kcHsContext context `thenTc_`
263 mapTc_ kc_con_decl con_decls
265 kc_con_decl (ConDecl _ _ ex_tvs ex_ctxt details loc)
266 = kcHsTyVars ex_tvs `thenNF_Tc` \ kind_env ->
267 tcExtendKindEnv kind_env $
268 kcConDetails new_or_data ex_ctxt details
270 kcTyClDecl decl@(ClassDecl {tcdCtxt = context, tcdSigs = class_sigs})
271 = kcTyClDeclBody decl $ \ result_kind ->
272 kcHsContext context `thenTc_`
273 mapTc_ kc_sig (filter isClassOpSig class_sigs)
275 kc_sig (ClassOpSig _ _ op_ty loc) = kcHsLiftedSigType op_ty
277 kcTyClDeclBody :: RenamedTyClDecl -> (Kind -> TcM a) -> TcM a
278 -- Extend the env with bindings for the tyvars, taken from
279 -- the kind of the tycon/class. Give it to the thing inside, and
280 -- check the result kind matches
281 kcTyClDeclBody decl thing_inside
282 = tcAddDeclCtxt decl $
283 tcLookup (tcdName decl) `thenNF_Tc` \ thing ->
286 AGlobal (ATyCon tc) -> tyConKind tc
287 AGlobal (AClass cl) -> tyConKind (classTyCon cl)
289 -- For some odd reason, a class doesn't include its kind
291 (tyvars_w_kinds, result_kind) = zipFunTys (hsTyVarNames (tyClDeclTyVars decl)) kind
293 tcExtendKindEnv tyvars_w_kinds (thing_inside result_kind)
298 %************************************************************************
300 \subsection{Step 4: Building the tycon/class}
302 %************************************************************************
307 -> RecFlag -> NameEnv Kind
308 -> FiniteMap TyCon ArgVrcs -> NameEnv TyThingDetails
309 -> RenamedTyClDecl -> TyThing
311 buildTyConOrClass dflags is_rec kenv rec_vrcs rec_details
312 (TySynonym {tcdName = tycon_name, tcdTyVars = tyvar_names})
315 tycon = mkSynTyCon tycon_name tycon_kind arity tyvars rhs_ty argvrcs
316 tycon_kind = lookupNameEnv_NF kenv tycon_name
317 arity = length tyvar_names
318 tyvars = mkTyClTyVars tycon_kind tyvar_names
319 SynTyDetails rhs_ty = lookupNameEnv_NF rec_details tycon_name
320 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
322 buildTyConOrClass dflags is_rec kenv rec_vrcs rec_details
323 (TyData {tcdND = data_or_new, tcdName = tycon_name, tcdTyVars = tyvar_names,
324 tcdNCons = nconstrs, tcdSysNames = sys_names})
327 tycon = mkAlgTyCon tycon_name tycon_kind tyvars ctxt argvrcs
328 data_cons nconstrs sel_ids
329 flavour is_rec gen_info
331 gen_info | not (dopt Opt_Generics dflags) = Nothing
332 | otherwise = mkTyConGenInfo tycon sys_names
334 DataTyDetails ctxt data_cons sel_ids = lookupNameEnv_NF rec_details tycon_name
336 tycon_kind = lookupNameEnv_NF kenv tycon_name
337 tyvars = mkTyClTyVars tycon_kind tyvar_names
338 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
340 -- Watch out! mkTyConApp asks whether the tycon is a NewType,
341 -- so flavour has to be able to answer this question without consulting rec_details
342 flavour = case data_or_new of
343 NewType -> NewTyCon (mkNewTyConRep tycon)
344 DataType | all (null . dataConOrigArgTys) data_cons -> EnumTyCon
345 | otherwise -> DataTyCon
346 -- NB (null . dataConOrigArgTys). It used to say isNullaryDataCon
347 -- but that looks at the *representation* arity, and that in turn
348 -- depends on deciding whether to unpack the args, and that
349 -- depends on whether it's a data type or a newtype --- so
350 -- in the recursive case we can get a loop. This version is simple!
352 buildTyConOrClass dflags is_rec kenv rec_vrcs rec_details
353 (ForeignType {tcdName = tycon_name, tcdExtName = tycon_ext_name})
354 = ATyCon (mkForeignTyCon tycon_name tycon_ext_name liftedTypeKind 0 [])
356 buildTyConOrClass dflags is_rec kenv rec_vrcs rec_details
357 (ClassDecl {tcdName = class_name, tcdTyVars = tyvar_names,
358 tcdFDs = fundeps, tcdSysNames = name_list} )
361 (tycon_name, _, _, _) = getClassDeclSysNames name_list
362 clas = mkClass class_name tyvars fds
363 sc_theta sc_sel_ids op_items
366 tycon = mkClassTyCon tycon_name class_kind tyvars
368 clas -- Yes! It's a dictionary
371 -- A class can be recursive, and in the case of newtypes
372 -- this matters. For example
373 -- class C a where { op :: C b => a -> b -> Int }
374 -- Because C has only one operation, it is represented by
375 -- a newtype, and it should be a *recursive* newtype.
376 -- [If we don't make it a recursive newtype, we'll expand the
377 -- newtype like a synonym, but that will lead toan inifinite type
379 ClassDetails sc_theta sc_sel_ids op_items dict_con = lookupNameEnv_NF rec_details class_name
381 class_kind = lookupNameEnv_NF kenv class_name
382 tyvars = mkTyClTyVars class_kind tyvar_names
383 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
385 flavour = case dataConOrigArgTys dict_con of
386 -- The tyvars in the datacon are the same as in the class
387 [rep_ty] -> NewTyCon rep_ty
390 -- We can find the functional dependencies right away,
391 -- and it is vital to do so. Why? Because in the next pass
392 -- we check for ambiguity in all the type signatures, and we
393 -- need the functional dependcies to be done by then
394 fds = [(map lookup xs, map lookup ys) | (xs,ys) <- fundeps]
395 tyvar_env = mkNameEnv [(varName tv, tv) | tv <- tyvars]
396 lookup = lookupNameEnv_NF tyvar_env
398 bogusVrcs = panic "Bogus tycon arg variances"
402 mkNewTyConRep :: TyCon -- The original type constructor
403 -> Type -- Chosen representation type
404 -- (guaranteed not to be another newtype)
406 -- Find the representation type for this newtype TyCon
408 -- The non-recursive newtypes are easy, because they look transparent
409 -- to splitTyConApp_maybe, but recursive ones really are represented as
410 -- TyConApps (see TypeRep).
412 -- The trick is to to deal correctly with recursive newtypes
413 -- such as newtype T = MkT T
418 -- Invariant: tc is a NewTyCon
419 -- tcs have been seen before
421 | tc `elem` tcs = unitTy
424 rep_ty = head (dataConOrigArgTys (head (tyConDataCons tc)))
426 case splitTyConApp_maybe rep_ty of
428 Just (tc', tys) | not (isNewTyCon tc') -> rep_ty
429 | otherwise -> go1 (tc:tcs) tc' tys
431 go1 tcs tc tys = substTyWith (tyConTyVars tc) tys (go tcs tc)
434 %************************************************************************
436 \subsection{Dependency analysis}
438 %************************************************************************
443 sortByDependency :: [RenamedTyClDecl] -> TcM [SCC RenamedTyClDecl]
444 sortByDependency decls
445 = let -- CHECK FOR CLASS CYCLES
446 cls_sccs = stronglyConnComp (mapMaybe mkClassEdges tycl_decls)
447 cls_cycles = [ decls | CyclicSCC decls <- cls_sccs]
449 checkTc (null cls_cycles) (classCycleErr cls_cycles) `thenTc_`
451 let -- CHECK FOR SYNONYM CYCLES
452 syn_sccs = stronglyConnComp (filter is_syn_decl edges)
453 syn_cycles = [ decls | CyclicSCC decls <- syn_sccs]
456 checkTc (null syn_cycles) (typeCycleErr syn_cycles) `thenTc_`
458 -- DO THE MAIN DEPENDENCY ANALYSIS
460 decl_sccs = stronglyConnComp edges
464 tycl_decls = filter (not . isIfaceSigDecl) decls
465 edges = map mkEdges tycl_decls
467 is_syn_decl (d, _, _) = isSynDecl d
470 Edges in Type/Class decls
471 ~~~~~~~~~~~~~~~~~~~~~~~~~
474 tyClDeclFTVs :: RenamedTyClDecl -> [Name]
475 -- Find the free non-tyvar vars
476 tyClDeclFTVs d = foldNameSet add [] (tyClDeclFVs d)
478 add n fvs | isTyVarName n = fvs
479 | otherwise = n : fvs
481 ----------------------------------------------------
482 -- mk_cls_edges looks only at the context of class decls
483 -- Its used when we are figuring out if there's a cycle in the
484 -- superclass hierarchy
486 mkClassEdges :: RenamedTyClDecl -> Maybe (RenamedTyClDecl, Name, [Name])
488 mkClassEdges decl@(ClassDecl {tcdCtxt = ctxt, tcdName = name}) = Just (decl, name, [c | HsClassP c _ <- ctxt])
489 mkClassEdges other_decl = Nothing
491 mkEdges :: RenamedTyClDecl -> (RenamedTyClDecl, Name, [Name])
492 mkEdges decl = (decl, tyClDeclName decl, tyClDeclFTVs decl)
496 %************************************************************************
498 \subsection{Error management
500 %************************************************************************
503 typeCycleErr, classCycleErr :: [[RenamedTyClDecl]] -> Message
505 typeCycleErr syn_cycles
506 = vcat (map (pp_cycle "Cycle in type declarations:") syn_cycles)
508 classCycleErr cls_cycles
509 = vcat (map (pp_cycle "Cycle in class declarations:") cls_cycles)
513 4 (vcat (map pp_decl decls))
516 = hsep [quotes (ppr name), ptext SLIT("at"), ppr (getSrcLoc name)]
518 name = tyClDeclName decl