2 % (c) The AQUA Project, Glasgow University, 1996-1998
4 \section[TcTyClsDecls]{Typecheck type and class declarations}
11 #include "HsVersions.h"
13 import HsSyn ( HsDecl(..), TyClDecl(..),
14 HsType(..), HsTyVarBndr,
15 ConDecl(..), ConDetails(..),
16 Sig(..), HsPred(..), HsTupCon(..),
17 tyClDeclName, hsTyVarNames, isClassDecl, isSynDecl, isClassOpSig, getBangType
19 import RnHsSyn ( RenamedHsDecl, RenamedTyClDecl, listTyCon_name )
20 import BasicTypes ( RecFlag(..), NewOrData(..) )
23 import TcEnv ( TcEnv, TyThing(..), TyThingDetails(..), tyThingKind,
24 tcExtendTypeEnv, tcExtendKindEnv, tcLookupGlobal
26 import TcTyDecls ( tcTyDecl1, kcConDetails, mkNewTyConRep )
27 import TcClassDcl ( tcClassDecl1 )
28 import TcMonoType ( kcHsTyVars, kcHsType, kcHsBoxedSigType, kcHsContext, mkTyClTyVars )
29 import TcType ( TcKind, newKindVar, zonkKindEnv )
31 import TcUnify ( unifyKind )
32 import TcInstDcls ( tcAddDeclCtxt )
33 import Type ( Kind, mkArrowKind, boxedTypeKind, zipFunTys )
34 import Variance ( calcTyConArgVrcs )
35 import Class ( Class, mkClass, classTyCon )
36 import TyCon ( TyCon, ArgVrcs, AlgTyConFlavour(..), mkSynTyCon, mkAlgTyConRep, mkClassTyCon )
37 import DataCon ( isNullaryDataCon )
38 import Var ( varName )
40 import Digraph ( stronglyConnComp, SCC(..) )
41 import Name ( Name, NamedThing(..), NameEnv, getSrcLoc, isTvOcc, nameOccName,
42 mkNameEnv, lookupNameEnv_NF
45 import Maybes ( mapMaybe, catMaybes )
46 import UniqSet ( emptyUniqSet, unitUniqSet, unionUniqSets,
47 unionManyUniqSets, uniqSetToList )
48 import ErrUtils ( Message )
49 import Unique ( Unique, Uniquable(..) )
50 import HsDecls ( fromClassDeclNameList )
51 import Generics ( mkTyConGenInfo )
55 %************************************************************************
57 \subsection{Type checking for type and class declarations}
59 %************************************************************************
64 tcTyAndClassDecls :: TcEnv -- Knot tying stuff
68 tcTyAndClassDecls unf_env decls
69 = sortByDependency decls `thenTc` \ groups ->
70 tcGroups unf_env groups
73 = tcGetEnv `thenNF_Tc` \ env ->
76 tcGroups unf_env (group:groups)
77 = tcGroup unf_env group `thenTc` \ env ->
79 tcGroups unf_env groups
84 Consider a mutually-recursive group, binding
85 a type constructor T and a class C.
87 Step 1: getInitialKind
88 Construct a KindEnv by binding T and C to a kind variable
91 In that environment, do a kind check
93 Step 3: Zonk the kinds
95 Step 4: buildTyConOrClass
96 Construct an environment binding T to a TyCon and C to a Class.
97 a) Their kinds comes from zonking the relevant kind variable
98 b) Their arity (for synonyms) comes direct from the decl
99 c) The funcional dependencies come from the decl
100 d) The rest comes a knot-tied binding of T and C, returned from Step 4
101 e) The variances of the tycons in the group is calculated from
105 In this environment, walk over the decls, constructing the TyCons and Classes.
106 This uses in a strict way items (a)-(c) above, which is why they must
107 be constructed in Step 4.
108 Feed the results back to Step 4.
110 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
111 @TyThing@s. @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
114 tcGroup :: TcEnv -> SCC RenamedTyClDecl -> TcM TcEnv
117 mapNF_Tc getInitialKind decls `thenNF_Tc` \ initial_kinds ->
120 tcExtendKindEnv initial_kinds (mapTc kcTyClDecl decls) `thenTc_`
123 zonkKindEnv initial_kinds `thenNF_Tc` \ final_kinds ->
126 fixTc ( \ ~(rec_details_list, _) ->
129 kind_env = mkNameEnv final_kinds
130 rec_details = mkNameEnv rec_details_list
132 tyclss, all_tyclss :: [(Name, TyThing)]
133 tyclss = map (buildTyConOrClass is_rec kind_env rec_vrcs rec_details) decls
135 -- Add the tycons that come from the classes
136 -- We want them in the environment because
137 -- they are mentioned in interface files
138 all_tyclss = [ (getName tycon, ATyCon tycon) | (_, AClass clas) <- tyclss,
139 let tycon = classTyCon clas
142 -- Calculate variances, and (yes!) feed back into buildTyConOrClass.
143 rec_vrcs = calcTyConArgVrcs [tc | (_, ATyCon tc) <- all_tyclss]
146 tcExtendGlobalEnv all_tyclss $
147 mapTc (tcTyClDecl1 unf_env) decls `thenTc` \ tycls_details ->
148 tcGetEnv `thenNF_Tc` \ env ->
149 returnTc (tycls_details, env)
150 ) `thenTc` \ (_, env) ->
154 AcyclicSCC _ -> NonRecursive
155 CyclicSCC _ -> Recursive
158 AcyclicSCC decl -> [decl]
159 CyclicSCC decls -> decls
161 tcTyClDecl1 unf_env decl
162 = tcAddDeclCtxt decl $
163 if isClassDecl decl then
164 tcClassDecl1 unf_env decl
170 %************************************************************************
172 \subsection{Step 1: Initial environment}
174 %************************************************************************
177 getInitialKind :: RenamedTyClDecl -> NF_TcM (Name, TcKind)
178 getInitialKind (TySynonym name tyvars _ _)
179 = kcHsTyVars tyvars `thenNF_Tc` \ arg_kinds ->
180 newKindVar `thenNF_Tc` \ result_kind ->
181 returnNF_Tc (name, mk_kind arg_kinds result_kind)
183 getInitialKind (TyData _ _ name tyvars _ _ _ _ _ _ _)
184 = kcHsTyVars tyvars `thenNF_Tc` \ arg_kinds ->
185 returnNF_Tc (name, mk_kind arg_kinds boxedTypeKind)
187 getInitialKind (ClassDecl _ name tyvars _ _ _ _ _ _ )
188 = kcHsTyVars tyvars `thenNF_Tc` \ arg_kinds ->
189 returnNF_Tc (name, mk_kind arg_kinds boxedTypeKind)
191 mk_kind tvs_w_kinds res_kind = foldr (mkArrowKind . snd) res_kind tvs_w_kinds
195 %************************************************************************
197 \subsection{Step 2: Kind checking}
199 %************************************************************************
201 We need to kind check all types in the mutually recursive group
202 before we know the kind of the type variables. For example:
205 op :: D b => a -> b -> b
208 bop :: (Monad c) => ...
210 Here, the kind of the locally-polymorphic type variable "b"
211 depends on *all the uses of class D*. For example, the use of
212 Monad c in bop's type signature means that D must have kind Type->Type.
215 kcTyClDecl :: RenamedTyClDecl -> TcM ()
217 kcTyClDecl decl@(TySynonym tycon_name hs_tyvars rhs loc)
218 = tcAddDeclCtxt decl $
219 kcTyClDeclBody tycon_name hs_tyvars $ \ result_kind ->
220 kcHsType rhs `thenTc` \ rhs_kind ->
221 unifyKind result_kind rhs_kind
223 kcTyClDecl decl@(TyData _ context tycon_name hs_tyvars con_decls _ _ _ loc _ _)
224 = tcAddDeclCtxt decl $
225 kcTyClDeclBody tycon_name hs_tyvars $ \ result_kind ->
226 kcHsContext context `thenTc_`
227 mapTc_ kc_con_decl con_decls
229 kc_con_decl (ConDecl _ _ ex_tvs ex_ctxt details loc)
231 kcHsTyVars ex_tvs `thenNF_Tc` \ kind_env ->
232 tcExtendKindEnv kind_env $
233 kcConDetails ex_ctxt details
235 kcTyClDecl decl@(ClassDecl context class_name
236 hs_tyvars fundeps class_sigs
238 = tcAddDeclCtxt decl $
239 kcTyClDeclBody class_name hs_tyvars $ \ result_kind ->
240 kcHsContext context `thenTc_`
241 mapTc_ kc_sig (filter isClassOpSig class_sigs)
243 kc_sig (ClassOpSig _ _ op_ty loc) = tcAddSrcLoc loc (kcHsBoxedSigType op_ty)
245 kcTyClDeclBody :: Name -> [HsTyVarBndr Name] -- Kind of the tycon/cls and its tyvars
246 -> (Kind -> TcM a) -- Thing inside
248 -- Extend the env with bindings for the tyvars, taken from
249 -- the kind of the tycon/class. Give it to the thing inside, and
250 -- check the result kind matches
251 kcTyClDeclBody tc_name hs_tyvars thing_inside
252 = tcLookupGlobal tc_name `thenNF_Tc` \ thing ->
255 ATyCon tc -> tyConKind tc
256 AClass cl -> tyConKind (classTyCon cl)
257 -- For some odd reason, a class doesn't include its kind
259 (tyvars_w_kinds, result_kind) = zipFunTys (hsTyVarNames hs_tyvars) kind
261 tcExtendKindEnv tyvars_w_kinds (thing_inside result_kind)
265 %************************************************************************
267 \subsection{Step 4: Building the tycon/class}
269 %************************************************************************
273 :: RecFlag -> NameEnv Kind
274 -> FiniteMap TyCon ArgVrcs -> NameEnv TyThingDetails
275 -> RenamedTyClDecl -> (Name, TyThing)
276 -- Can't fail; the only reason it's in the monad
277 -- is so it can zonk the kinds
279 buildTyConOrClass is_rec kenv rec_vrcs rec_details
280 (TySynonym tycon_name tyvar_names rhs src_loc)
281 = (tycon_name, ATyCon tycon)
283 tycon = mkSynTyCon tycon_name tycon_kind arity tyvars rhs_ty argvrcs
284 tycon_kind = lookupNameEnv_NF kenv tycon_name
285 arity = length tyvar_names
286 tyvars = mkTyClTyVars tycon_kind tyvar_names
287 SynTyDetails rhs_ty = lookupNameEnv_NF rec_details tycon_name
288 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
290 buildTyConOrClass is_rec kenv rec_vrcs rec_details
291 (TyData data_or_new context tycon_name tyvar_names _ nconstrs _ _ src_loc name1 name2)
292 = (tycon_name, ATyCon tycon)
294 tycon = mkAlgTyConRep tycon_name tycon_kind tyvars ctxt argvrcs
297 flavour is_rec gen_info
298 gen_info = mkTyConGenInfo tycon name1 name2
300 DataTyDetails ctxt data_cons derived_classes = lookupNameEnv_NF rec_details tycon_name
302 tycon_kind = lookupNameEnv_NF kenv tycon_name
303 tyvars = mkTyClTyVars tycon_kind tyvar_names
304 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
306 flavour = case data_or_new of
307 NewType -> NewTyCon (mkNewTyConRep tycon)
308 DataType | all isNullaryDataCon data_cons -> EnumTyCon
309 | otherwise -> DataTyCon
311 buildTyConOrClass is_rec kenv rec_vrcs rec_details
312 (ClassDecl context class_name
313 tyvar_names fundeps class_sigs def_methods pragmas
315 = (class_name, AClass clas)
317 (tycon_name, _, _, _) = fromClassDeclNameList name_list
318 clas = mkClass class_name tyvars fds
319 sc_theta sc_sel_ids op_items
322 tycon = mkClassTyCon tycon_name class_kind tyvars
324 clas -- Yes! It's a dictionary
327 ClassDetails sc_theta sc_sel_ids op_items dict_con = lookupNameEnv_NF rec_details class_name
329 class_kind = lookupNameEnv_NF kenv class_name
330 tyvars = mkTyClTyVars class_kind tyvar_names
331 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
332 n_fields = length sc_sel_ids + length op_items
334 flavour | n_fields == 1 = NewTyCon (mkNewTyConRep tycon)
335 | otherwise = DataTyCon
337 -- We can find the functional dependencies right away,
338 -- and it is vital to do so. Why? Because in the next pass
339 -- we check for ambiguity in all the type signatures, and we
340 -- need the functional dependcies to be done by then
341 fds = [(map lookup xs, map lookup ys) | (xs,ys) <- fundeps]
342 tyvar_env = mkNameEnv [(varName tv, tv) | tv <- tyvars]
343 lookup = lookupNameEnv_NF tyvar_env
345 bogusVrcs = panic "Bogus tycon arg variances"
349 %************************************************************************
351 \subsection{Dependency analysis}
353 %************************************************************************
358 sortByDependency :: [RenamedHsDecl] -> TcM [SCC RenamedTyClDecl]
359 sortByDependency decls
360 = let -- CHECK FOR CLASS CYCLES
361 cls_sccs = stronglyConnComp (mapMaybe mk_cls_edges tycl_decls)
362 cls_cycles = [ decls | CyclicSCC decls <- cls_sccs]
364 checkTc (null cls_cycles) (classCycleErr cls_cycles) `thenTc_`
366 let -- CHECK FOR SYNONYM CYCLES
367 syn_sccs = stronglyConnComp (filter is_syn_decl edges)
368 syn_cycles = [ decls | CyclicSCC decls <- syn_sccs]
371 checkTc (null syn_cycles) (typeCycleErr syn_cycles) `thenTc_`
373 -- DO THE MAIN DEPENDENCY ANALYSIS
375 decl_sccs = stronglyConnComp edges
379 tycl_decls = [d | TyClD d <- decls]
380 edges = map mk_edges tycl_decls
382 is_syn_decl (d, _, _) = isSynDecl d
385 Edges in Type/Class decls
386 ~~~~~~~~~~~~~~~~~~~~~~~~~
389 ----------------------------------------------------
390 -- mk_cls_edges looks only at the context of class decls
391 -- Its used when we are figuring out if there's a cycle in the
392 -- superclass hierarchy
394 mk_cls_edges :: RenamedTyClDecl -> Maybe (RenamedTyClDecl, Unique, [Unique])
396 mk_cls_edges decl@(ClassDecl ctxt name _ _ _ _ _ _ _)
397 = Just (decl, getUnique name, map getUnique (catMaybes (map get_clas ctxt)))
398 mk_cls_edges other_decl
401 ----------------------------------------------------
402 mk_edges :: RenamedTyClDecl -> (RenamedTyClDecl, Unique, [Unique])
404 mk_edges decl@(TyData _ ctxt name _ condecls _ derivs _ _ _ _)
405 = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
406 get_cons condecls `unionUniqSets`
409 mk_edges decl@(TySynonym name _ rhs _)
410 = (decl, getUnique name, uniqSetToList (get_ty rhs))
412 mk_edges decl@(ClassDecl ctxt name _ _ sigs _ _ _ _)
413 = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
417 ----------------------------------------------------
418 get_ctxt ctxt = unionManyUniqSets (map set_name (catMaybes (map get_clas ctxt)))
419 get_clas (HsPClass clas _) = Just clas
422 ----------------------------------------------------
423 get_deriv Nothing = emptyUniqSet
424 get_deriv (Just clss) = unionManyUniqSets (map set_name clss)
426 ----------------------------------------------------
427 get_cons cons = unionManyUniqSets (map get_con cons)
429 ----------------------------------------------------
430 get_con (ConDecl _ _ _ ctxt details _)
431 = get_ctxt ctxt `unionUniqSets` get_con_details details
433 ----------------------------------------------------
434 get_con_details (VanillaCon btys) = unionManyUniqSets (map get_bty btys)
435 get_con_details (InfixCon bty1 bty2) = unionUniqSets (get_bty bty1) (get_bty bty2)
436 get_con_details (RecCon nbtys) = unionManyUniqSets (map (get_bty.snd) nbtys)
438 ----------------------------------------------------
439 get_bty bty = get_ty (getBangType bty)
441 ----------------------------------------------------
442 get_ty (HsTyVar name) | isTvOcc (nameOccName name) = emptyUniqSet
443 | otherwise = set_name name
444 get_ty (HsAppTy ty1 ty2) = unionUniqSets (get_ty ty1) (get_ty ty2)
445 get_ty (HsFunTy ty1 ty2) = unionUniqSets (get_ty ty1) (get_ty ty2)
446 get_ty (HsListTy ty) = set_name listTyCon_name `unionUniqSets` get_ty ty
447 get_ty (HsTupleTy (HsTupCon n _) tys) = set_name n `unionUniqSets` get_tys tys
448 get_ty (HsUsgTy _ ty) = get_ty ty
449 get_ty (HsUsgForAllTy _ ty) = get_ty ty
450 get_ty (HsForAllTy _ ctxt mty) = get_ctxt ctxt `unionUniqSets` get_ty mty
451 get_ty (HsPredTy (HsPClass name _)) = set_name name
452 get_ty (HsPredTy (HsPIParam _ _)) = emptyUniqSet -- I think
454 ----------------------------------------------------
455 get_tys tys = unionManyUniqSets (map get_ty tys)
457 ----------------------------------------------------
459 = unionManyUniqSets (map get_sig sigs)
461 get_sig (ClassOpSig _ _ ty _) = get_ty ty
462 get_sig (FixSig _) = emptyUniqSet
463 get_sig other = panic "TcTyClsDecls:get_sig"
465 ----------------------------------------------------
466 set_name name = unitUniqSet (getUnique name)
470 %************************************************************************
472 \subsection{Error management
474 %************************************************************************
477 typeCycleErr, classCycleErr :: [[RenamedTyClDecl]] -> Message
479 typeCycleErr syn_cycles
480 = vcat (map (pp_cycle "Cycle in type declarations:") syn_cycles)
482 classCycleErr cls_cycles
483 = vcat (map (pp_cycle "Cycle in class declarations:") cls_cycles)
487 4 (vcat (map pp_decl decls))
490 = hsep [quotes (ppr name), ptext SLIT("at"), ppr (getSrcLoc name)]
492 name = tyClDeclName decl