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