[project @ 2000-09-22 15:56:12 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         tcTyDecl1, 
9         kcConDetails, 
10         mkImplicitDataBinds, mkNewTyConRep
11     ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn            ( MonoBinds(..), 
16                           TyClDecl(..), ConDecl(..), ConDetails(..), BangType(..),
17                           getBangType
18                         )
19 import RnHsSyn          ( RenamedTyClDecl, RenamedConDecl, RenamedContext )
20 import TcHsSyn          ( TcMonoBinds, idsToMonoBinds )
21 import BasicTypes       ( NewOrData(..) )
22
23 import TcMonoType       ( tcHsType, tcHsSigType, tcHsBoxedSigType, kcTyVarScope, tcClassContext,
24                           kcHsContext, kcHsSigType, mkImmutTyVars
25                         )
26 import TcEnv            ( tcExtendTyVarEnv, tcLookupTy, tcLookupValueByKey, TyThing(..), TyThingDetails(..) )
27 import TcMonad
28
29 import Class            ( ClassContext )
30 import DataCon          ( DataCon, mkDataCon, 
31                           dataConFieldLabels, dataConId, dataConWrapId,
32                           markedStrict, notMarkedStrict, markedUnboxed, dataConRepType
33                         )
34 import MkId             ( mkDataConId, mkDataConWrapId, mkRecordSelId )
35 import FieldLabel
36 import Var              ( Id, TyVar )
37 import Name             ( Name, isLocallyDefined, NamedThing(..) )
38 import Outputable
39 import TyCon            ( TyCon, isSynTyCon, isNewTyCon,
40                           tyConDataConsIfAvailable, tyConTyVars
41                         )
42 import Type             ( tyVarsOfTypes, splitFunTy, applyTys,
43                           mkTyConApp, mkTyVarTys, mkForAllTys, 
44                           splitAlgTyConApp_maybe, Type
45                         )
46 import TysWiredIn       ( unitTy )
47 import VarSet           ( intersectVarSet, isEmptyVarSet )
48 import Unique           ( unpackCStringIdKey, unpackCStringUtf8IdKey )
49 import Util             ( equivClasses )
50 \end{code}
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection{Type checking}
55 %*                                                                      *
56 %************************************************************************
57
58 \begin{code}
59 tcTyDecl1 :: RenamedTyClDecl -> TcM s (Name, TyThingDetails)
60 tcTyDecl1 (TySynonym tycon_name tyvar_names rhs src_loc)
61   = tcLookupTy tycon_name                       `thenNF_Tc` \ (ATyCon tycon) ->
62     tcExtendTyVarEnv (tyConTyVars tycon)        $
63     tcHsType rhs                                `thenTc` \ rhs_ty ->
64         -- Note tcHsType not tcHsSigType; we allow type synonyms
65         -- that aren't types; e.g.  type List = []
66         --
67         -- If the RHS mentions tyvars that aren't in scope, we'll 
68         -- quantify over them:
69         --      e.g.    type T = a->a
70         -- will become  type T = forall a. a->a
71         --
72         -- With gla-exts that's right, but for H98 we should complain. 
73         -- We can now do that here without falling into
74         -- a black hole, we still do it in rnDecl (TySynonym case)
75
76     returnTc (tycon_name, SynTyDetails rhs_ty)
77
78 tcTyDecl1 (TyData new_or_data context tycon_name _ con_decls _ derivings _  src_loc)
79   = tcLookupTy tycon_name                       `thenNF_Tc` \ (ATyCon tycon) ->
80     let
81         tyvars = tyConTyVars tycon
82     in
83     tcExtendTyVarEnv tyvars                             $
84
85         -- Typecheck the pieces
86     tcClassContext context                                      `thenTc` \ ctxt ->
87     tc_derivs derivings                                         `thenTc` \ derived_classes ->
88     mapTc (tcConDecl new_or_data tycon tyvars ctxt) con_decls   `thenTc` \ data_cons ->
89
90     returnTc (tycon_name, DataTyDetails ctxt data_cons derived_classes)
91   where
92     tc_derivs Nothing   = returnTc []
93     tc_derivs (Just ds) = mapTc tc_deriv ds
94
95     tc_deriv name = tcLookupTy name `thenTc` \ (AClass clas) ->
96                     returnTc clas
97 \end{code}
98
99 \begin{code}
100 mkNewTyConRep :: TyCon -> Type
101 -- Find the representation type for this newtype TyCon
102 -- The trick is to to deal correctly with recursive newtypes
103 -- such as      newtype T = MkT T
104
105 mkNewTyConRep tc
106   = mkForAllTys tvs (loop [] (mkTyConApp tc (mkTyVarTys tvs)))
107   where
108     tvs = tyConTyVars tc
109     loop tcs ty = case splitAlgTyConApp_maybe ty of {
110                         Nothing -> ty ;
111                         Just (tc, tys, data_cons) | not (isNewTyCon tc) -> ty
112                                                   | tc `elem` tcs       -> unitTy
113                                                   | otherwise           ->
114
115                   case splitFunTy (applyTys (dataConRepType (head data_cons)) tys) of
116                         (rep_ty, _) -> loop (tc:tcs) rep_ty
117                   }
118 \end{code}
119
120
121 %************************************************************************
122 %*                                                                      *
123 \subsection{Kind and type check constructors}
124 %*                                                                      *
125 %************************************************************************
126
127 \begin{code}
128 kcConDetails :: RenamedContext -> ConDetails Name -> TcM s ()
129 kcConDetails ex_ctxt details
130   = kcHsContext ex_ctxt         `thenTc_`
131     kc_con_details details
132   where
133     kc_con_details (VanillaCon btys)    = mapTc_ kc_bty btys
134     kc_con_details (InfixCon bty1 bty2) = mapTc_ kc_bty [bty1,bty2]
135     kc_con_details (RecCon flds)        = mapTc_ kc_field flds
136
137     kc_field (_, bty) = kc_bty bty
138
139     kc_bty bty = kcHsSigType (getBangType bty)
140
141 tcConDecl :: NewOrData -> TyCon -> [TyVar] -> ClassContext -> RenamedConDecl -> TcM s DataCon
142
143 tcConDecl new_or_data tycon tyvars ctxt (ConDecl name wkr_name ex_tvs ex_ctxt details src_loc)
144   = tcAddSrcLoc src_loc                                 $
145     kcTyVarScope ex_tvs (kcConDetails ex_ctxt details)  `thenTc` \ ex_tv_kinds ->
146     let
147         ex_tyvars = mkImmutTyVars ex_tv_kinds
148     in
149     tcExtendTyVarEnv ex_tyvars                          $
150     tcClassContext ex_ctxt                              `thenTc` \ ex_theta ->
151     case details of
152         VanillaCon btys    -> tc_datacon ex_tyvars ex_theta btys
153         InfixCon bty1 bty2 -> tc_datacon ex_tyvars ex_theta [bty1,bty2]
154         RecCon fields      -> tc_rec_con ex_tyvars ex_theta fields
155   where
156     tc_sig_type = case new_or_data of
157                     DataType -> tcHsSigType
158                     NewType  -> tcHsBoxedSigType
159             -- Can't allow an unboxed type here, because we're effectively
160             -- going to remove the constructor while coercing it to a boxed type.
161
162     tc_datacon ex_tyvars ex_theta btys
163       = let
164             arg_stricts = map getBangStrictness btys
165             tys         = map getBangType btys
166         in
167         mapTc tc_sig_type tys   `thenTc` \ arg_tys ->
168         mk_data_con ex_tyvars ex_theta arg_stricts arg_tys []
169
170     tc_rec_con ex_tyvars ex_theta fields
171       = checkTc (null ex_tyvars) (exRecConErr name)     `thenTc_`
172         mapTc tc_field (fields `zip` allFieldLabelTags) `thenTc` \ field_labels_s ->
173         let
174             field_labels = concat field_labels_s
175             arg_stricts = [str | (ns, bty) <- fields, 
176                                   let str = getBangStrictness bty, 
177                                   n <- ns               -- One for each.  E.g   x,y,z :: !Int
178                           ]
179         in
180         mk_data_con ex_tyvars ex_theta arg_stricts 
181                     (map fieldLabelType field_labels) field_labels
182
183     tc_field ((field_label_names, bty), tag)
184       = tc_sig_type (getBangType bty)   `thenTc` \ field_ty ->
185         returnTc [mkFieldLabel (getName name) tycon field_ty tag | name <- field_label_names]
186
187     mk_data_con ex_tyvars ex_theta arg_stricts arg_tys fields
188       = let
189            data_con = mkDataCon name arg_stricts fields
190                            tyvars (thinContext arg_tys ctxt)
191                            ex_tyvars ex_theta
192                            arg_tys
193                            tycon data_con_id data_con_wrap_id
194
195            data_con_id      = mkDataConId wkr_name data_con
196            data_con_wrap_id = mkDataConWrapId data_con
197         in
198         returnNF_Tc data_con
199
200 -- The context for a data constructor should be limited to
201 -- the type variables mentioned in the arg_tys
202 thinContext arg_tys ctxt
203   = filter in_arg_tys ctxt
204   where
205       arg_tyvars = tyVarsOfTypes arg_tys
206       in_arg_tys (clas,tys) = not $ isEmptyVarSet $ 
207                               tyVarsOfTypes tys `intersectVarSet` arg_tyvars
208
209 getBangStrictness (Banged   _) = markedStrict
210 getBangStrictness (Unbanged _) = notMarkedStrict
211 getBangStrictness (Unpacked _) = markedUnboxed
212 \end{code}
213
214
215
216 %************************************************************************
217 %*                                                                      *
218 \subsection{Generating constructor/selector bindings for data declarations}
219 %*                                                                      *
220 %************************************************************************
221
222 \begin{code}
223 mkImplicitDataBinds :: [TyCon] -> TcM s ([Id], TcMonoBinds)
224 mkImplicitDataBinds [] = returnTc ([], EmptyMonoBinds)
225 mkImplicitDataBinds (tycon : tycons) 
226   | isSynTyCon tycon = mkImplicitDataBinds tycons
227   | otherwise        = mkImplicitDataBinds_one tycon    `thenTc` \ (ids1, b1) ->
228                        mkImplicitDataBinds tycons       `thenTc` \ (ids2, b2) ->
229                        returnTc (ids1++ids2, b1 `AndMonoBinds` b2)
230
231 mkImplicitDataBinds_one tycon
232   = mapTc (mkRecordSelector tycon) groups       `thenTc` \ sel_ids ->
233     let
234         unf_ids = sel_ids ++ data_con_wrapper_ids
235         all_ids = map dataConId data_cons ++ unf_ids 
236
237         -- For the locally-defined things
238         -- we need to turn the unfoldings inside the selector Ids into bindings,
239         -- and build bindigns for the constructor wrappers
240         binds | isLocallyDefined tycon = idsToMonoBinds unf_ids
241               | otherwise              = EmptyMonoBinds
242     in  
243     returnTc (all_ids, binds)
244   where
245     data_cons = tyConDataConsIfAvailable tycon
246         -- Abstract types mean we don't bring the 
247         -- data cons into scope, which should be fine
248
249     data_con_wrapper_ids = map dataConWrapId data_cons
250
251     fields = [ (con, field) | con   <- data_cons,
252                               field <- dataConFieldLabels con
253              ]
254
255         -- groups is list of fields that share a common name
256     groups = equivClasses cmp_name fields
257     cmp_name (_, field1) (_, field2) 
258         = fieldLabelName field1 `compare` fieldLabelName field2
259 \end{code}
260
261 \begin{code}
262 mkRecordSelector tycon fields@((first_con, first_field_label) : other_fields)
263                 -- These fields all have the same name, but are from
264                 -- different constructors in the data type
265         -- Check that all the fields in the group have the same type
266         -- This check assumes that all the constructors of a given
267         -- data type use the same type variables
268   = checkTc (all (== field_ty) other_tys)
269             (fieldTypeMisMatch field_name)      `thenTc_`
270     tcLookupValueByKey unpackCStringIdKey       `thenTc` \ unpack_id ->
271     tcLookupValueByKey unpackCStringUtf8IdKey   `thenTc` \ unpackUtf8_id ->
272     returnTc (mkRecordSelId tycon first_field_label unpack_id unpackUtf8_id)
273   where
274     field_ty   = fieldLabelType first_field_label
275     field_name = fieldLabelName first_field_label
276     other_tys  = [fieldLabelType fl | (_, fl) <- other_fields]
277 \end{code}
278
279
280 Errors and contexts
281 ~~~~~~~~~~~~~~~~~~~
282 \begin{code}
283 fieldTypeMisMatch field_name
284   = sep [ptext SLIT("Declared types differ for field"), quotes (ppr field_name)]
285
286 exRecConErr name
287   = ptext SLIT("Can't combine named fields with locally-quantified type variables")
288     $$
289     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
290 \end{code}