[project @ 2005-07-25 11:42:24 by simonpj]
[ghc-hetmet.git] / ghc / 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 Util             ( zipLazy )
18 import DataCon          ( DataCon, isNullarySrcDataCon,
19                           mkDataCon, dataConFieldLabels, dataConOrigArgTys )
20 import Var              ( tyVarKind, TyVar, Id )
21 import VarSet           ( isEmptyVarSet, intersectVarSet )
22 import TysWiredIn       ( unitTy )
23 import BasicTypes       ( RecFlag, StrictnessMark(..) )
24 import Name             ( Name )
25 import OccName          ( mkDataConWrapperOcc, mkDataConWorkerOcc, mkClassTyConOcc,
26                           mkClassDataConOcc, mkSuperDictSelOcc )
27 import MkId             ( mkDataConIds, mkRecordSelId, mkDictSelId )
28 import Class            ( mkClass, Class( classTyCon), FunDep, DefMeth(..) )
29 import TyCon            ( FieldLabel, mkSynTyCon, mkAlgTyCon, visibleDataCons, tyConStupidTheta,
30                           tyConDataCons, isNewTyCon, mkClassTyCon, TyCon( tyConTyVars ),
31                           ArgVrcs, AlgTyConRhs(..), newTyConRhs )
32 import Type             ( mkArrowKinds, liftedTypeKind, typeKind, tyVarsOfTypes, tyVarsOfPred,
33                           splitTyConApp_maybe, mkPredTys, mkTyVarTys, ThetaType, Type,
34                           substTyWith, zipTopTvSubst, substTheta )
35 import Outputable
36 import List             ( nubBy )
37
38 \end{code}
39         
40
41 \begin{code}
42 ------------------------------------------------------
43 buildSynTyCon name tvs rhs_ty arg_vrcs
44   = mkSynTyCon name kind tvs rhs_ty arg_vrcs
45   where
46     kind = mkArrowKinds (map tyVarKind tvs) (typeKind rhs_ty)
47
48
49 ------------------------------------------------------
50 buildAlgTyCon :: Name -> [TyVar] 
51               -> ThetaType              -- Stupid theta
52               -> AlgTyConRhs
53               -> ArgVrcs -> RecFlag
54               -> Bool                   -- True <=> want generics functions
55               -> TcRnIf m n TyCon
56
57 buildAlgTyCon tc_name tvs stupid_theta rhs arg_vrcs is_rec want_generics
58   = do  { let { tycon = mkAlgTyCon tc_name kind tvs arg_vrcs stupid_theta
59                                    rhs fields is_rec want_generics
60               ; kind    = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
61               ; fields  = mkTyConFields tycon rhs
62           }
63         ; return tycon }
64
65 ------------------------------------------------------
66 mkAbstractTyConRhs :: AlgTyConRhs
67 mkAbstractTyConRhs = AbstractTyCon
68
69 mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
70 mkDataTyConRhs cons
71   = DataTyCon cons (all isNullarySrcDataCon cons)
72
73 mkNewTyConRhs :: TyCon -> DataCon -> AlgTyConRhs
74 mkNewTyConRhs tycon con 
75   = NewTyCon con rhs_ty (mkNewTyConRep tycon)
76   where
77     rhs_ty = head (dataConOrigArgTys con)
78         -- Newtypes are guaranteed vanilla, so OrigArgTys will do
79                                 
80 mkNewTyConRep :: TyCon          -- The original type constructor
81               -> Type           -- Chosen representation type
82                                 -- (guaranteed not to be another newtype)
83                                 -- Free vars of rep = tyConTyVars tc
84
85 -- Find the representation type for this newtype TyCon
86 -- Remember that the representation type is the *ultimate* representation
87 -- type, looking through other newtypes.
88 -- 
89 -- The non-recursive newtypes are easy, because they look transparent
90 -- to splitTyConApp_maybe, but recursive ones really are represented as
91 -- TyConApps (see TypeRep).
92 -- 
93 -- The trick is to to deal correctly with recursive newtypes
94 -- such as      newtype T = MkT T
95
96 mkNewTyConRep tc
97   | null (tyConDataCons tc) = unitTy
98         -- External Core programs can have newtypes with no data constructors
99   | otherwise               = go [] tc
100   where
101         -- Invariant: tc is a NewTyCon
102         --            tcs have been seen before
103     go tcs tc 
104         | tc `elem` tcs = unitTy
105         | otherwise
106         = case splitTyConApp_maybe rhs_ty of
107             Just (tc1, tys) | isNewTyCon tc1
108                            -> ASSERT( length (tyConTyVars tc1) == length tys )
109                               substTyWith (tyConTyVars tc1) tys (go (tc:tcs) tc1)
110             other          -> rhs_ty 
111         where
112           (_tc_tvs, rhs_ty) = newTyConRhs tc
113
114
115 ------------------------------------------------------
116 buildDataCon :: Name -> Bool -> Bool
117             -> [StrictnessMark] 
118             -> [Name]                   -- Field labels
119             -> [TyVar] -> ThetaType
120             -> [Type] -> TyCon -> [Type]
121             -> TcRnIf m n DataCon
122 -- A wrapper for DataCon.mkDataCon that
123 --   a) makes the worker Id
124 --   b) makes the wrapper Id if necessary, including
125 --      allocating its unique (hence monadic)
126 buildDataCon src_name declared_infix vanilla arg_stricts field_lbls
127              tyvars ctxt arg_tys tycon res_tys
128   = do  { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
129         ; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
130         -- This last one takes the name of the data constructor in the source
131         -- code, which (for Haskell source anyway) will be in the DataName name
132         -- space, and puts it into the VarName name space
133
134         ; let
135                 stupid_ctxt = mkDataConStupidTheta tycon arg_tys res_tys
136                 data_con = mkDataCon src_name declared_infix vanilla
137                                      arg_stricts field_lbls
138                                      tyvars stupid_ctxt ctxt
139                                      arg_tys tycon res_tys dc_ids
140                 dc_ids = mkDataConIds wrap_name work_name data_con
141
142         ; returnM data_con }
143
144
145 -- The stupid context for a data constructor should be limited to
146 -- the type variables mentioned in the arg_tys
147 mkDataConStupidTheta tycon arg_tys res_tys
148   | null stupid_theta = []      -- The common case
149   | otherwise         = filter in_arg_tys stupid_theta
150   where
151     tc_subst        = zipTopTvSubst (tyConTyVars tycon) res_tys
152     stupid_theta    = substTheta tc_subst (tyConStupidTheta tycon)
153     arg_tyvars      = tyVarsOfTypes arg_tys
154     in_arg_tys pred = not $ isEmptyVarSet $ 
155                         tyVarsOfPred pred `intersectVarSet` arg_tyvars
156
157 ------------------------------------------------------
158 mkTyConFields :: TyCon -> AlgTyConRhs -> [(FieldLabel,Type,Id)]
159 mkTyConFields tycon rhs
160   =     -- We'll check later that fields with the same name 
161         -- from different constructors have the same type.
162      [ (fld, ty, mkRecordSelId tycon fld ty) 
163      | (fld, ty) <- nubBy eq_fld all_fld_tys ]
164   where
165     all_fld_tys    = concatMap fld_tys_of (visibleDataCons rhs)
166     fld_tys_of con = dataConFieldLabels con `zipLazy` 
167                      dataConOrigArgTys con
168                 -- The laziness means that the type isn't sucked in prematurely
169                 -- Only vanilla datacons have fields at all, and they
170                 -- share the tycon's type variables => datConOrigArgTys will do
171
172     eq_fld (f1,_) (f2,_) = f1 == f2
173 \end{code}
174
175
176 ------------------------------------------------------
177 \begin{code}
178 buildClass :: Name -> [TyVar] -> ThetaType
179            -> [FunDep TyVar]            -- Functional dependencies
180            -> [(Name, DefMeth, Type)]   -- Method info
181            -> RecFlag -> ArgVrcs        -- Info for type constructor
182            -> TcRnIf m n Class
183
184 buildClass class_name tvs sc_theta fds sig_stuff tc_isrec tc_vrcs
185   = do  { tycon_name <- newImplicitBinder class_name mkClassTyConOcc
186         ; datacon_name <- newImplicitBinder class_name mkClassDataConOcc
187                 -- The class name is the 'parent' for this datacon, not its tycon,
188                 -- because one should import the class to get the binding for 
189                 -- the datacon
190         ; sc_sel_names <- mapM (newImplicitBinder class_name . mkSuperDictSelOcc) 
191                                 [1..length sc_theta]
192               -- We number off the superclass selectors, 1, 2, 3 etc so that we 
193               -- can construct names for the selectors.  Thus
194               --      class (C a, C b) => D a b where ...
195               -- gives superclass selectors
196               --      D_sc1, D_sc2
197               -- (We used to call them D_C, but now we can have two different
198               --  superclasses both called C!)
199
200         ; fixM (\ clas -> do {  -- Only name generation inside loop
201
202           let { op_tys             = [ty | (_,_,ty) <- sig_stuff]
203               ; sc_tys             = mkPredTys sc_theta
204               ; dict_component_tys = sc_tys ++ op_tys
205               ; sc_sel_ids         = [mkDictSelId sc_name clas | sc_name <- sc_sel_names]
206               ; op_items = [ (mkDictSelId op_name clas, dm_info)
207                            | (op_name, dm_info, _) <- sig_stuff ] }
208                         -- Build the selector id and default method id
209
210         ; dict_con <- buildDataCon datacon_name 
211                                    False        -- Not declared infix
212                                    True         -- Is vanilla; tyvars same as tycon
213                                    (map (const NotMarkedStrict) dict_component_tys)
214                                    [{- No labelled fields -}]
215                                    tvs [{-No context-}] dict_component_tys
216                                    (classTyCon clas) (mkTyVarTys tvs)
217
218         ; let { clas = mkClass class_name tvs fds
219                        sc_theta sc_sel_ids op_items
220                        tycon
221
222               ; tycon = mkClassTyCon tycon_name clas_kind tvs
223                              tc_vrcs rhs clas tc_isrec
224                 -- A class can be recursive, and in the case of newtypes 
225                 -- this matters.  For example
226                 --      class C a where { op :: C b => a -> b -> Int }
227                 -- Because C has only one operation, it is represented by
228                 -- a newtype, and it should be a *recursive* newtype.
229                 -- [If we don't make it a recursive newtype, we'll expand the
230                 -- newtype like a synonym, but that will lead to an infinite type]
231
232               ; clas_kind = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
233
234               ; rhs = case dict_component_tys of
235                             [rep_ty] -> mkNewTyConRhs tycon dict_con
236                             other    -> mkDataTyConRhs [dict_con]
237               }
238         ; return clas
239         })}
240 \end{code}
241
242