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(..),
15 ConDecl(..), ConDetails(..), BangType(..),
17 tyClDeclName, isClassDecl, isSynDecl
19 import RnHsSyn ( RenamedHsDecl, RenamedTyClDecl, listTyCon_name, tupleTyCon_name )
20 import BasicTypes ( RecFlag(..), NewOrData(..), Arity )
23 import Inst ( InstanceMapper )
24 import TcClassDcl ( kcClassDecl, tcClassDecl1 )
25 import TcEnv ( ValueEnv, TcTyThing(..),
26 tcExtendTypeEnv, getAllEnvTyCons
28 import TcTyDecls ( tcTyDecl, kcTyDecl )
29 import TcMonoType ( kcHsTyVar )
30 import TcType ( TcKind, newKindVar, newKindVars, kindToTcKind, zonkTcKindToKind )
32 import Type ( mkArrowKind, boxedTypeKind, mkDictTy )
33 -- next two imports for usage stuff only
34 import TyCon ( ArgVrcs, tyConKind, tyConArity, tyConDataCons, tyConTyVars,
35 tyConArgVrcs_maybe, getSynTyConDefn, isSynTyCon, isAlgTyCon )
36 import DataCon ( dataConRawArgTys, dataConSig )
38 import Class ( Class, classBigSig )
39 import Type ( Type(..), TyNote(..), tyVarsOfTypes )
40 import Var ( TyVar, tyVarKind )
44 import Digraph ( stronglyConnComp, SCC(..) )
45 import Name ( Name, NamedThing(..), getSrcLoc, isTvOcc, nameOccName )
47 import Maybes ( mapMaybe, expectJust )
48 import UniqSet ( UniqSet, emptyUniqSet,
49 unitUniqSet, unionUniqSets,
50 unionManyUniqSets, uniqSetToList )
51 import ErrUtils ( Message )
52 import SrcLoc ( SrcLoc )
53 import TyCon ( TyCon )
54 import Unique ( Unique, Uniquable(..) )
55 import UniqFM ( listToUFM, lookupUFM )
61 tcTyAndClassDecls :: ValueEnv -> InstanceMapper -- Knot tying stuff
65 tcTyAndClassDecls unf_env inst_mapper decls
66 = sortByDependency decls `thenTc` \ groups ->
67 tcGroups unf_env inst_mapper groups
69 tcGroups unf_env inst_mapper []
70 = tcGetEnv `thenNF_Tc` \ env ->
73 tcGroups unf_env inst_mapper (group:groups)
74 = tcGroup unf_env inst_mapper group `thenTc` \ env ->
76 tcGroups unf_env inst_mapper groups
82 The knot-tying parameters: @rec_tyclss@ is an alist mapping @Name@s to
83 @TcTyThing@s. @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
86 tcGroup :: ValueEnv -> InstanceMapper -> SCC RenamedTyClDecl -> TcM s TcEnv
87 tcGroup unf_env inst_mapper scc
89 mapNF_Tc getTyBinding1 decls `thenNF_Tc` \ ty_env_stuff1 ->
90 tcExtendTypeEnv ty_env_stuff1 (mapTc kcDecl decls) `thenTc_`
93 -- traceTc (ppr (map fst ty_env_stuff1)) `thenTc_`
94 fixTc ( \ ~(rec_tyclss, rec_vrcs, _) ->
96 rec_env = listToUFM rec_tyclss
100 mapNF_Tc (getTyBinding2 rec_env) ty_env_stuff1 `thenNF_Tc` \ ty_env_stuff2 ->
101 tcExtendTypeEnv ty_env_stuff2 $
102 mapTc (tcDecl is_rec_group unf_env inst_mapper rec_vrcs) decls
105 tcGetEnv `thenTc` \ env ->
107 tycons = getAllEnvTyCons env
108 vrcs = calcTyConArgVrcs tycons
111 returnTc (tyclss, vrcs, env)
112 ) `thenTc` \ (_, _, env) ->
113 -- traceTc (text "done" <+> ppr (map fst ty_env_stuff1)) `thenTc_`
116 is_rec_group = case scc of
117 AcyclicSCC _ -> NonRecursive
118 CyclicSCC _ -> Recursive
121 AcyclicSCC decl -> [decl]
122 CyclicSCC decls -> decls
125 Dealing with one decl
126 ~~~~~~~~~~~~~~~~~~~~~
129 = tcAddDeclCtxt decl $
130 if isClassDecl decl then
135 tcDecl :: RecFlag -- True => recursive group
136 -> ValueEnv -> InstanceMapper -> FiniteMap Name ArgVrcs
137 -> RenamedTyClDecl -> TcM s (Name, TcTyThing)
139 tcDecl is_rec_group unf_env inst_mapper vrcs_env decl
140 = tcAddDeclCtxt decl $
141 -- traceTc (text "Starting" <+> ppr name) `thenTc_`
142 if isClassDecl decl then
143 tcClassDecl1 unf_env inst_mapper vrcs_env decl `thenTc` \ clas ->
144 -- traceTc (text "Finished" <+> ppr name) `thenTc_`
145 returnTc (getName clas, AClass clas)
147 tcTyDecl is_rec_group vrcs_env decl `thenTc` \ tycon ->
148 -- traceTc (text "Finished" <+> ppr name) `thenTc_`
149 returnTc (getName tycon, ATyCon tycon)
152 name = tyClDeclName decl
155 tcAddDeclCtxt decl thing_inside
162 (ClassDecl _ name _ _ _ _ _ _ loc) -> (name, loc, "class")
163 (TySynonym name _ _ loc) -> (name, loc, "type synonym")
164 (TyData NewType _ name _ _ _ _ loc) -> (name, loc, "data type")
165 (TyData DataType _ name _ _ _ _ loc) -> (name, loc, "newtype")
167 ctxt = hsep [ptext SLIT("In the"), text thing,
168 ptext SLIT("declaration for"), quotes (ppr name)]
174 Extract *binding* names from type and class decls. Type variables are
175 bound in type, data, newtype and class declarations,
176 *and* the polytypes in the class op sigs.
177 *and* the existentially quantified contexts in datacon decls
179 Why do we need to grab all these type variables at once, including
180 those locally-quantified type variables in class op signatures?
182 [Incidentally, this only works because the names are all unique by now.]
184 Because we can only commit to the final kind of a type variable when
185 we've completed the mutually recursive group. 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.
199 getTyBinding1 :: RenamedTyClDecl -> NF_TcM s (Name, (TcKind, Maybe Arity, TcTyThing))
200 getTyBinding1 (TySynonym name tyvars _ _)
201 = mapNF_Tc kcHsTyVar tyvars `thenNF_Tc` \ arg_kinds ->
202 newKindVar `thenNF_Tc` \ result_kind ->
203 returnNF_Tc (name, (foldr mkArrowKind result_kind arg_kinds,
204 Just (length tyvars),
205 ATyCon (pprPanic "ATyCon: syn" (ppr name))))
207 getTyBinding1 (TyData _ _ name tyvars _ _ _ _)
208 = mapNF_Tc kcHsTyVar tyvars `thenNF_Tc` \ arg_kinds ->
209 returnNF_Tc (name, (foldr mkArrowKind boxedTypeKind arg_kinds,
211 ATyCon (error "ATyCon: data")))
213 getTyBinding1 (ClassDecl _ name tyvars _ _ _ _ _ _)
214 = mapNF_Tc kcHsTyVar tyvars `thenNF_Tc` \ arg_kinds ->
215 returnNF_Tc (name, (foldr mkArrowKind boxedTypeKind arg_kinds,
216 Just (length tyvars),
217 AClass (error "AClass")))
219 -- Zonk the kind to its final form, and lookup the
220 -- recursive tycon/class
221 getTyBinding2 rec_env (name, (tc_kind, maybe_arity, thing))
222 = zonkTcKindToKind tc_kind `thenNF_Tc` \ kind ->
223 returnNF_Tc (name, (kind, maybe_arity, mk_thing thing (lookupUFM rec_env name)))
225 mk_thing (ATyCon _) ~(Just (ATyCon tc)) = ATyCon tc
226 mk_thing (AClass _) ~(Just (AClass cls)) = AClass cls
230 %************************************************************************
232 \subsection{Dependency analysis}
234 %************************************************************************
239 sortByDependency :: [RenamedHsDecl] -> TcM s [SCC RenamedTyClDecl]
240 sortByDependency decls
241 = let -- CHECK FOR CLASS CYCLES
242 cls_sccs = stronglyConnComp (mapMaybe mk_cls_edges tycl_decls)
243 cls_cycles = [ decls | CyclicSCC decls <- cls_sccs]
245 checkTc (null cls_cycles) (classCycleErr cls_cycles) `thenTc_`
247 let -- CHECK FOR SYNONYM CYCLES
248 syn_sccs = stronglyConnComp (filter is_syn_decl edges)
249 syn_cycles = [ decls | CyclicSCC decls <- syn_sccs]
252 checkTc (null syn_cycles) (typeCycleErr syn_cycles) `thenTc_`
254 -- DO THE MAIN DEPENDENCY ANALYSIS
256 decl_sccs = stronglyConnComp edges
260 tycl_decls = [d | TyClD d <- decls]
261 edges = map mk_edges tycl_decls
263 is_syn_decl (d, _, _) = isSynDecl d
264 is_cls_decl (d, _, _) = isClassDecl d
267 Edges in Type/Class decls
268 ~~~~~~~~~~~~~~~~~~~~~~~~~
271 ----------------------------------------------------
272 -- mk_cls_edges looks only at the context of class decls
273 -- Its used when we are figuring out if there's a cycle in the
274 -- superclass hierarchy
276 mk_cls_edges :: RenamedTyClDecl -> Maybe (RenamedTyClDecl, Unique, [Unique])
278 mk_cls_edges decl@(ClassDecl ctxt name _ _ _ _ _ _ _)
279 = Just (decl, getUnique name, map (getUnique . fst) ctxt)
280 mk_cls_edges other_decl
283 ----------------------------------------------------
284 mk_edges :: RenamedTyClDecl -> (RenamedTyClDecl, Unique, [Unique])
286 mk_edges decl@(TyData _ ctxt name _ condecls derivs _ _)
287 = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
288 get_cons condecls `unionUniqSets`
291 mk_edges decl@(TySynonym name _ rhs _)
292 = (decl, getUnique name, uniqSetToList (get_ty rhs))
294 mk_edges decl@(ClassDecl ctxt name _ sigs _ _ _ _ _)
295 = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
299 ----------------------------------------------------
300 get_ctxt ctxt = unionManyUniqSets (map (set_name.fst) ctxt)
302 ----------------------------------------------------
303 get_deriv Nothing = emptyUniqSet
304 get_deriv (Just clss) = unionManyUniqSets (map set_name clss)
306 ----------------------------------------------------
307 get_cons cons = unionManyUniqSets (map get_con cons)
309 ----------------------------------------------------
310 get_con (ConDecl _ _ ctxt details _)
311 = get_ctxt ctxt `unionUniqSets` get_con_details details
313 ----------------------------------------------------
314 get_con_details (VanillaCon btys) = unionManyUniqSets (map get_bty btys)
315 get_con_details (InfixCon bty1 bty2) = unionUniqSets (get_bty bty1) (get_bty bty2)
316 get_con_details (NewCon ty _) = get_ty ty
317 get_con_details (RecCon nbtys) = unionManyUniqSets (map (get_bty.snd) nbtys)
319 ----------------------------------------------------
320 get_bty (Banged ty) = get_ty ty
321 get_bty (Unbanged ty) = get_ty ty
322 get_bty (Unpacked ty) = get_ty ty
324 ----------------------------------------------------
325 get_ty (MonoTyVar name)
326 = if isTvOcc (nameOccName name) then emptyUniqSet else set_name name
327 get_ty (MonoTyApp ty1 ty2)
328 = unionUniqSets (get_ty ty1) (get_ty ty2)
329 get_ty (MonoFunTy ty1 ty2)
330 = unionUniqSets (get_ty ty1) (get_ty ty2)
331 get_ty (MonoListTy ty)
332 = set_name listTyCon_name `unionUniqSets` get_ty ty
333 get_ty (MonoTupleTy tys boxed)
334 = set_name (tupleTyCon_name boxed (length tys)) `unionUniqSets` get_tys tys
335 get_ty (MonoUsgTy _ ty)
337 get_ty (HsForAllTy _ ctxt mty)
338 = get_ctxt ctxt `unionUniqSets` get_ty mty
339 get_ty (MonoDictTy name _)
342 ----------------------------------------------------
344 = unionManyUniqSets (map get_ty tys)
346 ----------------------------------------------------
348 = unionManyUniqSets (mapMaybe get_sig sigs)
350 get_sig (ClassOpSig _ _ ty _) = Just (get_ty ty)
351 get_sig (FixSig _) = Nothing
352 get_sig other = panic "TcTyClsDecls:get_sig"
354 ----------------------------------------------------
355 set_name name = unitUniqSet (getUnique name)
356 set_to_bag set = listToBag (uniqSetToList set)
361 typeCycleErr, classCycleErr :: [[RenamedTyClDecl]] -> Message
363 typeCycleErr syn_cycles
364 = vcat (map (pp_cycle "Cycle in type declarations:") syn_cycles)
366 classCycleErr cls_cycles
367 = vcat (map (pp_cycle "Cycle in class declarations:") cls_cycles)
371 4 (vcat (map pp_decl decls))
374 = hsep [quotes (ppr name), ptext SLIT("at"), ppr (getSrcLoc name)]
376 name = tyClDeclName decl
380 Computing the tyConArgVrcs info
381 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383 @tyConArgVrcs@ gives a list of (occPos,occNeg) flags, one for each
384 tyvar. For @AlgTyCon@s and @SynTyCon@s, this info must be precomputed
385 separately. Note that this is information about occurrences of type
386 variables, not usages of term variables.
388 The function @calcTyConArgVrcs@ must be passed a list of *algebraic or
389 syntycons only* such that all tycons referred to (by mutual recursion)
390 appear in the list. The fixpointing will be done on this set of
391 tycons as a whole. It returns a list of @tyconVrcInfo@ data, ready to
392 be (knot-tyingly?) stuck back into the appropriate fields.
395 calcTyConArgVrcs :: [TyCon]
396 -> FiniteMap Name ArgVrcs
398 calcTyConArgVrcs tycons
399 = let oi = foldl (\fm tc -> addToFM fm tc (initial tc)) emptyFM tycons
400 initial tc = if isAlgTyCon tc && null (tyConDataCons tc) then
401 -- make pessimistic assumption (and warn)
402 take (tyConArity tc) abstractVrcs
404 replicate (tyConArity tc) (False,False)
406 go (tc,vrcs) = (getName tc,vrcs)
407 in listToFM (map go (fmToList oi''))
411 tcaoFix :: FiniteMap TyCon ArgVrcs -- initial ArgVrcs per tycon
412 -> FiniteMap TyCon ArgVrcs -- fixpointed ArgVrcs per tycon
414 tcaoFix oi = let (changed,oi') = foldFM (\ tc pms
416 -> let pms' = tcaoIter oi' tc -- seq not simult
417 in (changed || (pms /= pms'),
418 addToFM oi' tc pms'))
419 (False,oi) -- seq not simult for faster fixpting
425 tcaoIter :: FiniteMap TyCon ArgVrcs -- reference ArgVrcs (initial)
426 -> TyCon -- tycon to update
427 -> ArgVrcs -- new ArgVrcs for tycon
429 tcaoIter oi tc | isAlgTyCon tc
430 = let cs = tyConDataCons tc
432 argtys = concatMap dataConRawArgTys cs
433 exdicttys = concatMap ((\ (_,_,_,exth,_,_) -> map (uncurry mkDictTy) exth)
435 myfao tc = lookupWithDefaultFM oi (expectJust "tcaoIter(Alg)" $
436 tyConArgVrcs_maybe tc)
438 -- we use the already-computed result for tycons not in this SCC
439 in map (\v -> anyVrc (\ty -> vrcInTy myfao v ty) (exdicttys ++ argtys))
442 tcaoIter oi tc | isSynTyCon tc
443 = let (tyvs,ty) = getSynTyConDefn tc
444 myfao tc = lookupWithDefaultFM oi (expectJust "tcaoIter(Syn)" $
445 tyConArgVrcs_maybe tc)
447 -- we use the already-computed result for tycons not in this SCC
448 in map (\v -> vrcInTy myfao v ty) tyvs
451 abstractVrcs :: ArgVrcs
452 -- we pull this out as a CAF so the warning only appears *once*
453 abstractVrcs = trace ("WARNING: tyConArgVrc info inaccurate due to unavailable constructors.\n"
454 ++ "\tUse -fno-prune-tydecls to fix.") $
458 And a general variance-check function. We pass a function for
459 determining the @ArgVrc@s of a tycon; when fixpointing this refers to
460 the current value; otherwise this should be looked up from the tycon's
464 vrcInTy :: (TyCon -> ArgVrcs) -- function to get argVrcs of a tycon (break out of recursion)
465 -> TyVar -- tyvar to check Vrcs of
466 -> Type -- type to check for occ in
467 -> (Bool,Bool) -- (occurs positively, occurs negatively)
469 vrcInTy fao v (NoteTy (UsgNote _) ty) = vrcInTy fao v ty
471 vrcInTy fao v (NoteTy (SynNote _) ty) = vrcInTy fao v ty
472 -- SynTyCon doesn't neccessarily have vrcInfo at this point,
473 -- so don't try and use it
475 vrcInTy fao v (NoteTy (FTVNote ftv) ty) = if elemVarSet v ftv
476 then vrcInTy fao v ty
478 -- note that ftv cannot be calculated as occPos||occNeg,
479 -- since if a tyvar occurs only as unused tyconarg,
480 -- occPos==occNeg==False, but ftv=True
482 vrcInTy fao v (TyVarTy v') = if v==v'
486 vrcInTy fao v (AppTy ty1 ty2) = if vrcInTy fao v ty2 /= (False,False)
488 else vrcInTy fao v ty1
489 -- ty1 is probably unknown (or it would have been beta-reduced);
490 -- hence if v occurs in ty2 at all then it could occur with
491 -- either variance. Otherwise it occurs as it does in ty1.
493 vrcInTy fao v (FunTy ty1 ty2) = let (p1,m1) = vrcInTy fao v ty1
494 (p2,m2) = vrcInTy fao v ty2
497 vrcInTy fao v (ForAllTy v' ty) = if v==v'
499 else vrcInTy fao v ty
501 vrcInTy fao v (TyConApp tc tys) = let pms1 = map (vrcInTy fao v) tys
503 in orVrcs (zipWith timesVrc pms1 pms2)
505 orVrc :: (Bool,Bool) -> (Bool,Bool) -> (Bool,Bool)
506 orVrc (p1,m1) (p2,m2) = (p1||p2,m1||m2)
508 orVrcs :: [(Bool,Bool)] -> (Bool,Bool)
509 orVrcs = foldl orVrc (False,False)
511 anyVrc :: (a -> (Bool,Bool)) -> [a] -> (Bool,Bool)
512 anyVrc p as = foldl (\pm a -> pm `orVrc` p a) (False,False) as
514 timesVrc :: (Bool,Bool) -> (Bool,Bool) -> (Bool,Bool)
515 timesVrc (p1,m1) (p2,m2) = (p1 && p2 || m1 && m2,
516 p1 && m2 || m1 && p2)