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