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