[project @ 2000-05-25 12:41:14 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcTyClsDecls.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1996-1998
3 %
4 \section[TcTyClsDecls]{Typecheck type and class declarations}
5
6 \begin{code}
7 module TcTyClsDecls (
8         tcTyAndClassDecls
9     ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( HsDecl(..), TyClDecl(..),
14                           HsType(..), HsTyVarBndr,
15                           ConDecl(..), ConDetails(..), BangType(..),
16                           Sig(..), HsPred(..), HsTupCon(..),
17                           tyClDeclName, isClassDecl, isSynDecl
18                         )
19 import RnHsSyn          ( RenamedHsDecl, RenamedTyClDecl, listTyCon_name )
20 import BasicTypes       ( RecFlag(..), NewOrData(..), Arity )
21
22 import TcMonad
23 import Inst             ( InstanceMapper )
24 import TcClassDcl       ( kcClassDecl, tcClassDecl1 )
25 import TcEnv            ( ValueEnv, TcTyThing(..),
26                           tcExtendTypeEnv, getEnvAllTyCons
27                         )
28 import TcTyDecls        ( tcTyDecl, kcTyDecl )
29 import TcMonoType       ( kcHsTyVar )
30 import TcType           ( TcKind, newKindVar, newKindVars, kindToTcKind, zonkTcKindToKind )
31
32 import Type             ( mkArrowKind, boxedTypeKind )
33
34 import Class            ( Class )
35 import Var              ( TyVar, tyVarKind )
36 import FiniteMap
37 import Bag      
38 import VarSet
39 import Digraph          ( stronglyConnComp, SCC(..) )
40 import Name             ( Name, NamedThing(..), getSrcLoc, isTvOcc, nameOccName )
41 import Outputable
42 import Maybes           ( mapMaybe, catMaybes, expectJust )
43 import UniqSet          ( UniqSet, emptyUniqSet,
44                           unitUniqSet, unionUniqSets, 
45                           unionManyUniqSets, uniqSetToList ) 
46 import ErrUtils         ( Message )
47 import SrcLoc           ( SrcLoc )
48 import TyCon            ( TyCon, ArgVrcs )
49 import Variance         ( calcTyConArgVrcs )
50 import Unique           ( Unique, Uniquable(..) )
51 import UniqFM           ( listToUFM, lookupUFM )
52 \end{code}
53
54 The main function
55 ~~~~~~~~~~~~~~~~~
56 \begin{code}
57 tcTyAndClassDecls :: ValueEnv -> InstanceMapper -- Knot tying stuff
58                   -> [RenamedHsDecl]
59                   -> TcM s TcEnv
60
61 tcTyAndClassDecls unf_env inst_mapper decls
62   = sortByDependency decls              `thenTc` \ groups ->
63     tcGroups unf_env inst_mapper groups
64
65 tcGroups unf_env inst_mapper []
66   = tcGetEnv    `thenNF_Tc` \ env ->
67     returnTc env
68
69 tcGroups unf_env inst_mapper (group:groups)
70   = tcGroup unf_env inst_mapper group   `thenTc` \ env ->
71     tcSetEnv env                        $
72     tcGroups unf_env inst_mapper groups
73 \end{code}
74
75 Dealing with a group
76 ~~~~~~~~~~~~~~~~~~~~
77
78 The knot-tying parameters: @rec_tyclss@ is an alist mapping @Name@s to
79 @TcTyThing@s.  @rec_vrcs@ is a finite map from @Name@s to @ArgVrcs@s.
80
81 \begin{code}
82 tcGroup :: ValueEnv -> InstanceMapper -> SCC RenamedTyClDecl -> TcM s TcEnv
83 tcGroup unf_env inst_mapper scc
84   =     -- Do kind checking
85     mapNF_Tc getTyBinding1 decls                        `thenNF_Tc` \ ty_env_stuff1 ->
86     tcExtendTypeEnv ty_env_stuff1 (mapTc kcDecl decls)  `thenTc_`
87
88         -- Tie the knot
89 --  traceTc (ppr (map fst ty_env_stuff1))               `thenTc_`
90     fixTc ( \ ~(rec_tyclss,  _) ->
91         let
92             rec_env    = listToUFM rec_tyclss
93             rec_tycons = getEnvAllTyCons rec_tyclss
94             rec_vrcs   = calcTyConArgVrcs rec_tycons
95         in
96         
97                 -- Do type checking
98         mapNF_Tc (getTyBinding2 rec_env) ty_env_stuff1  `thenNF_Tc` \ ty_env_stuff2 ->
99         tcExtendTypeEnv ty_env_stuff2                           $
100         mapTc (tcDecl is_rec_group unf_env inst_mapper rec_vrcs) decls
101                                                                 `thenTc` \ tyclss ->
102
103         tcGetEnv                                                `thenTc` \ env -> 
104         returnTc (tyclss, env)
105     )                                                           `thenTc` \ (_, env) ->
106 --  traceTc (text "done" <+> ppr (map fst ty_env_stuff1))       `thenTc_`
107     returnTc env
108   where
109     is_rec_group = case scc of
110                         AcyclicSCC _ -> NonRecursive
111                         CyclicSCC _  -> Recursive
112
113     decls = case scc of
114                 AcyclicSCC decl -> [decl]
115                 CyclicSCC decls -> decls
116 \end{code}
117
118 Dealing with one decl
119 ~~~~~~~~~~~~~~~~~~~~~
120 \begin{code}
121 kcDecl decl
122   = tcAddDeclCtxt decl          $
123     if isClassDecl decl then
124         kcClassDecl decl
125     else
126         kcTyDecl    decl
127
128 tcDecl  :: RecFlag                      -- True => recursive group
129          -> ValueEnv -> InstanceMapper -> FiniteMap Name ArgVrcs
130          -> RenamedTyClDecl -> TcM s (Name, TcTyThing)
131
132 tcDecl is_rec_group unf_env inst_mapper vrcs_env decl
133   = tcAddDeclCtxt decl          $
134     if isClassDecl decl then
135         tcClassDecl1 unf_env inst_mapper vrcs_env decl
136     else
137         tcTyDecl is_rec_group vrcs_env decl
138                 
139
140 tcAddDeclCtxt decl thing_inside
141   = tcAddSrcLoc loc     $
142     tcAddErrCtxt ctxt   $
143     thing_inside
144   where
145      (name, loc, thing)
146         = case decl of
147             (ClassDecl _ name _ _ _ _ _ _ _ _ _ loc) -> (name, loc, "class")
148             (TySynonym name _ _ loc)                 -> (name, loc, "type synonym")
149             (TyData NewType  _ name _ _ _ _ _ loc)   -> (name, loc, "data type")
150             (TyData DataType _ name _ _ _ _ _ loc)   -> (name, loc, "newtype")
151
152      ctxt = hsep [ptext SLIT("In the"), text thing, 
153                   ptext SLIT("declaration for"), quotes (ppr name)]
154 \end{code}
155
156
157 getTyBinders
158 ~~~~~~~~~~~
159 Extract *binding* names from type and class decls.  Type variables are
160 bound in type, data, newtype and class declarations, 
161         *and* the polytypes in the class op sigs.
162         *and* the existentially quantified contexts in datacon decls
163
164 Why do we need to grab all these type variables at once, including
165 those locally-quantified type variables in class op signatures?
166
167    [Incidentally, this only works because the names are all unique by now.]
168
169 Because we can only commit to the final kind of a type variable when
170 we've completed the mutually recursive group. For example:
171
172 class C a where
173    op :: D b => a -> b -> b
174
175 class D c where
176    bop :: (Monad c) => ...
177
178 Here, the kind of the locally-polymorphic type variable "b"
179 depends on *all the uses of class D*.  For example, the use of
180 Monad c in bop's type signature means that D must have kind Type->Type.
181
182     [April 00: looks as if we've dropped this subtlety; I'm not sure when]
183
184 \begin{code}
185 getTyBinding1 :: RenamedTyClDecl -> NF_TcM s (Name, (TcKind, TcTyThing))
186 getTyBinding1 (TySynonym name tyvars _ _)
187  = mapNF_Tc kcHsTyVar tyvars            `thenNF_Tc` \ arg_kinds ->
188    newKindVar                           `thenNF_Tc` \ result_kind  ->
189    returnNF_Tc (name, (foldr mkArrowKind result_kind arg_kinds, 
190                        ASynTyCon (pprPanic "ATyCon: syn" (ppr name)) (length tyvars)))
191
192 getTyBinding1 (TyData _ _ name tyvars _ _ _ _ _)
193  = mapNF_Tc kcHsTyVar tyvars            `thenNF_Tc` \ arg_kinds ->
194    returnNF_Tc (name, (foldr mkArrowKind boxedTypeKind arg_kinds, 
195                        ADataTyCon (error "ATyCon: data")))
196
197 getTyBinding1 (ClassDecl _ name tyvars _ _ _ _ _ _ _ _ _)
198  = mapNF_Tc kcHsTyVar tyvars            `thenNF_Tc` \ arg_kinds ->
199    returnNF_Tc (name, (foldr mkArrowKind boxedTypeKind arg_kinds, 
200                        AClass (pprPanic "AClass" (ppr name)) (length tyvars)))
201
202 -- Zonk the kind to its final form, and lookup the 
203 -- recursive tycon/class
204 getTyBinding2 rec_env (name, (tc_kind, thing))
205   = zonkTcKindToKind tc_kind            `thenNF_Tc` \ kind ->
206     returnNF_Tc (name, (kind, mk_thing thing (lookupUFM rec_env name)))
207   where
208     mk_thing (ADataTyCon _)      ~(Just (ADataTyCon tc))  = ADataTyCon tc
209     mk_thing (ASynTyCon _ arity) ~(Just (ASynTyCon tc _)) = ASynTyCon tc arity
210     mk_thing (AClass _ arity)    ~(Just (AClass cls _))   = AClass cls arity
211 \end{code}
212
213
214 %************************************************************************
215 %*                                                                      *
216 \subsection{Dependency analysis}
217 %*                                                                      *
218 %************************************************************************
219
220 Dependency analysis
221 ~~~~~~~~~~~~~~~~~~~
222 \begin{code}
223 sortByDependency :: [RenamedHsDecl] -> TcM s [SCC RenamedTyClDecl]
224 sortByDependency decls
225   = let         -- CHECK FOR CLASS CYCLES
226         cls_sccs   = stronglyConnComp (mapMaybe mk_cls_edges tycl_decls)
227         cls_cycles = [ decls | CyclicSCC decls <- cls_sccs]
228     in
229     checkTc (null cls_cycles) (classCycleErr cls_cycles)        `thenTc_`
230
231     let         -- CHECK FOR SYNONYM CYCLES
232         syn_sccs   = stronglyConnComp (filter is_syn_decl edges)
233         syn_cycles = [ decls | CyclicSCC decls <- syn_sccs]
234
235     in
236     checkTc (null syn_cycles) (typeCycleErr syn_cycles)         `thenTc_`
237
238         -- DO THE MAIN DEPENDENCY ANALYSIS
239     let
240         decl_sccs  = stronglyConnComp edges
241     in
242     returnTc decl_sccs
243   where
244     tycl_decls = [d | TyClD d <- decls]
245     edges      = map mk_edges tycl_decls
246     
247     is_syn_decl (d, _, _) = isSynDecl d
248 \end{code}
249
250 Edges in Type/Class decls
251 ~~~~~~~~~~~~~~~~~~~~~~~~~
252
253 \begin{code}
254 ----------------------------------------------------
255 -- mk_cls_edges looks only at the context of class decls
256 -- Its used when we are figuring out if there's a cycle in the
257 -- superclass hierarchy
258
259 mk_cls_edges :: RenamedTyClDecl -> Maybe (RenamedTyClDecl, Unique, [Unique])
260
261 mk_cls_edges decl@(ClassDecl ctxt name _ _ _ _ _ _ _ _ _ _)
262   = Just (decl, getUnique name, map getUnique (catMaybes (map get_clas ctxt)))
263 mk_cls_edges other_decl
264   = Nothing
265
266 ----------------------------------------------------
267 mk_edges :: RenamedTyClDecl -> (RenamedTyClDecl, Unique, [Unique])
268
269 mk_edges decl@(TyData _ ctxt name _ condecls _ derivs _ _)
270   = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
271                                          get_cons condecls `unionUniqSets`
272                                          get_deriv derivs))
273
274 mk_edges decl@(TySynonym name _ rhs _)
275   = (decl, getUnique name, uniqSetToList (get_ty rhs))
276
277 mk_edges decl@(ClassDecl ctxt name _ _ sigs _ _ _ _ _ _ _)
278   = (decl, getUnique name, uniqSetToList (get_ctxt ctxt `unionUniqSets`
279                                          get_sigs sigs))
280
281
282 ----------------------------------------------------
283 get_ctxt ctxt = unionManyUniqSets (map set_name (catMaybes (map get_clas ctxt)))
284 get_clas (HsPClass clas _) = Just clas
285 get_clas _                 = Nothing
286
287 ----------------------------------------------------
288 get_deriv Nothing     = emptyUniqSet
289 get_deriv (Just clss) = unionManyUniqSets (map set_name clss)
290
291 ----------------------------------------------------
292 get_cons cons = unionManyUniqSets (map get_con cons)
293
294 ----------------------------------------------------
295 get_con (ConDecl _ _ _ ctxt details _) 
296   = get_ctxt ctxt `unionUniqSets` get_con_details details
297
298 ----------------------------------------------------
299 get_con_details (VanillaCon btys)    = unionManyUniqSets (map get_bty btys)
300 get_con_details (InfixCon bty1 bty2) = unionUniqSets (get_bty bty1) (get_bty bty2)
301 get_con_details (NewCon ty _)        = get_ty ty
302 get_con_details (RecCon nbtys)       = unionManyUniqSets (map (get_bty.snd) nbtys)
303
304 ----------------------------------------------------
305 get_bty (Banged ty)   = get_ty ty
306 get_bty (Unbanged ty) = get_ty ty
307 get_bty (Unpacked ty) = get_ty ty
308
309 ----------------------------------------------------
310 get_ty (HsTyVar name) | isTvOcc (nameOccName name) = emptyUniqSet 
311                       | otherwise                  = set_name name
312 get_ty (HsAppTy ty1 ty2)              = unionUniqSets (get_ty ty1) (get_ty ty2)
313 get_ty (HsFunTy ty1 ty2)              = unionUniqSets (get_ty ty1) (get_ty ty2)
314 get_ty (HsListTy ty)                  = set_name listTyCon_name `unionUniqSets` get_ty ty
315 get_ty (HsTupleTy (HsTupCon n _) tys) = set_name n `unionUniqSets` get_tys tys
316 get_ty (HsUsgTy _ ty)                 = get_ty ty
317 get_ty (HsUsgForAllTy _ ty)           = get_ty ty
318 get_ty (HsForAllTy _ ctxt mty)        = get_ctxt ctxt `unionUniqSets` get_ty mty
319 get_ty (HsPredTy (HsPClass name _))   = set_name name
320 get_ty (HsPredTy (HsPIParam _ _))     = emptyUniqSet    -- I think
321
322 ----------------------------------------------------
323 get_tys tys = unionManyUniqSets (map get_ty tys)
324
325 ----------------------------------------------------
326 get_sigs sigs
327   = unionManyUniqSets (map get_sig sigs)
328   where 
329     get_sig (ClassOpSig _ _ _ ty _) = get_ty ty
330     get_sig (FixSig _)              = emptyUniqSet
331     get_sig other = panic "TcTyClsDecls:get_sig"
332
333 ----------------------------------------------------
334 set_name name = unitUniqSet (getUnique name)
335 set_to_bag set = listToBag (uniqSetToList set)
336 \end{code}
337
338
339 \begin{code}
340 typeCycleErr, classCycleErr :: [[RenamedTyClDecl]] -> Message
341
342 typeCycleErr syn_cycles
343   = vcat (map (pp_cycle "Cycle in type declarations:") syn_cycles)
344
345 classCycleErr cls_cycles
346   = vcat (map (pp_cycle "Cycle in class declarations:") cls_cycles)
347
348 pp_cycle str decls
349   = hang (text str)
350          4 (vcat (map pp_decl decls))
351   where
352     pp_decl decl
353       = hsep [quotes (ppr name), ptext SLIT("at"), ppr (getSrcLoc name)]
354      where
355         name = tyClDeclName decl
356 \end{code}