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 ( ValueEnv, TyThing(..), TyThingDetails(..), tyThingKind,
24 tcExtendTypeEnv, tcExtendKindEnv, tcLookupTy
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 Type ( Kind, mkArrowKind, boxedTypeKind, zipFunTys )
33 import Variance ( calcTyConArgVrcs )
34 import Class ( Class, mkClass, classTyCon )
35 import TyCon ( TyCon, ArgVrcs, AlgTyConFlavour(..), mkSynTyCon, mkAlgTyCon, mkClassTyCon )
36 import DataCon ( isNullaryDataCon )
37 import Var ( varName )
39 import Digraph ( stronglyConnComp, SCC(..) )
40 import Name ( Name, NamedThing(..), NameEnv, getSrcLoc, isTvOcc, nameOccName,
41 mkNameEnv, lookupNameEnv_NF
44 import Maybes ( mapMaybe, catMaybes )
45 import UniqSet ( emptyUniqSet, unitUniqSet, unionUniqSets,
46 unionManyUniqSets, uniqSetToList )
47 import ErrUtils ( Message )
48 import Unique ( Unique, Uniquable(..) )
52 %************************************************************************
54 \subsection{Type checking for type and class declarations}
56 %************************************************************************
61 tcTyAndClassDecls :: ValueEnv -- Knot tying stuff
65 tcTyAndClassDecls unf_env decls
66 = sortByDependency decls `thenTc` \ groups ->
67 tcGroups unf_env groups
70 = tcGetEnv `thenNF_Tc` \ env ->
73 tcGroups unf_env (group:groups)
74 = tcGroup unf_env group `thenTc` \ env ->
76 tcGroups unf_env groups
82 Consider a mutually-recursive group, binding
83 a type constructor T and a class C.
85 Step 1: getInitialKind
86 Construct a KindEnv by binding T and C to a kind variable
89 In that environment, do a kind check
91 Step 3: Zonk the kinds
93 Step 4: buildTyConOrClass
94 Construct an environment binding T to a TyCon and C to a Class.
95 a) Their kinds comes from zonking the relevant kind variable
96 b) Their arity (for synonyms) comes direct from the decl
97 c) The funcional dependencies come from the decl
98 d) The rest comes a knot-tied binding of T and C, returned from Step 4
99 e) The variances of the tycons in the group is calculated from
103 In this environment, walk over the decls, constructing the TyCons and Classes.
104 This uses in a strict way items (a)-(c) above, which is why they must
105 be constructed in Step 4.
106 Feed the results back to Step 4.
108 The knot-tying parameters: @rec_details_list@ is an alist mapping @Name@s to
109 @TyThing@s. @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
112 tcGroup :: ValueEnv -> SCC RenamedTyClDecl -> TcM s TcEnv
115 mapNF_Tc getInitialKind decls `thenNF_Tc` \ initial_kinds ->
118 tcExtendKindEnv initial_kinds (mapTc kcTyClDecl decls) `thenTc_`
121 zonkKindEnv initial_kinds `thenNF_Tc` \ final_kinds ->
124 fixTc ( \ ~(rec_details_list, _) ->
127 kind_env = mkNameEnv final_kinds
128 rec_details = mkNameEnv rec_details_list
130 tyclss, all_tyclss :: [(Name, TyThing)]
131 tyclss = map (buildTyConOrClass is_rec kind_env rec_vrcs rec_details) decls
133 -- Add the tycons that come from the classes
134 -- We want them in the environment because
135 -- they are mentioned in interface files
136 all_tyclss = [ (getName tycon, ATyCon tycon) | (_, AClass clas) <- tyclss,
137 let tycon = classTyCon clas
140 -- Calculate variances, and (yes!) feed back into buildTyConOrClass.
141 rec_vrcs = calcTyConArgVrcs [tc | (_, ATyCon tc) <- all_tyclss]
144 tcExtendTypeEnv all_tyclss $
145 mapTc (tcTyClDecl1 unf_env) decls `thenTc` \ tycls_details ->
146 tcGetEnv `thenNF_Tc` \ env ->
147 returnTc (tycls_details, env)
148 ) `thenTc` \ (_, env) ->
152 AcyclicSCC _ -> NonRecursive
153 CyclicSCC _ -> Recursive
156 AcyclicSCC decl -> [decl]
157 CyclicSCC decls -> decls
159 tcTyClDecl1 :: ValueEnv -> RenamedTyClDecl -> TcM s (Name, TyThingDetails)
161 tcTyClDecl1 unf_env decl
162 | isClassDecl decl = tcClassDecl1 unf_env decl
163 | otherwise = tcTyDecl1 decl
167 %************************************************************************
169 \subsection{Step 1: Initial environment}
171 %************************************************************************
174 getInitialKind :: RenamedTyClDecl -> NF_TcM s (Name, TcKind)
175 getInitialKind (TySynonym name tyvars _ _)
176 = kcHsTyVars tyvars `thenNF_Tc` \ arg_kinds ->
177 newKindVar `thenNF_Tc` \ result_kind ->
178 returnNF_Tc (name, mk_kind arg_kinds result_kind)
180 getInitialKind (TyData _ _ name tyvars _ _ _ _ _)
181 = kcHsTyVars tyvars `thenNF_Tc` \ arg_kinds ->
182 returnNF_Tc (name, mk_kind arg_kinds boxedTypeKind)
184 getInitialKind (ClassDecl _ name tyvars _ _ _ _ _ _ _ _ _)
185 = kcHsTyVars tyvars `thenNF_Tc` \ arg_kinds ->
186 returnNF_Tc (name, mk_kind arg_kinds boxedTypeKind)
188 mk_kind tvs_w_kinds res_kind = foldr (mkArrowKind . snd) res_kind tvs_w_kinds
192 %************************************************************************
194 \subsection{Step 2: Kind checking}
196 %************************************************************************
198 We need to kind check all types in the mutually recursive group
199 before we know the kind of the type variables. For example:
202 op :: D b => a -> b -> b
205 bop :: (Monad c) => ...
207 Here, the kind of the locally-polymorphic type variable "b"
208 depends on *all the uses of class D*. For example, the use of
209 Monad c in bop's type signature means that D must have kind Type->Type.
212 kcTyClDecl :: RenamedTyClDecl -> TcM s ()
214 kcTyClDecl decl@(TySynonym tycon_name hs_tyvars rhs loc)
215 = tcAddDeclCtxt decl $
216 kcTyClDeclBody tycon_name hs_tyvars $ \ result_kind ->
217 kcHsType rhs `thenTc` \ rhs_kind ->
218 unifyKind result_kind rhs_kind
220 kcTyClDecl decl@(TyData _ context tycon_name hs_tyvars con_decls _ _ _ loc)
221 = tcAddDeclCtxt decl $
222 kcTyClDeclBody tycon_name hs_tyvars $ \ result_kind ->
223 kcHsContext context `thenTc_`
224 mapTc_ kc_con_decl con_decls
226 kc_con_decl (ConDecl _ _ ex_tvs ex_ctxt details loc)
228 kcHsTyVars ex_tvs `thenNF_Tc` \ kind_env ->
229 tcExtendKindEnv kind_env $
230 kcConDetails ex_ctxt details
232 kcTyClDecl decl@(ClassDecl context class_name
233 hs_tyvars fundeps class_sigs
235 = tcAddDeclCtxt decl $
236 kcTyClDeclBody class_name hs_tyvars $ \ result_kind ->
237 kcHsContext context `thenTc_`
238 mapTc_ kc_sig (filter isClassOpSig class_sigs)
240 kc_sig (ClassOpSig _ _ op_ty loc) = tcAddSrcLoc loc (kcHsBoxedSigType op_ty)
242 kcTyClDeclBody :: Name -> [HsTyVarBndr Name] -- Kind of the tycon/cls and its tyvars
243 -> (Kind -> TcM s a) -- Thing inside
245 -- Extend the env with bindings for the tyvars, taken from
246 -- the kind of the tycon/class. Give it to the thing inside, and
247 -- check the result kind matches
248 kcTyClDeclBody tc_name hs_tyvars thing_inside
249 = tcLookupTy tc_name `thenNF_Tc` \ tc ->
251 (tyvars_w_kinds, result_kind) = zipFunTys (hsTyVarNames hs_tyvars) (tyThingKind tc)
253 tcExtendKindEnv tyvars_w_kinds (thing_inside result_kind)
257 %************************************************************************
259 \subsection{Step 4: Building the tycon/class}
261 %************************************************************************
265 :: RecFlag -> NameEnv Kind
266 -> FiniteMap TyCon ArgVrcs -> NameEnv TyThingDetails
267 -> RenamedTyClDecl -> (Name, TyThing)
268 -- Can't fail; the only reason it's in the monad
269 -- is so it can zonk the kinds
271 buildTyConOrClass is_rec kenv rec_vrcs rec_details
272 (TySynonym tycon_name tyvar_names rhs src_loc)
273 = (tycon_name, ATyCon tycon)
275 tycon = mkSynTyCon tycon_name tycon_kind arity tyvars rhs_ty argvrcs
276 tycon_kind = lookupNameEnv_NF kenv tycon_name
277 arity = length tyvar_names
278 tyvars = mkTyClTyVars tycon_kind tyvar_names
279 SynTyDetails rhs_ty = lookupNameEnv_NF rec_details tycon_name
280 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
282 buildTyConOrClass is_rec kenv rec_vrcs rec_details
283 (TyData data_or_new context tycon_name tyvar_names _ nconstrs _ _ src_loc)
284 = (tycon_name, ATyCon tycon)
286 tycon = mkAlgTyCon tycon_name tycon_kind tyvars ctxt argvrcs
291 DataTyDetails ctxt data_cons derived_classes = lookupNameEnv_NF rec_details tycon_name
293 tycon_kind = lookupNameEnv_NF kenv tycon_name
294 tyvars = mkTyClTyVars tycon_kind tyvar_names
295 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
297 flavour = case data_or_new of
298 NewType -> NewTyCon (mkNewTyConRep tycon)
299 DataType | all isNullaryDataCon data_cons -> EnumTyCon
300 | otherwise -> DataTyCon
302 buildTyConOrClass is_rec kenv rec_vrcs rec_details
303 (ClassDecl context class_name
304 tyvar_names fundeps class_sigs def_methods pragmas
305 tycon_name datacon_name datacon_wkr_name sc_sel_names src_loc)
306 = (class_name, AClass clas)
308 clas = mkClass class_name tyvars fds
309 sc_theta sc_sel_ids op_items
312 tycon = mkClassTyCon tycon_name class_kind tyvars
314 clas -- Yes! It's a dictionary
317 ClassDetails sc_theta sc_sel_ids op_items dict_con = lookupNameEnv_NF rec_details class_name
319 class_kind = lookupNameEnv_NF kenv class_name
320 tyvars = mkTyClTyVars class_kind tyvar_names
321 argvrcs = lookupWithDefaultFM rec_vrcs bogusVrcs tycon
322 n_fields = length sc_sel_ids + length op_items
324 flavour | n_fields == 1 = NewTyCon (mkNewTyConRep tycon)
325 | otherwise = DataTyCon
327 -- We can find the functional dependencies right away,
328 -- and it is vital to do so. Why? Because in the next pass
329 -- we check for ambiguity in all the type signatures, and we
330 -- need the functional dependcies to be done by then
331 fds = [(map lookup xs, map lookup ys) | (xs,ys) <- fundeps]
332 tyvar_env = mkNameEnv [(varName tv, tv) | tv <- tyvars]
333 lookup = lookupNameEnv_NF tyvar_env
335 bogusVrcs = panic "Bogus tycon arg variances"
339 %************************************************************************
341 \subsection{Dependency analysis}
343 %************************************************************************
348 sortByDependency :: [RenamedHsDecl] -> TcM s [SCC RenamedTyClDecl]
349 sortByDependency decls
350 = let -- CHECK FOR CLASS CYCLES
351 cls_sccs = stronglyConnComp (mapMaybe mk_cls_edges tycl_decls)
352 cls_cycles = [ decls | CyclicSCC decls <- cls_sccs]
354 checkTc (null cls_cycles) (classCycleErr cls_cycles) `thenTc_`
356 let -- CHECK FOR SYNONYM CYCLES
357 syn_sccs = stronglyConnComp (filter is_syn_decl edges)
358 syn_cycles = [ decls | CyclicSCC decls <- syn_sccs]
361 checkTc (null syn_cycles) (typeCycleErr syn_cycles) `thenTc_`
363 -- DO THE MAIN DEPENDENCY ANALYSIS
365 decl_sccs = stronglyConnComp edges
369 tycl_decls = [d | TyClD d <- decls]
370 edges = map mk_edges tycl_decls
372 is_syn_decl (d, _, _) = isSynDecl d
375 Edges in Type/Class decls
376 ~~~~~~~~~~~~~~~~~~~~~~~~~
379 ----------------------------------------------------
380 -- mk_cls_edges looks only at the context of class decls
381 -- Its used when we are figuring out if there's a cycle in the
382 -- superclass hierarchy
384 mk_cls_edges :: RenamedTyClDecl -> Maybe (RenamedTyClDecl, Unique, [Unique])
386 mk_cls_edges decl@(ClassDecl ctxt name _ _ _ _ _ _ _ _ _ _)
387 = Just (decl, getUnique name, map getUnique (catMaybes (map get_clas ctxt)))
388 mk_cls_edges other_decl
391 ----------------------------------------------------
392 mk_edges :: RenamedTyClDecl -> (RenamedTyClDecl, Unique, [Unique])
394 mk_edges decl@(TyData _ ctxt name _ condecls _ derivs _ _)
395 = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
396 get_cons condecls `unionUniqSets`
399 mk_edges decl@(TySynonym name _ rhs _)
400 = (decl, getUnique name, uniqSetToList (get_ty rhs))
402 mk_edges decl@(ClassDecl ctxt name _ _ sigs _ _ _ _ _ _ _)
403 = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
407 ----------------------------------------------------
408 get_ctxt ctxt = unionManyUniqSets (map set_name (catMaybes (map get_clas ctxt)))
409 get_clas (HsPClass clas _) = Just clas
412 ----------------------------------------------------
413 get_deriv Nothing = emptyUniqSet
414 get_deriv (Just clss) = unionManyUniqSets (map set_name clss)
416 ----------------------------------------------------
417 get_cons cons = unionManyUniqSets (map get_con cons)
419 ----------------------------------------------------
420 get_con (ConDecl _ _ _ ctxt details _)
421 = get_ctxt ctxt `unionUniqSets` get_con_details details
423 ----------------------------------------------------
424 get_con_details (VanillaCon btys) = unionManyUniqSets (map get_bty btys)
425 get_con_details (InfixCon bty1 bty2) = unionUniqSets (get_bty bty1) (get_bty bty2)
426 get_con_details (RecCon nbtys) = unionManyUniqSets (map (get_bty.snd) nbtys)
428 ----------------------------------------------------
429 get_bty bty = get_ty (getBangType bty)
431 ----------------------------------------------------
432 get_ty (HsTyVar name) | isTvOcc (nameOccName name) = emptyUniqSet
433 | otherwise = set_name name
434 get_ty (HsAppTy ty1 ty2) = unionUniqSets (get_ty ty1) (get_ty ty2)
435 get_ty (HsFunTy ty1 ty2) = unionUniqSets (get_ty ty1) (get_ty ty2)
436 get_ty (HsListTy ty) = set_name listTyCon_name `unionUniqSets` get_ty ty
437 get_ty (HsTupleTy (HsTupCon n _) tys) = set_name n `unionUniqSets` get_tys tys
438 get_ty (HsUsgTy _ ty) = get_ty ty
439 get_ty (HsUsgForAllTy _ ty) = get_ty ty
440 get_ty (HsForAllTy _ ctxt mty) = get_ctxt ctxt `unionUniqSets` get_ty mty
441 get_ty (HsPredTy (HsPClass name _)) = set_name name
442 get_ty (HsPredTy (HsPIParam _ _)) = emptyUniqSet -- I think
444 ----------------------------------------------------
445 get_tys tys = unionManyUniqSets (map get_ty tys)
447 ----------------------------------------------------
449 = unionManyUniqSets (map get_sig sigs)
451 get_sig (ClassOpSig _ _ ty _) = get_ty ty
452 get_sig (FixSig _) = emptyUniqSet
453 get_sig other = panic "TcTyClsDecls:get_sig"
455 ----------------------------------------------------
456 set_name name = unitUniqSet (getUnique name)
460 %************************************************************************
462 \subsection{Error management
464 %************************************************************************
467 tcAddDeclCtxt decl thing_inside
474 (ClassDecl _ name _ _ _ _ _ _ _ _ _ loc) -> (name, loc, "class")
475 (TySynonym name _ _ loc) -> (name, loc, "type synonym")
476 (TyData NewType _ name _ _ _ _ _ loc) -> (name, loc, "data type")
477 (TyData DataType _ name _ _ _ _ _ loc) -> (name, loc, "newtype")
479 ctxt = hsep [ptext SLIT("In the"), text thing,
480 ptext SLIT("declaration for"), quotes (ppr name)]
484 typeCycleErr, classCycleErr :: [[RenamedTyClDecl]] -> Message
486 typeCycleErr syn_cycles
487 = vcat (map (pp_cycle "Cycle in type declarations:") syn_cycles)
489 classCycleErr cls_cycles
490 = vcat (map (pp_cycle "Cycle in class declarations:") cls_cycles)
494 4 (vcat (map pp_decl decls))
497 = hsep [quotes (ppr name), ptext SLIT("at"), ppr (getSrcLoc name)]
499 name = tyClDeclName decl