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