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