[project @ 2000-11-20 14:48:52 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, kcConDetails, mkNewTyConRep
9     ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( TyClDecl(..), ConDecl(..), ConDetails(..), BangType(..),
14                           getBangType, conDetailsTys
15                         )
16 import RnHsSyn          ( RenamedTyClDecl, RenamedConDecl, RenamedContext )
17 import BasicTypes       ( NewOrData(..), RecFlag, isRec )
18
19 import TcMonoType       ( tcHsRecType, tcHsTyVars, tcRecClassContext,
20                           kcHsContext, kcHsSigType, kcHsBoxedSigType
21                         )
22 import TcEnv            ( tcExtendTyVarEnv, 
23                           tcLookupTyCon, tcLookupRecId, 
24                           TyThingDetails(..), RecTcEnv
25                         )
26 import TcMonad
27
28 import Class            ( ClassContext )
29 import DataCon          ( DataCon, mkDataCon, dataConFieldLabels,  markedStrict, 
30                           notMarkedStrict, markedUnboxed, dataConRepType
31                         )
32 import MkId             ( mkDataConId, mkDataConWrapId, mkRecordSelId )
33 import FieldLabel
34 import Var              ( TyVar )
35 import Name             ( Name, NamedThing(..) )
36 import Outputable
37 import TyCon            ( TyCon, isNewTyCon, tyConTyVars )
38 import Type             ( tyVarsOfTypes, splitFunTy, applyTys,
39                           mkTyConApp, mkTyVarTys, mkForAllTys, 
40                           splitAlgTyConApp_maybe, Type
41                         )
42 import TysWiredIn       ( unitTy )
43 import VarSet           ( intersectVarSet, isEmptyVarSet )
44 import PrelNames        ( unpackCStringName, unpackCStringUtf8Name )
45 import ListSetOps       ( equivClasses )
46 \end{code}
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection{Type checking}
51 %*                                                                      *
52 %************************************************************************
53
54 \begin{code}
55 tcTyDecl1 :: RecFlag -> RecTcEnv -> RenamedTyClDecl -> TcM (Name, TyThingDetails)
56 tcTyDecl1 is_rec unf_env (TySynonym tycon_name tyvar_names rhs src_loc)
57   = tcLookupTyCon tycon_name                    `thenNF_Tc` \ tycon ->
58     tcExtendTyVarEnv (tyConTyVars tycon)        $
59     tcHsRecType is_rec rhs                      `thenTc` \ rhs_ty ->
60         -- Note tcHsRecType not tcHsRecSigType; we allow type synonyms
61         -- that aren't types; e.g.  type List = []
62         --
63         -- If the RHS mentions tyvars that aren't in scope, we'll 
64         -- quantify over them:
65         --      e.g.    type T = a->a
66         -- will become  type T = forall a. a->a
67         --
68         -- With gla-exts that's right, but for H98 we should complain. 
69         -- We can now do that here without falling into
70         -- a black hole, we still do it in rnDecl (TySynonym case)
71
72     returnTc (tycon_name, SynTyDetails rhs_ty)
73
74 tcTyDecl1 is_rec unf_env (TyData new_or_data context tycon_name _ con_decls _ derivings src_loc name1 name2)
75   = tcLookupTyCon tycon_name                    `thenNF_Tc` \ tycon ->
76     let
77         tyvars = tyConTyVars tycon
78     in
79     tcExtendTyVarEnv tyvars                             $
80
81         -- Typecheck the pieces
82     tcRecClassContext is_rec context                                    `thenTc` \ ctxt ->
83     mapTc (tcConDecl is_rec new_or_data tycon tyvars ctxt) con_decls    `thenTc` \ data_cons ->
84     tcRecordSelectors is_rec unf_env tycon data_cons                    `thenTc` \ sel_ids -> 
85     returnTc (tycon_name, DataTyDetails ctxt data_cons sel_ids)
86 \end{code}
87
88 \begin{code}
89 mkNewTyConRep :: TyCon -> Type
90 -- Find the representation type for this newtype TyCon
91 -- The trick is to to deal correctly with recursive newtypes
92 -- such as      newtype T = MkT T
93
94 mkNewTyConRep tc
95   = mkForAllTys tvs (loop [] (mkTyConApp tc (mkTyVarTys tvs)))
96   where
97     tvs = tyConTyVars tc
98     loop tcs ty = case splitAlgTyConApp_maybe ty of {
99                         Nothing -> ty ;
100                         Just (tc, tys, data_cons) | not (isNewTyCon tc) -> ty
101                                                   | tc `elem` tcs       -> unitTy
102                                                   | otherwise           ->
103
104                   case splitFunTy (applyTys (dataConRepType (head data_cons)) tys) of
105                         (rep_ty, _) -> loop (tc:tcs) rep_ty
106                   }
107 \end{code}
108
109
110 %************************************************************************
111 %*                                                                      *
112 \subsection{Kind and type check constructors}
113 %*                                                                      *
114 %************************************************************************
115
116 \begin{code}
117 kcConDetails :: NewOrData -> RenamedContext -> ConDetails Name -> TcM ()
118 kcConDetails new_or_data ex_ctxt details
119   = kcHsContext ex_ctxt         `thenTc_`
120     mapTc_ kc_sig_type (conDetailsTys details)
121   where
122     kc_sig_type = case new_or_data of
123                     DataType -> kcHsSigType
124                     NewType  -> kcHsBoxedSigType
125             -- Can't allow an unboxed type here, because we're effectively
126             -- going to remove the constructor while coercing it to a boxed type.
127
128
129 tcConDecl :: RecFlag -> NewOrData -> TyCon -> [TyVar] -> ClassContext -> RenamedConDecl -> TcM DataCon
130
131 tcConDecl is_rec new_or_data tycon tyvars ctxt (ConDecl name wkr_name ex_tvs ex_ctxt details src_loc)
132   = tcAddSrcLoc src_loc                                                 $
133     tcHsTyVars ex_tvs (kcConDetails new_or_data ex_ctxt details)        $ \ ex_tyvars ->
134     tcRecClassContext is_rec ex_ctxt                                    `thenTc` \ ex_theta ->
135     case details of
136         VanillaCon btys    -> tc_datacon ex_tyvars ex_theta btys
137         InfixCon bty1 bty2 -> tc_datacon ex_tyvars ex_theta [bty1,bty2]
138         RecCon fields      -> tc_rec_con ex_tyvars ex_theta fields
139   where
140     tc_datacon ex_tyvars ex_theta btys
141       = let
142             arg_stricts = map getBangStrictness btys
143             tys         = map getBangType btys
144         in
145         mapTc (tcHsRecType is_rec) tys          `thenTc` \ arg_tys ->
146         mk_data_con ex_tyvars ex_theta arg_stricts arg_tys []
147
148     tc_rec_con ex_tyvars ex_theta fields
149       = checkTc (null ex_tyvars) (exRecConErr name)     `thenTc_`
150         mapTc tc_field (fields `zip` allFieldLabelTags) `thenTc` \ field_labels_s ->
151         let
152             field_labels = concat field_labels_s
153             arg_stricts = [str | (ns, bty) <- fields, 
154                                  let str = getBangStrictness bty, 
155                                  n <- ns                -- One for each.  E.g   x,y,z :: !Int
156                           ]
157         in
158         mk_data_con ex_tyvars ex_theta arg_stricts 
159                     (map fieldLabelType field_labels) field_labels
160
161     tc_field ((field_label_names, bty), tag)
162       = tcHsRecType is_rec (getBangType bty)            `thenTc` \ field_ty ->
163         returnTc [mkFieldLabel (getName name) tycon field_ty tag | name <- field_label_names]
164
165     mk_data_con ex_tyvars ex_theta arg_stricts arg_tys fields
166       = let
167            data_con = mkDataCon name arg_stricts fields
168                            tyvars (thinContext arg_tys ctxt)
169                            ex_tyvars ex_theta
170                            arg_tys
171                            tycon data_con_id data_con_wrap_id
172
173            data_con_id      = mkDataConId wkr_name data_con
174            data_con_wrap_id = mkDataConWrapId data_con
175         in
176         returnNF_Tc data_con
177
178 -- The context for a data constructor should be limited to
179 -- the type variables mentioned in the arg_tys
180 thinContext arg_tys ctxt
181   = filter in_arg_tys ctxt
182   where
183       arg_tyvars = tyVarsOfTypes arg_tys
184       in_arg_tys (clas,tys) = not $ isEmptyVarSet $ 
185                               tyVarsOfTypes tys `intersectVarSet` arg_tyvars
186
187 getBangStrictness (Banged   _) = markedStrict
188 getBangStrictness (Unbanged _) = notMarkedStrict
189 getBangStrictness (Unpacked _) = markedUnboxed
190 \end{code}
191
192
193 %************************************************************************
194 %*                                                                      *
195 \subsection{Record selectors}
196 %*                                                                      *
197 %************************************************************************
198
199 \begin{code}
200 tcRecordSelectors is_rec unf_env tycon data_cons
201   = mapTc tc_group groups
202   where
203     fields = [ (con, field) | con   <- data_cons,
204                               field <- dataConFieldLabels con ]
205
206         -- groups is list of fields that share a common name
207     groups = equivClasses cmp_name fields
208     cmp_name (_, field1) (_, field2) 
209         = fieldLabelName field1 `compare` fieldLabelName field2
210
211     tc_group fields@((first_con, first_field_label) : other_fields)
212         -- These fields all have the same name, but are from
213         -- different constructors in the data type
214         =       -- Check that all the fields in the group have the same type
215                 -- Wimp out (omit check) if the group is recursive; 
216                 -- TcTyClsDecls.tcGroup will repeat with NonRecursive once we
217                 -- have tied the knot
218                 -- NB: this check assumes that all the constructors of a given
219                 -- data type use the same type variables
220           checkTc (not (isRec is_rec) && all (== field_ty) other_tys)
221                   (fieldTypeMisMatch field_name)        `thenTc_`
222           returnTc (mkRecordSelId tycon first_field_label unpack_id unpackUtf8_id)
223         where
224             field_ty   = fieldLabelType first_field_label
225             field_name = fieldLabelName first_field_label
226             other_tys  = [fieldLabelType fl | (_, fl) <- other_fields]
227
228     unpack_id     = tcLookupRecId unf_env unpackCStringName
229     unpackUtf8_id = tcLookupRecId unf_env unpackCStringUtf8Name
230 \end{code}
231
232
233
234 %************************************************************************
235 %*                                                                      *
236 \subsection{Errors and contexts}
237 %*                                                                      *
238 %************************************************************************
239
240
241 \begin{code}
242 fieldTypeMisMatch field_name
243   = sep [ptext SLIT("Declared types differ for field"), quotes (ppr field_name)]
244
245 exRecConErr name
246   = ptext SLIT("Can't combine named fields with locally-quantified type variables")
247     $$
248     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
249 \end{code}