[project @ 2000-03-24 17:49:29 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         mkImplicitDataBinds
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, idsToMonoBinds )
21 import BasicTypes       ( RecFlag(..), NewOrData(..) )
22
23 import TcMonoType       ( tcExtendTopTyVarScope, tcExtendTyVarScope, 
24                           tcHsTypeKind, kcHsType, tcHsTopType, tcHsTopBoxedType,
25                           tcContext, tcHsTopTypeKind
26                         )
27 import TcType           ( zonkTcTyVarToTyVar, zonkTcClassConstraints )
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, dataConWrapId,
35                           markedStrict, notMarkedStrict, markedUnboxed
36                         )
37 import MkId             ( mkDataConId, mkDataConWrapId, mkRecordSelId )
38 import FieldLabel
39 import Var              ( Id, TyVar )
40 import Name             ( Name, isLocallyDefined, OccName, NamedThing(..), nameUnique )
41 import Outputable
42 import TyCon            ( TyCon, ArgVrcs, mkSynTyCon, mkAlgTyCon, 
43                           isSynTyCon, tyConDataCons, isNewTyCon
44                         )
45 import Type             ( getTyVar, tyVarsOfTypes,
46                           mkTyConApp, mkTyVarTys, mkForAllTys, mkFunTy,
47                           mkTyVarTy, splitForAllTys, isForAllTy,
48                           mkArrowKind, mkArrowKinds, boxedTypeKind,
49                           isUnboxedType, Type, ThetaType, classesOfPreds
50                         )
51 import Var              ( tyVarKind )
52 import VarSet           ( intersectVarSet, isEmptyVarSet )
53 import Util             ( equivClasses )
54 import FiniteMap        ( FiniteMap, lookupWithDefaultFM )
55 import CmdLineOpts      ( opt_GlasgowExts )
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 _)        = kcHsType ty
91     kc_con (RecCon flds)        = mapTc kc_field flds           `thenTc_` returnTc ()
92
93     kc_bty (Banged ty)   = kcHsType ty
94     kc_bty (Unbanged ty) = kcHsType ty
95     kc_bty (Unpacked ty) = kcHsType 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     tcHsTopTypeKind rhs                                 `thenTc` \ (_, rhs_ty) ->
114         -- If the RHS mentions tyvars that aren't in scope, we'll 
115         -- quantify over them.  With gla-exts that's right, but for H98
116         -- we should complain. We can't do that here without falling into
117         -- a black hole, so we do it in rnDecl (TySynonym case)
118     let
119         -- Construct the tycon
120         argvrcs = lookupWithDefaultFM rec_vrcs (pprPanic "tcTyDecl: argvrcs:" $ ppr tycon_name)
121                                       tycon_name
122         tycon = mkSynTyCon tycon_name tycon_kind arity tyvars rhs_ty argvrcs
123     in
124     returnTc tycon
125
126
127 tcTyDecl is_rec rec_vrcs (TyData data_or_new context tycon_name tyvar_names con_decls derivings pragmas src_loc)
128   =     -- Lookup the pieces
129     tcLookupTy tycon_name                               `thenNF_Tc` \ (tycon_kind, _, ATyCon rec_tycon) ->
130     tcExtendTopTyVarScope tycon_kind tyvar_names        $ \ tyvars _ ->
131
132         -- Typecheck the pieces
133     tcContext context                                   `thenTc` \ ctxt ->
134     let ctxt' = classesOfPreds ctxt in
135     mapTc (tcConDecl rec_tycon tyvars ctxt') con_decls  `thenTc` \ data_cons ->
136     tc_derivs derivings                                 `thenTc` \ derived_classes ->
137
138     let
139         -- Construct the tycon
140         real_data_or_new = case data_or_new of
141                                 NewType -> NewType
142                                 DataType | all isNullaryDataCon data_cons -> EnumType
143                                          | otherwise                      -> DataType
144
145         argvrcs = lookupWithDefaultFM rec_vrcs (pprPanic "tcTyDecl: argvrcs:" $ ppr tycon_name)
146                                       tycon_name
147
148         tycon = mkAlgTyCon tycon_name tycon_kind tyvars ctxt' argvrcs
149                            data_cons
150                            derived_classes
151                            Nothing              -- Not a dictionary
152                            real_data_or_new is_rec
153     in
154     returnTc tycon
155   where
156         tc_derivs Nothing   = returnTc []
157         tc_derivs (Just ds) = mapTc tc_deriv ds
158
159         tc_deriv name = tcLookupTy name `thenTc` \ (_, _, AClass clas) ->
160                         returnTc clas
161 \end{code}
162
163
164 %************************************************************************
165 %*                                                                      *
166 \subsection{Type check constructors}
167 %*                                                                      *
168 %************************************************************************
169
170 \begin{code}
171 tcConDecl :: TyCon -> [TyVar] -> [(Class,[Type])] -> RenamedConDecl -> TcM s DataCon
172
173 tcConDecl tycon tyvars ctxt (ConDecl name wkr_name ex_tvs ex_ctxt details src_loc)
174   = tcAddSrcLoc src_loc                 $
175     tcExtendTyVarScope ex_tvs           $ \ ex_tyvars -> 
176     tcContext ex_ctxt                   `thenTc` \ ex_theta ->
177     let 
178         ex_ctxt' = classesOfPreds ex_theta
179     in
180     tc_con_decl_help tycon tyvars ctxt name wkr_name ex_tyvars ex_ctxt' details
181
182 tc_con_decl_help tycon tyvars ctxt name wkr_name ex_tyvars ex_theta details
183   = case details of
184         VanillaCon btys    -> tc_datacon btys
185         InfixCon bty1 bty2 -> tc_datacon [bty1,bty2]
186         NewCon ty mb_f     -> tc_newcon ty mb_f
187         RecCon fields      -> tc_rec_con fields
188   where
189     tc_datacon btys
190       = let
191             arg_stricts = map get_strictness btys
192             tys         = map get_pty btys
193         in
194         mapTc tcHsTopType tys `thenTc` \ arg_tys ->
195         mk_data_con arg_stricts arg_tys []
196
197     tc_newcon ty mb_f
198       = tcHsTopBoxedType ty     `thenTc` \ arg_ty ->
199             -- can't allow an unboxed type here, because we're effectively
200             -- going to remove the constructor while coercing it to a boxed type.
201         let
202           field_label =
203             case mb_f of
204               Nothing -> []
205               Just f  -> [mkFieldLabel (getName f) arg_ty (head allFieldLabelTags)]
206         in            
207         mk_data_con [notMarkedStrict] [arg_ty] field_label
208
209     tc_rec_con fields
210       = checkTc (null ex_tyvars) (exRecConErr name)         `thenTc_`
211         mapTc tc_field fields   `thenTc` \ field_label_infos_s ->
212         let
213             field_label_infos = concat field_label_infos_s
214             arg_stricts       = [strict | (_, _, strict) <- field_label_infos]
215             arg_tys           = [ty     | (_, ty, _)     <- field_label_infos]
216
217             field_labels      = [ mkFieldLabel (getName name) ty tag 
218                               | ((name, ty, _), tag) <- field_label_infos `zip` allFieldLabelTags ]
219         in
220         mk_data_con arg_stricts arg_tys field_labels
221
222     tc_field (field_label_names, bty)
223       = tcHsTopType (get_pty bty)       `thenTc` \ field_ty ->
224         returnTc [(name, field_ty, get_strictness bty) | name <- field_label_names]
225
226     mk_data_con arg_stricts arg_tys fields
227       =         -- Now we've checked all the field types we must
228                 -- zonk the existential tyvars to finish the kind
229                 -- inference on their kinds, and commit them to being
230                 -- immutable type variables.  (The top-level tyvars are
231                 -- already fixed, by the preceding kind-inference pass.)
232         mapNF_Tc zonkTcTyVarToTyVar ex_tyvars   `thenNF_Tc` \ ex_tyvars' ->
233         zonkTcClassConstraints  ex_theta        `thenNF_Tc` \ ex_theta' ->
234         let
235            data_con = mkDataCon name arg_stricts fields
236                            tyvars (thinContext arg_tys ctxt)
237                            ex_tyvars' ex_theta'
238                            arg_tys
239                            tycon data_con_id data_con_wrap_id
240            data_con_id      = mkDataConId wkr_name data_con
241            data_con_wrap_id = mkDataConWrapId data_con
242         in
243         returnNF_Tc data_con
244
245 -- The context for a data constructor should be limited to
246 -- the type variables mentioned in the arg_tys
247 thinContext arg_tys ctxt
248   = filter in_arg_tys ctxt
249   where
250       arg_tyvars = tyVarsOfTypes arg_tys
251       in_arg_tys (clas,tys) = not $ isEmptyVarSet $ 
252                               tyVarsOfTypes tys `intersectVarSet` arg_tyvars
253   
254 get_strictness (Banged   _) = markedStrict
255 get_strictness (Unbanged _) = notMarkedStrict
256 get_strictness (Unpacked _) = markedUnboxed
257
258 get_pty (Banged ty)   = ty
259 get_pty (Unbanged ty) = ty
260 get_pty (Unpacked ty) = ty
261 \end{code}
262
263
264
265 %************************************************************************
266 %*                                                                      *
267 \subsection{Generating constructor/selector bindings for data declarations}
268 %*                                                                      *
269 %************************************************************************
270
271 \begin{code}
272 mkImplicitDataBinds :: [TyCon] -> TcM s ([Id], TcMonoBinds)
273 mkImplicitDataBinds [] = returnTc ([], EmptyMonoBinds)
274 mkImplicitDataBinds (tycon : tycons) 
275   | isSynTyCon tycon = mkImplicitDataBinds tycons
276   | otherwise        = mkImplicitDataBinds_one tycon    `thenTc` \ (ids1, b1) ->
277                        mkImplicitDataBinds tycons       `thenTc` \ (ids2, b2) ->
278                        returnTc (ids1++ids2, b1 `AndMonoBinds` b2)
279
280 mkImplicitDataBinds_one tycon
281   = mapTc (mkRecordSelector tycon) groups       `thenTc` \ sel_ids ->
282     let
283         unf_ids = sel_ids ++ data_con_wrapper_ids
284         all_ids = map dataConId data_cons ++ unf_ids 
285
286         -- For the locally-defined things
287         -- we need to turn the unfoldings inside the selector Ids into bindings,
288         -- and build bindigns for the constructor wrappers
289         binds | isLocallyDefined tycon = idsToMonoBinds unf_ids
290               | otherwise              = EmptyMonoBinds
291     in  
292     returnTc (all_ids, binds)
293   where
294     data_cons = tyConDataCons tycon
295
296     data_con_wrapper_ids = map dataConWrapId data_cons
297
298     fields = [ (con, field) | con   <- data_cons,
299                               field <- dataConFieldLabels con
300              ]
301
302         -- groups is list of fields that share a common name
303     groups = equivClasses cmp_name fields
304     cmp_name (_, field1) (_, field2) 
305         = fieldLabelName field1 `compare` fieldLabelName field2
306 \end{code}
307
308 \begin{code}
309 mkRecordSelector tycon fields@((first_con, first_field_label) : other_fields)
310                 -- These fields all have the same name, but are from
311                 -- different constructors in the data type
312         -- Check that all the fields in the group have the same type
313         -- This check assumes that all the constructors of a given
314         -- data type use the same type variables
315   = checkTc (all (== field_ty) other_tys)
316             (fieldTypeMisMatch field_name)      `thenTc_`
317     returnTc (mkRecordSelId tycon first_field_label)
318   where
319     field_ty   = fieldLabelType first_field_label
320     field_name = fieldLabelName first_field_label
321     other_tys  = [fieldLabelType fl | (_, fl) <- other_fields]
322 \end{code}
323
324
325 Errors and contexts
326 ~~~~~~~~~~~~~~~~~~~
327 \begin{code}
328 fieldTypeMisMatch field_name
329   = sep [ptext SLIT("Declared types differ for field"), quotes (ppr field_name)]
330
331 exRecConErr name
332   = ptext SLIT("Can't combine named fields with locally-quantified type variables")
333     $$
334     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
335 \end{code}