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