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