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