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