[project @ 2001-08-14 06:35:56 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 ( tcTyDecl, checkValidTyCon, kcConDetails ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( TyClDecl(..), ConDecl(..), ConDetails(..), 
12                           getBangType, getBangStrictness, conDetailsTys
13                         )
14 import RnHsSyn          ( RenamedTyClDecl, RenamedConDecl, RenamedContext )
15 import BasicTypes       ( NewOrData(..) )
16
17 import TcMonoType       ( tcHsTyVars, tcHsTheta, tcHsType, 
18                           kcHsContext, kcHsSigType, kcHsLiftedSigType
19                         )
20 import TcEnv            ( tcExtendTyVarEnv, 
21                           tcLookupTyCon, tcLookupRecId, 
22                           TyThingDetails(..), RecTcEnv
23                         )
24 import TcType           ( tcEqType, tyVarsOfTypes, tyVarsOfPred, ThetaType )
25 import TcMType          ( checkValidType, UserTypeCtxt(..), checkValidTheta, SourceTyCtxt(..) )
26 import TcMonad
27
28 import DataCon          ( DataCon, mkDataCon, dataConFieldLabels, dataConWrapId, dataConName )
29 import MkId             ( mkDataConId, mkDataConWrapId, mkRecordSelId )
30 import FieldLabel
31 import Var              ( TyVar, idType )
32 import Name             ( Name, NamedThing(..) )
33 import Outputable
34 import TyCon            ( TyCon, tyConName, tyConTheta, getSynTyConDefn, tyConTyVars, tyConDataCons, isSynTyCon )
35 import VarSet           ( intersectVarSet, isEmptyVarSet )
36 import PrelNames        ( unpackCStringName, unpackCStringUtf8Name )
37 import ListSetOps       ( equivClasses )
38 import List             ( nubBy )
39 \end{code}
40
41 %************************************************************************
42 %*                                                                      *
43 \subsection{Type checking}
44 %*                                                                      *
45 %************************************************************************
46
47 \begin{code}
48 tcTyDecl :: RecTcEnv -> RenamedTyClDecl -> TcM (Name, TyThingDetails)
49 tcTyDecl unf_env (TySynonym {tcdName = tycon_name, tcdSynRhs = rhs})
50   = tcLookupTyCon tycon_name                    `thenNF_Tc` \ tycon ->
51     tcExtendTyVarEnv (tyConTyVars tycon)        $
52     tcHsType rhs                                `thenTc` \ rhs_ty ->
53     returnTc (tycon_name, SynTyDetails rhs_ty)
54
55 tcTyDecl unf_env (TyData {tcdND = new_or_data, tcdCtxt = context,
56                                   tcdName = tycon_name, tcdCons = con_decls})
57   = tcLookupTyCon tycon_name                    `thenNF_Tc` \ tycon ->
58     let
59         tyvars = tyConTyVars tycon
60     in
61     tcExtendTyVarEnv tyvars                             $
62     tcHsTheta context                                           `thenTc` \ ctxt ->
63     mapTc (tcConDecl new_or_data tycon tyvars ctxt) con_decls   `thenTc` \ data_cons ->
64     let
65         sel_ids = mkRecordSelectors unf_env tycon data_cons
66     in
67     returnTc (tycon_name, DataTyDetails ctxt data_cons sel_ids)
68
69 tcTyDecl unf_env (ForeignType {tcdName = tycon_name})
70   = returnTc (tycon_name, ForeignTyDetails)
71
72
73 mkRecordSelectors unf_env tycon data_cons
74   =     -- We'll check later that fields with the same name 
75         -- from different constructors have the same type.
76      [ mkRecordSelId tycon field unpack_id unpackUtf8_id
77      | field <- nubBy eq_name fields ]
78   where
79     fields = [ field | con <- data_cons, field <- dataConFieldLabels con ]
80     eq_name field1 field2 = fieldLabelName field1 == fieldLabelName field2
81
82     unpack_id     = tcLookupRecId unf_env unpackCStringName
83     unpackUtf8_id = tcLookupRecId unf_env unpackCStringUtf8Name
84 \end{code}
85
86
87 %************************************************************************
88 %*                                                                      *
89 \subsection{Validity check}
90 %*                                                                      *
91 %************************************************************************
92
93 checkValidTyCon is called once the mutually-recursive knot has been
94 tied, so we can look at things freely.
95
96 \begin{code}
97 checkValidTyCon :: TyCon -> TcM ()
98 checkValidTyCon tc
99   | isSynTyCon tc = checkValidType (TySynCtxt name) syn_rhs
100   | otherwise
101   =     -- Check the context on the data decl
102     checkValidTheta (DataTyCtxt name) (tyConTheta tc)   `thenTc_` 
103         
104         -- Check arg types of data constructors
105     mapTc_ check_data_con data_cons                     `thenTc_`
106
107         -- Check that fields with the same name share a type
108     mapTc_ check_fields groups
109
110   where
111     name         = tyConName tc
112     (_, syn_rhs) = getSynTyConDefn tc
113     data_cons    = tyConDataCons tc
114
115     fields = [field | con <- data_cons, field <- dataConFieldLabels con]
116     groups = equivClasses cmp_name fields
117     cmp_name field1 field2 = fieldLabelName field1 `compare` fieldLabelName field2
118
119     check_data_con con = checkValidType (ConArgCtxt (dataConName con)) 
120                                         (idType (dataConWrapId con))
121                                 -- This checks the argument types and
122                                 -- the existential context (if any)                      
123
124     check_fields fields@(first_field_label : other_fields)
125         -- These fields all have the same name, but are from
126         -- different constructors in the data type
127         =       -- Check that all the fields in the group have the same type
128                 -- NB: this check assumes that all the constructors of a given
129                 -- data type use the same type variables
130           checkTc (all (tcEqType field_ty) other_tys) (fieldTypeMisMatch field_name)
131         where
132             field_ty   = fieldLabelType first_field_label
133             field_name = fieldLabelName first_field_label
134             other_tys  = map fieldLabelType other_fields
135 \end{code}
136
137
138
139 %************************************************************************
140 %*                                                                      *
141 \subsection{Kind and type check constructors}
142 %*                                                                      *
143 %************************************************************************
144
145 \begin{code}
146 kcConDetails :: NewOrData -> RenamedContext -> ConDetails Name -> TcM ()
147 kcConDetails new_or_data ex_ctxt details
148   = kcHsContext ex_ctxt         `thenTc_`
149     mapTc_ kc_sig_type (conDetailsTys details)
150   where
151     kc_sig_type = case new_or_data of
152                     DataType -> kcHsSigType
153                     NewType  -> kcHsLiftedSigType
154             -- Can't allow an unlifted type here, because we're effectively
155             -- going to remove the constructor while coercing it to a lifted type.
156
157
158 tcConDecl :: NewOrData -> TyCon -> [TyVar] -> ThetaType -> RenamedConDecl -> TcM DataCon
159 tcConDecl new_or_data tycon tyvars ctxt (ConDecl name wkr_name ex_tvs ex_ctxt details src_loc)
160   = tcAddSrcLoc src_loc                                                 $
161     tcHsTyVars ex_tvs (kcConDetails new_or_data ex_ctxt details)        $ \ ex_tyvars ->
162     tcHsTheta ex_ctxt                                                   `thenTc` \ ex_theta ->
163     case details of
164         VanillaCon btys    -> tc_datacon ex_tyvars ex_theta btys
165         InfixCon bty1 bty2 -> tc_datacon ex_tyvars ex_theta [bty1,bty2]
166         RecCon fields      -> tc_rec_con ex_tyvars ex_theta fields
167   where
168     tc_datacon ex_tyvars ex_theta btys
169       = mapTc tcHsType (map getBangType btys)   `thenTc` \ arg_tys ->
170         mk_data_con ex_tyvars ex_theta (map getBangStrictness btys) arg_tys []
171
172     tc_rec_con ex_tyvars ex_theta fields
173       = checkTc (null ex_tyvars) (exRecConErr name)     `thenTc_`
174         mapTc tc_field (fields `zip` allFieldLabelTags) `thenTc` \ field_labels_s ->
175         let
176             field_labels = concat field_labels_s
177             arg_stricts = [str | (ns, bty) <- fields, 
178                                  let str = getBangStrictness bty, 
179                                  n <- ns        -- One for each.  E.g   x,y,z :: !Int
180                           ]
181         in
182         mk_data_con ex_tyvars ex_theta arg_stricts 
183                     (map fieldLabelType field_labels) field_labels
184
185     tc_field ((field_label_names, bty), tag)
186       = tcHsType (getBangType bty)                      `thenTc` \ field_ty ->
187         returnTc [mkFieldLabel (getName name) tycon field_ty tag | name <- field_label_names]
188
189     mk_data_con ex_tyvars ex_theta arg_stricts arg_tys fields
190       = let
191            data_con = mkDataCon name arg_stricts fields
192                            tyvars (thinContext arg_tys ctxt)
193                            ex_tyvars ex_theta
194                            arg_tys
195                            tycon data_con_id data_con_wrap_id
196
197            data_con_id      = mkDataConId wkr_name data_con
198            data_con_wrap_id = mkDataConWrapId data_con
199         in
200         returnNF_Tc data_con
201
202 -- The context for a data constructor should be limited to
203 -- the type variables mentioned in the arg_tys
204 thinContext arg_tys ctxt
205   = filter in_arg_tys ctxt
206   where
207       arg_tyvars = tyVarsOfTypes arg_tys
208       in_arg_tys pred = not $ isEmptyVarSet $ 
209                         tyVarsOfPred pred `intersectVarSet` arg_tyvars
210 \end{code}
211
212
213 %************************************************************************
214 %*                                                                      *
215 \subsection{Errors and contexts}
216 %*                                                                      *
217 %************************************************************************
218
219
220 \begin{code}
221 fieldTypeMisMatch field_name
222   = sep [ptext SLIT("Different constructors give different types for field"), quotes (ppr field_name)]
223
224 exRecConErr name
225   = ptext SLIT("Can't combine named fields with locally-quantified type variables")
226     $$
227     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
228 \end{code}