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