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