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