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