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