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