[project @ 2000-11-24 17:02:01 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 {tcdName = tycon_name, tcdSynRhs = rhs})
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 {tcdND = new_or_data, tcdCtxt = context,
75                                   tcdName = tycon_name, tcdCons = con_decls})
76   = tcLookupTyCon tycon_name                    `thenNF_Tc` \ tycon ->
77     let
78         tyvars = tyConTyVars tycon
79     in
80     tcExtendTyVarEnv tyvars                             $
81
82         -- Typecheck the pieces
83     tcRecClassContext is_rec context                                    `thenTc` \ ctxt ->
84     mapTc (tcConDecl is_rec new_or_data tycon tyvars ctxt) con_decls    `thenTc` \ data_cons ->
85     tcRecordSelectors is_rec unf_env tycon data_cons                    `thenTc` \ sel_ids -> 
86     returnTc (tycon_name, DataTyDetails ctxt data_cons sel_ids)
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  -> kcHsBoxedSigType
126             -- Can't allow an unboxed type here, because we're effectively
127             -- going to remove the constructor while coercing it to a boxed type.
128
129
130 tcConDecl :: RecFlag -> NewOrData -> TyCon -> [TyVar] -> ClassContext -> 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     tcRecClassContext 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 (clas,tys) = not $ isEmptyVarSet $ 
186                               tyVarsOfTypes tys `intersectVarSet` arg_tyvars
187
188 getBangStrictness (Banged   _) = markedStrict
189 getBangStrictness (Unbanged _) = notMarkedStrict
190 getBangStrictness (Unpacked _) = markedUnboxed
191 \end{code}
192
193
194 %************************************************************************
195 %*                                                                      *
196 \subsection{Record selectors}
197 %*                                                                      *
198 %************************************************************************
199
200 \begin{code}
201 tcRecordSelectors is_rec unf_env tycon data_cons
202         -- Omit the check that the fields have consistent types if 
203         -- the group is recursive; TcTyClsDecls.tcGroup will repeat 
204         -- with NonRecursive once we have tied the knot
205   | isRec is_rec = returnTc sel_ids
206   | otherwise    = mapTc check groups   `thenTc_` 
207                    returnTc sel_ids
208   where
209     fields = [ field | con   <- data_cons
210                      , field <- dataConFieldLabels con ]
211
212         -- groups is list of fields that share a common name
213     groups                 = equivClasses cmp_name fields
214     cmp_name field1 field2 = fieldLabelName field1 `compare` fieldLabelName field2
215
216     sel_ids = [ mkRecordSelId tycon field unpack_id unpackUtf8_id
217               | (field : _) <- groups ]
218
219     check fields@(first_field_label : other_fields)
220         -- These fields all have the same name, but are from
221         -- different constructors in the data type
222         =       -- Check that all the fields in the group have the same type
223                 -- NB: this check assumes that all the constructors of a given
224                 -- data type use the same type variables
225           checkTc (all (== field_ty) other_tys) (fieldTypeMisMatch field_name)
226         where
227             field_ty   = fieldLabelType first_field_label
228             field_name = fieldLabelName first_field_label
229             other_tys  = map fieldLabelType other_fields
230
231     unpack_id     = tcLookupRecId unf_env unpackCStringName
232     unpackUtf8_id = tcLookupRecId unf_env unpackCStringUtf8Name
233 \end{code}
234
235
236
237 %************************************************************************
238 %*                                                                      *
239 \subsection{Errors and contexts}
240 %*                                                                      *
241 %************************************************************************
242
243
244 \begin{code}
245 fieldTypeMisMatch field_name
246   = sep [ptext SLIT("Different constructors give different types for field"), quotes (ppr field_name)]
247
248 exRecConErr name
249   = ptext SLIT("Can't combine named fields with locally-quantified type variables")
250     $$
251     (ptext SLIT("In the declaration of data constructor") <+> ppr name)
252 \end{code}