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