some bug-fixes, newtype deriving might work now
[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         ; return (NewTyCon { data_con = con, 
87                              nt_co = Just co_tycon, 
88                              -- Coreview looks through newtypes with a Nothing
89                              -- for nt_co, or uses explicit coercions otherwise
90                              nt_rhs = rhs_ty,
91                              nt_etad_rhs = eta_reduce tvs rhs_ty,
92                              nt_rep = mkNewTyConRep tycon rhs_ty }) }
93   where
94     tvs    = tyConTyVars tycon
95     rhs_ty = head (dataConInstOrigArgTys con (mkTyVarTys tvs))
96         -- Instantiate the data con with the 
97         -- type variables from the tycon
98
99     eta_reduce [] ty = ([], ty)
100     eta_reduce (a:as) ty | null as', 
101                            Just (fun, arg) <- splitAppTy_maybe ty',
102                            Just tv <- getTyVar_maybe arg,
103                            tv == a,
104                            not (a `elemVarSet` tyVarsOfType fun)
105                          = ([], fun)    -- Successful eta reduction
106                          | otherwise
107                          = (a:as', ty')
108         where
109           (as', ty') = eta_reduce as ty
110                                 
111 mkNewTyConRep :: TyCon          -- The original type constructor
112               -> Type           -- The arg type of its constructor
113               -> Type           -- Chosen representation type
114 -- The "representation type" is guaranteed not to be another newtype
115 -- at the outermost level; but it might have newtypes in type arguments
116
117 -- Find the representation type for this newtype TyCon
118 -- Remember that the representation type is the *ultimate* representation
119 -- type, looking through other newtypes.
120 -- 
121 -- splitTyConApp_maybe no longer looks through newtypes, so we must
122 -- deal explicitly with this case
123 -- 
124 -- The trick is to to deal correctly with recursive newtypes
125 -- such as      newtype T = MkT T
126
127 mkNewTyConRep tc rhs_ty
128   | null (tyConDataCons tc) = unitTy
129         -- External Core programs can have newtypes with no data constructors
130   | otherwise               = go [tc] rhs_ty
131   where
132         -- Invariant: tcs have been seen before
133     go tcs rep_ty 
134         = case splitTyConApp_maybe rep_ty of
135             Just (tc, tys)
136                 | tc `elem` tcs -> unitTy       -- Recursive loop
137                 | isNewTyCon tc -> 
138                     if isRecursiveTyCon tc then
139                         go (tc:tcs) (substTyWith tvs tys rhs_ty)
140                     else
141                         substTyWith tvs tys rhs_ty
142                 where
143                   (tvs, rhs_ty) = newTyConRhs tc
144
145             other -> rep_ty 
146
147 ------------------------------------------------------
148 buildDataCon :: Name -> Bool
149             -> [StrictnessMark] 
150             -> [Name]                   -- Field labels
151             -> [TyVar] -> [TyVar]       -- Univ and ext 
152             -> [(TyVar,Type)]           -- Equality spec
153             -> ThetaType                -- Does not include the "stupid theta"
154                                         -- or the GADT equalities
155             -> [Type] -> TyCon
156             -> TcRnIf m n DataCon
157 -- A wrapper for DataCon.mkDataCon that
158 --   a) makes the worker Id
159 --   b) makes the wrapper Id if necessary, including
160 --      allocating its unique (hence monadic)
161 buildDataCon src_name declared_infix arg_stricts field_lbls
162              univ_tvs ex_tvs eq_spec ctxt arg_tys tycon
163   = do  { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
164         ; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
165         -- This last one takes the name of the data constructor in the source
166         -- code, which (for Haskell source anyway) will be in the DataName name
167         -- space, and puts it into the VarName name space
168
169         ; let
170                 stupid_ctxt = mkDataConStupidTheta tycon arg_tys univ_tvs
171                 data_con = mkDataCon src_name declared_infix
172                                      arg_stricts field_lbls
173                                      univ_tvs ex_tvs eq_spec ctxt
174                                      arg_tys tycon stupid_ctxt dc_ids
175                 dc_ids = mkDataConIds wrap_name work_name data_con
176
177         ; returnM data_con }
178
179
180 -- The stupid context for a data constructor should be limited to
181 -- the type variables mentioned in the arg_tys
182 -- ToDo: Or functionally dependent on?  
183 --       This whole stupid theta thing is, well, stupid.
184 mkDataConStupidTheta tycon arg_tys univ_tvs
185   | null stupid_theta = []      -- The common case
186   | otherwise         = filter in_arg_tys stupid_theta
187   where
188     tc_subst     = zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs)
189     stupid_theta = substTheta tc_subst (tyConStupidTheta tycon)
190         -- Start by instantiating the master copy of the 
191         -- stupid theta, taken from the TyCon
192
193     arg_tyvars      = tyVarsOfTypes arg_tys
194     in_arg_tys pred = not $ isEmptyVarSet $ 
195                       tyVarsOfPred pred `intersectVarSet` arg_tyvars
196
197 ------------------------------------------------------
198 mkTyConSelIds :: TyCon -> AlgTyConRhs -> [Id]
199 mkTyConSelIds tycon rhs
200   =  [ mkRecordSelId tycon fld 
201      | fld <- nub (concatMap dataConFieldLabels (visibleDataCons rhs)) ]
202         -- We'll check later that fields with the same name 
203         -- from different constructors have the same type.
204 \end{code}
205
206
207 ------------------------------------------------------
208 \begin{code}
209 buildClass :: Name -> [TyVar] -> ThetaType
210            -> [FunDep TyVar]            -- Functional dependencies
211            -> [(Name, DefMeth, Type)]   -- Method info
212            -> RecFlag                   -- Info for type constructor
213            -> TcRnIf m n Class
214
215 buildClass class_name tvs sc_theta fds sig_stuff tc_isrec
216   = do  { tycon_name <- newImplicitBinder class_name mkClassTyConOcc
217         ; datacon_name <- newImplicitBinder class_name mkClassDataConOcc
218                 -- The class name is the 'parent' for this datacon, not its tycon,
219                 -- because one should import the class to get the binding for 
220                 -- the datacon
221         ; sc_sel_names <- mapM (newImplicitBinder class_name . mkSuperDictSelOcc) 
222                                 [1..length sc_theta]
223               -- We number off the superclass selectors, 1, 2, 3 etc so that we 
224               -- can construct names for the selectors.  Thus
225               --      class (C a, C b) => D a b where ...
226               -- gives superclass selectors
227               --      D_sc1, D_sc2
228               -- (We used to call them D_C, but now we can have two different
229               --  superclasses both called C!)
230
231         ; fixM (\ rec_clas -> do {      -- Only name generation inside loop
232
233           let { rec_tycon          = classTyCon rec_clas
234               ; op_tys             = [ty | (_,_,ty) <- sig_stuff]
235               ; sc_tys             = mkPredTys sc_theta
236               ; dict_component_tys = sc_tys ++ op_tys
237               ; sc_sel_ids         = [mkDictSelId sc_name rec_clas | sc_name <- sc_sel_names]
238               ; op_items = [ (mkDictSelId op_name rec_clas, dm_info)
239                            | (op_name, dm_info, _) <- sig_stuff ] }
240                         -- Build the selector id and default method id
241
242         ; dict_con <- buildDataCon datacon_name
243                                    False        -- Not declared infix
244                                    (map (const NotMarkedStrict) dict_component_tys)
245                                    [{- No labelled fields -}]
246                                    tvs [{- no existentials -}]
247                                    [{- No equalities -}] [{-No context-}] 
248                                    dict_component_tys 
249                                    rec_tycon
250
251         ; rhs <- case dict_component_tys of
252                             [rep_ty] -> mkNewTyConRhs tycon_name rec_tycon dict_con
253                             other    -> return (mkDataTyConRhs [dict_con])
254
255         ; let { clas_kind = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
256
257               ; tycon = mkClassTyCon tycon_name clas_kind tvs
258                              rhs rec_clas tc_isrec
259                 -- A class can be recursive, and in the case of newtypes 
260                 -- this matters.  For example
261                 --      class C a where { op :: C b => a -> b -> Int }
262                 -- Because C has only one operation, it is represented by
263                 -- a newtype, and it should be a *recursive* newtype.
264                 -- [If we don't make it a recursive newtype, we'll expand the
265                 -- newtype like a synonym, but that will lead to an infinite type]
266               }
267         ; return (mkClass class_name tvs fds
268                        sc_theta sc_sel_ids op_items
269                        tycon)
270         })}
271 \end{code}
272
273