[project @ 1999-05-28 19:24:26 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcTyDecls.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1996-1998
3 %
4 \section[TcTyDecls]{Typecheck type declarations}
5
6 \begin{code}
7 module TcTyDecls (
8         tcTyDecl, kcTyDecl, 
9         tcConDecl,
10         mkDataBinds
11     ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn            ( MonoBinds(..), 
16                           TyClDecl(..), ConDecl(..), ConDetails(..), BangType(..),
17                           andMonoBindList
18                         )
19 import RnHsSyn          ( RenamedTyClDecl, RenamedConDecl )
20 import TcHsSyn          ( TcMonoBinds )
21 import BasicTypes       ( RecFlag(..), NewOrData(..) )
22
23 import TcMonoType       ( tcExtendTopTyVarScope, tcExtendTyVarScope, 
24                           tcHsTypeKind, tcHsType, tcHsTopType, tcHsTopBoxedType,
25                           tcContext, tcHsTopTypeKind
26                         )
27 import TcType           ( zonkTcTyVarToTyVar, zonkTcThetaType )
28 import TcEnv            ( tcLookupTy, TcTyThing(..) )
29 import TcMonad
30 import TcUnify          ( unifyKind )
31
32 import Class            ( Class )
33 import DataCon          ( DataCon, dataConSig, mkDataCon, isNullaryDataCon,
34                           dataConFieldLabels, dataConId,
35                           markedStrict, notMarkedStrict, markedUnboxed
36                         )
37 import MkId             ( mkDataConId, mkRecordSelId, mkNewTySelId )
38 import Id               ( getIdUnfolding )
39 import CoreUnfold       ( getUnfoldingTemplate )
40 import FieldLabel
41 import Var              ( Id, TyVar )
42 import Name             ( Name, isLocallyDefined, OccName, NamedThing(..), nameUnique )
43 import Outputable
44 import TyCon            ( TyCon, ArgVrcs, mkSynTyCon, mkAlgTyCon, isAlgTyCon, 
45                           isSynTyCon, tyConDataCons, isNewTyCon
46                         )
47 import Type             ( getTyVar, tyVarsOfTypes,
48                           mkTyConApp, mkTyVarTys, mkForAllTys, mkFunTy,
49                           mkTyVarTy,
50                           mkArrowKind, mkArrowKinds, boxedTypeKind,
51                           isUnboxedType, Type, ThetaType
52                         )
53 import Var              ( tyVarKind )
54 import VarSet           ( intersectVarSet, isEmptyVarSet )
55 import Util             ( equivClasses )
56 import FiniteMap        ( FiniteMap, lookupWithDefaultFM )
57 \end{code}
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection{Kind checking}
62 %*                                                                      *
63 %************************************************************************
64
65 \begin{code}
66 kcTyDecl :: RenamedTyClDecl -> TcM s ()
67
68 kcTyDecl (TySynonym name tyvar_names rhs src_loc)
69   = tcLookupTy name                             `thenNF_Tc` \ (kind, _, _) ->
70     tcExtendTopTyVarScope kind tyvar_names      $ \ _ result_kind ->
71     tcHsTypeKind rhs                            `thenTc` \ (rhs_kind, _) ->
72     unifyKind result_kind rhs_kind
73
74 kcTyDecl (TyData _ context tycon_name tyvar_names con_decls _ _ src_loc)
75   = tcLookupTy tycon_name                       `thenNF_Tc` \ (kind, _, _) ->
76     tcExtendTopTyVarScope kind tyvar_names      $ \ result_kind _ ->
77     tcContext context                           `thenTc_` 
78     mapTc kcConDecl con_decls                   `thenTc_`
79     returnTc ()
80
81 kcConDecl (ConDecl _ ex_tvs ex_ctxt details loc)
82   = tcAddSrcLoc loc                     (
83     tcExtendTyVarScope ex_tvs           ( \ tyvars -> 
84     tcContext ex_ctxt                   `thenTc_`
85     kc_con details                      `thenTc_`
86     returnTc ()
87     ))
88   where
89     kc_con (VanillaCon btys)    = mapTc kc_bty btys             `thenTc_` returnTc ()
90     kc_con (InfixCon bty1 bty2) = mapTc kc_bty [bty1,bty2]      `thenTc_` returnTc ()
91     kc_con (NewCon ty _)        = tcHsType ty                   `thenTc_` returnTc ()
92     kc_con (RecCon flds)        = mapTc kc_field flds           `thenTc_` returnTc ()
93
94     kc_bty (Banged ty)   = tcHsType ty
95     kc_bty (Unbanged ty) = tcHsType ty
96     kc_bty (Unpacked ty) = tcHsType ty
97
98     kc_field (_, bty)    = kc_bty bty
99 \end{code}
100
101
102 %************************************************************************
103 %*                                                                      *
104 \subsection{Type checking}
105 %*                                                                      *
106 %************************************************************************
107
108 \begin{code}
109 tcTyDecl :: RecFlag -> FiniteMap Name ArgVrcs -> RenamedTyClDecl -> TcM s TyCon
110
111 tcTyDecl is_rec rec_vrcs (TySynonym tycon_name tyvar_names rhs src_loc)
112   = tcLookupTy tycon_name                               `thenNF_Tc` \ (tycon_kind, Just arity, _) ->
113     tcExtendTopTyVarScope tycon_kind tyvar_names        $ \ tyvars _ ->
114     tcHsTopTypeKind rhs                                 `thenTc` \ (_, rhs_ty) ->
115     let
116         -- Construct the tycon
117         argvrcs = lookupWithDefaultFM rec_vrcs (pprPanic "tcTyDecl: argvrcs:" $ ppr tycon_name)
118                                       tycon_name
119         tycon = mkSynTyCon tycon_name tycon_kind arity tyvars rhs_ty argvrcs
120     in
121     returnTc tycon
122
123
124 tcTyDecl is_rec rec_vrcs (TyData data_or_new context tycon_name tyvar_names con_decls derivings pragmas src_loc)
125   =     -- Lookup the pieces
126     tcLookupTy tycon_name                               `thenNF_Tc` \ (tycon_kind, _, ATyCon rec_tycon) ->
127     tcExtendTopTyVarScope tycon_kind tyvar_names        $ \ tyvars _ ->
128
129         -- Typecheck the pieces
130     tcContext context                                   `thenTc` \ ctxt ->
131     mapTc (tcConDecl rec_tycon tyvars ctxt) con_decls   `thenTc` \ data_cons ->
132     tc_derivs derivings                                 `thenTc` \ derived_classes ->
133
134     let
135         -- Construct the tycon
136         real_data_or_new = case data_or_new of
137                                 NewType -> NewType
138                                 DataType | all isNullaryDataCon data_cons -> EnumType
139                                          | otherwise                      -> DataType
140
141         argvrcs = lookupWithDefaultFM rec_vrcs (pprPanic "tcTyDecl: argvrcs:" $ ppr tycon_name)
142                                       tycon_name
143
144         tycon = mkAlgTyCon tycon_name tycon_kind tyvars ctxt argvrcs
145                            data_cons
146                            derived_classes
147                            Nothing              -- Not a dictionary
148                            real_data_or_new is_rec
149     in
150     returnTc tycon
151   where
152         tc_derivs Nothing   = returnTc []
153         tc_derivs (Just ds) = mapTc tc_deriv ds
154
155         tc_deriv name = tcLookupTy name `thenTc` \ (_, _, AClass clas) ->
156                         returnTc clas
157 \end{code}
158
159
160 %************************************************************************
161 %*                                                                      *
162 \subsection{Type check constructors}
163 %*                                                                      *
164 %************************************************************************
165
166 \begin{code}
167 tcConDecl :: TyCon -> [TyVar] -> ThetaType -> RenamedConDecl -> TcM s DataCon
168
169 tcConDecl tycon tyvars ctxt (ConDecl name ex_tvs ex_ctxt details src_loc)
170   = tcAddSrcLoc src_loc                 $
171     tcExtendTyVarScope ex_tvs           $ \ ex_tyvars -> 
172     tcContext ex_ctxt                   `thenTc` \ ex_theta ->
173     tc_con_decl_help tycon tyvars ctxt name ex_tyvars ex_theta details
174
175 tc_con_decl_help tycon tyvars ctxt name ex_tyvars ex_theta details
176   = case details of
177         VanillaCon btys    -> tc_datacon btys
178         InfixCon bty1 bty2 -> tc_datacon [bty1,bty2]
179         NewCon ty mb_f     -> tc_newcon ty mb_f
180         RecCon fields      -> tc_rec_con fields
181   where
182     tc_datacon btys
183       = let
184             arg_stricts = map get_strictness btys
185             tys         = map get_pty btys
186         in
187         mapTc tcHsTopType tys `thenTc` \ arg_tys ->
188         mk_data_con arg_stricts arg_tys []
189
190     tc_newcon ty mb_f
191       = tcHsTopBoxedType ty     `thenTc` \ arg_ty ->
192             -- can't allow an unboxed type here, because we're effectively
193             -- going to remove the constructor while coercing it to a boxed type.
194         let
195           field_label =
196             case mb_f of
197               Nothing -> []
198               Just f  -> [mkFieldLabel (getName f) arg_ty (head allFieldLabelTags)]
199         in            
200         mk_data_con [notMarkedStrict] [arg_ty] field_label
201
202     tc_rec_con fields
203       = checkTc (null ex_tyvars) (exRecConErr name)         `thenTc_`
204         mapTc tc_field fields   `thenTc` \ field_label_infos_s ->
205         let
206             field_label_infos = concat field_label_infos_s
207             arg_stricts       = [strict | (_, _, strict) <- field_label_infos]
208             arg_tys           = [ty     | (_, ty, _)     <- field_label_infos]
209
210             field_labels      = [ mkFieldLabel (getName name) ty tag 
211                               | ((name, ty, _), tag) <- field_label_infos `zip` allFieldLabelTags ]
212         in
213         mk_data_con arg_stricts arg_tys field_labels
214
215     tc_field (field_label_names, bty)
216       = tcHsTopType (get_pty bty)       `thenTc` \ field_ty ->
217         returnTc [(name, field_ty, get_strictness bty) | name <- field_label_names]
218
219     mk_data_con arg_stricts arg_tys fields
220       =         -- Now we've checked all the field types we must
221                 -- zonk the existential tyvars to finish the kind
222                 -- inference on their kinds, and commit them to being
223                 -- immutable type variables.  (The top-level tyvars are
224                 -- already fixed, by the preceding kind-inference pass.)
225         mapNF_Tc zonkTcTyVarToTyVar ex_tyvars   `thenNF_Tc` \ ex_tyvars' ->
226         zonkTcThetaType ex_theta                `thenNF_Tc` \ ex_theta' ->
227         let
228            data_con = mkDataCon name arg_stricts fields
229                            tyvars (thinContext arg_tys ctxt)
230                            ex_tyvars' ex_theta'
231                            arg_tys
232                            tycon data_con_id
233            data_con_id = mkDataConId data_con
234         in
235         returnNF_Tc data_con
236
237 -- The context for a data constructor should be limited to
238 -- the type variables mentioned in the arg_tys
239 thinContext arg_tys ctxt
240   = filter in_arg_tys ctxt
241   where
242       arg_tyvars = tyVarsOfTypes arg_tys
243       in_arg_tys (clas,tys) = not $ isEmptyVarSet $ 
244                               tyVarsOfTypes tys `intersectVarSet` arg_tyvars
245   
246 get_strictness (Banged   _) = markedStrict
247 get_strictness (Unbanged _) = notMarkedStrict
248 get_strictness (Unpacked _) = markedUnboxed
249
250 get_pty (Banged ty)   = ty
251 get_pty (Unbanged ty) = ty
252 get_pty (Unpacked ty) = ty
253 \end{code}
254
255
256
257 %************************************************************************
258 %*                                                                      *
259 \subsection{Generating constructor/selector bindings for data declarations}
260 %*                                                                      *
261 %************************************************************************
262
263 \begin{code}
264 mkDataBinds :: [TyCon] -> TcM s ([Id], TcMonoBinds)
265 mkDataBinds [] = returnTc ([], EmptyMonoBinds)
266 mkDataBinds (tycon : tycons) 
267   | isSynTyCon tycon = mkDataBinds tycons
268   | otherwise        = mkDataBinds_one tycon    `thenTc` \ (ids1, b1) ->
269                        mkDataBinds tycons       `thenTc` \ (ids2, b2) ->
270                        returnTc (ids1++ids2, b1 `AndMonoBinds` b2)
271
272 mkDataBinds_one tycon
273   = mapTc (mkRecordSelector tycon) groups       `thenTc` \ sel_ids ->
274     let
275         data_ids = map dataConId data_cons ++ sel_ids
276
277         -- For the locally-defined things
278         -- we need to turn the unfoldings inside the Ids into bindings,
279         binds | isLocallyDefined tycon
280               = [ CoreMonoBind data_id (getUnfoldingTemplate (getIdUnfolding data_id))
281                 | data_id <- data_ids, isLocallyDefined data_id
282                 ]
283               | otherwise
284               = []
285     in  
286     returnTc (data_ids, andMonoBindList binds)
287   where
288     data_cons = tyConDataCons tycon
289     fields = [ (con, field) | con   <- data_cons,
290                               field <- dataConFieldLabels con
291              ]
292
293         -- groups is list of fields that share a common name
294     groups = equivClasses cmp_name fields
295     cmp_name (_, field1) (_, field2) 
296         = fieldLabelName field1 `compare` fieldLabelName field2
297 \end{code}
298
299 \begin{code}
300 mkRecordSelector tycon fields@((first_con, first_field_label) : other_fields)
301                 -- These fields all have the same name, but are from
302                 -- different constructors in the data type
303         -- Check that all the fields in the group have the same type
304         -- This check assumes that all the constructors of a given
305         -- data type use the same type variables
306   = (if null other_fields then (\x->x) else
307         let lbls = [fieldLabelName f | (_,f) <- fields]
308             uniqs = [nameUnique l | l <- lbls]
309
310         in
311         pprTrace "mkRecordSelector" (vcat [ppr fields,
312                                         ppr lbls,
313                                         ppr uniqs,
314                                         hsep [text (show (field_name `compare` fieldLabelName f)) | (_,f) <- fields]
315                                         ]))
316                                   
317     checkTc (all (== field_ty) other_tys)
318             (fieldTypeMisMatch field_name)      `thenTc_`
319     returnTc selector_id
320   where
321     field_ty   = fieldLabelType first_field_label
322     field_name = fieldLabelName first_field_label
323     other_tys  = [fieldLabelType fl | (_, fl) <- other_fields]
324     (tyvars, _, _, _, _, _) = dataConSig first_con
325     data_ty  = mkTyConApp tycon (mkTyVarTys tyvars)
326     -- tyvars of first_con may be free in field_ty
327     -- Now build the selector
328
329     selector_ty :: Type
330     selector_ty  = mkForAllTys tyvars $ 
331                    mkFunTy data_ty $
332                    field_ty
333       
334     selector_id :: Id
335     selector_id 
336       | isNewTyCon tycon    = mkNewTySelId  first_field_label selector_ty
337       | otherwise           = mkRecordSelId first_field_label selector_ty
338 \end{code}
339
340
341 Errors and contexts
342 ~~~~~~~~~~~~~~~~~~~
343 \begin{code}
344 fieldTypeMisMatch field_name
345   = sep [ptext SLIT("Declared types differ for field"), quotes (ppr field_name)]
346
347 exRecConErr name
348   = ptext SLIT("Can't combine named fields with locally-quantified type variables")
349     $$
350     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
351 \end{code}