bf71ca843ce8fa5158f27b326197aa2aa42341cb
[ghc-hetmet.git] / compiler / iface / BuildTyCl.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4
5 \begin{code}
6 module BuildTyCl (
7         buildSynTyCon, buildAlgTyCon, buildDataCon,
8         buildClass,
9         mkAbstractTyConRhs, mkOpenDataTyConRhs, mkOpenNewTyConRhs,
10         mkNewTyConRhs, mkDataTyConRhs 
11     ) where
12
13 #include "HsVersions.h"
14
15 import IfaceEnv         ( newImplicitBinder )
16 import TcRnMonad
17
18 import DataCon          ( DataCon, isNullarySrcDataCon, dataConUnivTyVars,
19                           mkDataCon, dataConFieldLabels, dataConInstOrigArgTys,
20                           dataConTyCon )
21 import Var              ( tyVarKind, TyVar, Id )
22 import VarSet           ( isEmptyVarSet, intersectVarSet, elemVarSet )
23 import TysWiredIn       ( unitTy )
24 import BasicTypes       ( RecFlag, StrictnessMark(..) )
25 import Name             ( Name )
26 import OccName          ( mkDataConWrapperOcc, mkDataConWorkerOcc, mkClassTyConOcc,
27                           mkClassDataConOcc, mkSuperDictSelOcc, mkNewTyCoOcc )
28 import MkId             ( mkDataConIds, mkRecordSelId, mkDictSelId )
29 import Class            ( mkClass, Class( classTyCon), FunDep, DefMeth(..) )
30 import TyCon            ( mkSynTyCon, mkAlgTyCon, visibleDataCons,
31                           tyConStupidTheta, tyConDataCons, isNewTyCon,
32                           mkClassTyCon, TyCon( tyConTyVars ),
33                           isRecursiveTyCon, tyConArity, AlgTyConRhs(..),
34                           SynTyConRhs(..), newTyConRhs )
35 import Type             ( mkArrowKinds, liftedTypeKind, typeKind, 
36                           tyVarsOfType, tyVarsOfTypes, tyVarsOfPred,
37                           splitTyConApp_maybe, splitAppTy_maybe,
38                           getTyVar_maybe, 
39                           mkPredTys, mkTyVarTys, ThetaType, Type, Kind,
40                           TyThing(..), 
41                           substTyWith, zipTopTvSubst, substTheta, mkForAllTys,
42                           mkTyConApp, mkTyVarTy )
43 import Coercion         ( mkNewTypeCoercion )
44 import Outputable
45 import List             ( nub )
46
47 \end{code}
48         
49
50 \begin{code}
51 ------------------------------------------------------
52 buildSynTyCon :: Name -> [TyVar] -> SynTyConRhs -> TyCon
53 buildSynTyCon name tvs rhs@(OpenSynTyCon rhs_ki)
54   = mkSynTyCon name kind tvs rhs
55   where
56     kind = mkArrowKinds (map tyVarKind tvs) rhs_ki
57 buildSynTyCon name tvs rhs@(SynonymTyCon rhs_ty)
58   = mkSynTyCon name kind tvs rhs
59   where
60     kind = mkArrowKinds (map tyVarKind tvs) (typeKind rhs_ty)
61
62
63 ------------------------------------------------------
64 buildAlgTyCon :: Name -> [TyVar] 
65               -> ThetaType              -- Stupid theta
66               -> AlgTyConRhs
67               -> RecFlag
68               -> Bool                   -- True <=> want generics functions
69               -> Bool                   -- True <=> was declared in GADT syntax
70               -> TcRnIf m n TyCon
71
72 buildAlgTyCon tc_name tvs stupid_theta rhs is_rec want_generics gadt_syn
73   = do  { let { tycon = mkAlgTyCon tc_name kind tvs stupid_theta
74                                    rhs fields is_rec want_generics gadt_syn
75               ; kind    = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
76               ; fields  = mkTyConSelIds tycon rhs
77           }
78         ; return tycon }
79
80 ------------------------------------------------------
81 mkAbstractTyConRhs :: AlgTyConRhs
82 mkAbstractTyConRhs = AbstractTyCon
83
84 mkOpenDataTyConRhs :: AlgTyConRhs
85 mkOpenDataTyConRhs = OpenDataTyCon
86
87 mkOpenNewTyConRhs :: AlgTyConRhs
88 mkOpenNewTyConRhs = OpenNewTyCon
89
90 mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
91 mkDataTyConRhs cons
92   = DataTyCon { data_cons = cons, is_enum = all isNullarySrcDataCon cons }
93
94 mkNewTyConRhs :: Name -> TyCon -> DataCon -> TcRnIf m n AlgTyConRhs
95 -- Monadic because it makes a Name for the coercion TyCon
96 -- We pass the Name of the parent TyCon, as well as the TyCon itself,
97 -- because the latter is part of a knot, whereas the former is not.
98 mkNewTyConRhs tycon_name tycon con 
99   = do  { co_tycon_name <- newImplicitBinder tycon_name mkNewTyCoOcc
100         ; let co_tycon = mkNewTypeCoercion co_tycon_name tycon tvs rhs_ty
101               cocon_maybe 
102                 | all_coercions || isRecursiveTyCon tycon 
103                 = Just co_tycon
104                 | otherwise              
105                 = Nothing
106         ; return (NewTyCon { data_con = con, 
107                              nt_co = cocon_maybe, 
108                              -- Coreview looks through newtypes with a Nothing
109                              -- for nt_co, or uses explicit coercions otherwise
110                              nt_rhs = rhs_ty,
111                              nt_etad_rhs = eta_reduce tvs rhs_ty,
112                              nt_rep = mkNewTyConRep tycon rhs_ty }) }
113   where
114         -- if all_coercions is True then we use coercions for all newtypes
115         -- otherwise we use coercions for recursive newtypes and look through
116         -- non-recursive newtypes
117     all_coercions = True
118     tvs    = tyConTyVars tycon
119     rhs_ty = head (dataConInstOrigArgTys con (mkTyVarTys tvs))
120         -- Instantiate the data con with the 
121         -- type variables from the tycon
122
123     eta_reduce [] ty = ([], ty)
124     eta_reduce (a:as) ty | null as', 
125                            Just (fun, arg) <- splitAppTy_maybe ty',
126                            Just tv <- getTyVar_maybe arg,
127                            tv == a,
128                            not (a `elemVarSet` tyVarsOfType fun)
129                          = ([], fun)    -- Successful eta reduction
130                          | otherwise
131                          = (a:as', ty')
132         where
133           (as', ty') = eta_reduce as ty
134                                 
135 mkNewTyConRep :: TyCon          -- The original type constructor
136               -> Type           -- The arg type of its constructor
137               -> Type           -- Chosen representation type
138 -- The "representation type" is guaranteed not to be another newtype
139 -- at the outermost level; but it might have newtypes in type arguments
140
141 -- Find the representation type for this newtype TyCon
142 -- Remember that the representation type is the *ultimate* representation
143 -- type, looking through other newtypes.
144 -- 
145 -- splitTyConApp_maybe no longer looks through newtypes, so we must
146 -- deal explicitly with this case
147 -- 
148 -- The trick is to to deal correctly with recursive newtypes
149 -- such as      newtype T = MkT T
150
151 mkNewTyConRep tc rhs_ty
152   | null (tyConDataCons tc) = unitTy
153         -- External Core programs can have newtypes with no data constructors
154   | otherwise               = go [tc] rhs_ty
155   where
156         -- Invariant: tcs have been seen before
157     go tcs rep_ty 
158         = case splitTyConApp_maybe rep_ty of
159             Just (tc, tys)
160                 | tc `elem` tcs -> unitTy       -- Recursive loop
161                 | isNewTyCon tc -> 
162                     if isRecursiveTyCon tc then
163                         go (tc:tcs) (substTyWith tvs tys rhs_ty)
164                     else
165                         substTyWith tvs tys rhs_ty
166                 where
167                   (tvs, rhs_ty) = newTyConRhs tc
168
169             other -> rep_ty 
170
171 ------------------------------------------------------
172 buildDataCon :: Name -> Bool
173             -> [StrictnessMark] 
174             -> [Name]                   -- Field labels
175             -> [TyVar] -> [TyVar]       -- Univ and ext 
176             -> [(TyVar,Type)]           -- Equality spec
177             -> ThetaType                -- Does not include the "stupid theta"
178                                         -- or the GADT equalities
179             -> [Type] -> TyCon
180             -> TcRnIf m n DataCon
181 -- A wrapper for DataCon.mkDataCon that
182 --   a) makes the worker Id
183 --   b) makes the wrapper Id if necessary, including
184 --      allocating its unique (hence monadic)
185 buildDataCon src_name declared_infix arg_stricts field_lbls
186              univ_tvs ex_tvs eq_spec ctxt arg_tys tycon
187   = do  { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
188         ; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
189         -- This last one takes the name of the data constructor in the source
190         -- code, which (for Haskell source anyway) will be in the DataName name
191         -- space, and puts it into the VarName name space
192
193         ; let
194                 stupid_ctxt = mkDataConStupidTheta tycon arg_tys univ_tvs
195                 data_con = mkDataCon src_name declared_infix
196                                      arg_stricts field_lbls
197                                      univ_tvs ex_tvs eq_spec ctxt
198                                      arg_tys tycon stupid_ctxt dc_ids
199                 dc_ids = mkDataConIds wrap_name work_name data_con
200
201         ; returnM data_con }
202
203
204 -- The stupid context for a data constructor should be limited to
205 -- the type variables mentioned in the arg_tys
206 -- ToDo: Or functionally dependent on?  
207 --       This whole stupid theta thing is, well, stupid.
208 mkDataConStupidTheta tycon arg_tys univ_tvs
209   | null stupid_theta = []      -- The common case
210   | otherwise         = filter in_arg_tys stupid_theta
211   where
212     tc_subst     = zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs)
213     stupid_theta = substTheta tc_subst (tyConStupidTheta tycon)
214         -- Start by instantiating the master copy of the 
215         -- stupid theta, taken from the TyCon
216
217     arg_tyvars      = tyVarsOfTypes arg_tys
218     in_arg_tys pred = not $ isEmptyVarSet $ 
219                       tyVarsOfPred pred `intersectVarSet` arg_tyvars
220
221 ------------------------------------------------------
222 mkTyConSelIds :: TyCon -> AlgTyConRhs -> [Id]
223 mkTyConSelIds tycon rhs
224   =  [ mkRecordSelId tycon fld 
225      | fld <- nub (concatMap dataConFieldLabels (visibleDataCons rhs)) ]
226         -- We'll check later that fields with the same name 
227         -- from different constructors have the same type.
228 \end{code}
229
230
231 ------------------------------------------------------
232 \begin{code}
233 buildClass :: Name -> [TyVar] -> ThetaType
234            -> [FunDep TyVar]            -- Functional dependencies
235            -> [TyThing]                 -- Associated types
236            -> [(Name, DefMeth, Type)]   -- Method info
237            -> RecFlag                   -- Info for type constructor
238            -> TcRnIf m n Class
239
240 buildClass class_name tvs sc_theta fds ats sig_stuff tc_isrec
241   = do  { tycon_name <- newImplicitBinder class_name mkClassTyConOcc
242         ; datacon_name <- newImplicitBinder class_name mkClassDataConOcc
243                 -- The class name is the 'parent' for this datacon, not its tycon,
244                 -- because one should import the class to get the binding for 
245                 -- the datacon
246         ; sc_sel_names <- mapM (newImplicitBinder class_name . mkSuperDictSelOcc) 
247                                 [1..length sc_theta]
248               -- We number off the superclass selectors, 1, 2, 3 etc so that we 
249               -- can construct names for the selectors.  Thus
250               --      class (C a, C b) => D a b where ...
251               -- gives superclass selectors
252               --      D_sc1, D_sc2
253               -- (We used to call them D_C, but now we can have two different
254               --  superclasses both called C!)
255
256         ; fixM (\ rec_clas -> do {      -- Only name generation inside loop
257
258           let { rec_tycon          = classTyCon rec_clas
259               ; op_tys             = [ty | (_,_,ty) <- sig_stuff]
260               ; sc_tys             = mkPredTys sc_theta
261               ; dict_component_tys = sc_tys ++ op_tys
262               ; sc_sel_ids         = [mkDictSelId sc_name rec_clas | sc_name <- sc_sel_names]
263               ; op_items = [ (mkDictSelId op_name rec_clas, dm_info)
264                            | (op_name, dm_info, _) <- sig_stuff ] }
265                         -- Build the selector id and default method id
266
267         ; dict_con <- buildDataCon datacon_name
268                                    False        -- Not declared infix
269                                    (map (const NotMarkedStrict) dict_component_tys)
270                                    [{- No labelled fields -}]
271                                    tvs [{- no existentials -}]
272                                    [{- No equalities -}] [{-No context-}] 
273                                    dict_component_tys 
274                                    rec_tycon
275
276         ; rhs <- case dict_component_tys of
277                             [rep_ty] -> mkNewTyConRhs tycon_name rec_tycon dict_con
278                             other    -> return (mkDataTyConRhs [dict_con])
279
280         ; let { clas_kind = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
281
282               ; tycon = mkClassTyCon tycon_name clas_kind tvs
283                              rhs rec_clas tc_isrec
284                 -- A class can be recursive, and in the case of newtypes 
285                 -- this matters.  For example
286                 --      class C a where { op :: C b => a -> b -> Int }
287                 -- Because C has only one operation, it is represented by
288                 -- a newtype, and it should be a *recursive* newtype.
289                 -- [If we don't make it a recursive newtype, we'll expand the
290                 -- newtype like a synonym, but that will lead to an infinite
291                 -- type]
292               ; atTyCons = [tycon | ATyCon tycon <- ats]
293               }
294         ; return (mkClass class_name tvs fds 
295                        sc_theta sc_sel_ids atTyCons op_items
296                        tycon)
297         })}
298 \end{code}
299
300