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