6636d7772ff856bb6a1519a044847e998d2f8c6d
[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, visibleDataCons )
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
84 -- Find the representation type for this newtype TyCon
85 -- Remember that the representation type is the *ultimate* representation
86 -- type, looking through other newtypes.
87 -- 
88 -- The non-recursive newtypes are easy, because they look transparent
89 -- to splitTyConApp_maybe, but recursive ones really are represented as
90 -- TyConApps (see TypeRep).
91 -- 
92 -- The trick is to to deal correctly with recursive newtypes
93 -- such as      newtype T = MkT T
94
95 mkNewTyConRep tc
96   | null (tyConDataCons tc) = unitTy
97         -- External Core programs can have newtypes with no data constructors
98   | otherwise               = go [] tc
99   where
100         -- Invariant: tc is a NewTyCon
101         --            tcs have been seen before
102     go tcs tc 
103         | tc `elem` tcs = unitTy
104         | otherwise
105         = case splitTyConApp_maybe rhs_ty of
106             Just (tc', tys) | isNewTyCon tc'
107                            -> substTyWith tc_tvs tys (go (tc:tcs) tc')
108             other          -> rhs_ty 
109         where
110           (tc_tvs, rhs_ty) = newTyConRhs tc
111
112
113 ------------------------------------------------------
114 buildDataCon :: Name -> Bool -> Bool
115             -> [StrictnessMark] 
116             -> [Name]                   -- Field labels
117             -> [TyVar] -> ThetaType
118             -> [Type] -> TyCon -> [Type]
119             -> TcRnIf m n DataCon
120 -- A wrapper for DataCon.mkDataCon that
121 --   a) makes the worker Id
122 --   b) makes the wrapper Id if necessary, including
123 --      allocating its unique (hence monadic)
124 buildDataCon src_name declared_infix vanilla arg_stricts field_lbls
125              tyvars ctxt arg_tys tycon res_tys
126   = do  { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
127         ; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
128         -- This last one takes the name of the data constructor in the source
129         -- code, which (for Haskell source anyway) will be in the SrcDataName name
130         -- space, and makes it into a "real data constructor name"
131
132         ; let
133                 stupid_ctxt = mkDataConStupidTheta tycon arg_tys res_tys
134                 data_con = mkDataCon src_name declared_infix vanilla
135                                      arg_stricts field_lbls
136                                      tyvars stupid_ctxt ctxt
137                                      arg_tys tycon res_tys dc_ids
138                 dc_ids = mkDataConIds wrap_name work_name data_con
139
140         ; returnM data_con }
141
142
143 -- The stupid context for a data constructor should be limited to
144 -- the type variables mentioned in the arg_tys
145 mkDataConStupidTheta tycon arg_tys res_tys
146   | null stupid_theta = []      -- The common case
147   | otherwise         = filter in_arg_tys stupid_theta
148   where
149     tc_subst        = zipTopTvSubst (tyConTyVars tycon) res_tys
150     stupid_theta    = substTheta tc_subst (tyConStupidTheta tycon)
151     arg_tyvars      = tyVarsOfTypes arg_tys
152     in_arg_tys pred = not $ isEmptyVarSet $ 
153                         tyVarsOfPred pred `intersectVarSet` arg_tyvars
154
155 ------------------------------------------------------
156 mkTyConFields :: TyCon -> AlgTyConRhs -> [(FieldLabel,Type,Id)]
157 mkTyConFields tycon rhs
158   =     -- We'll check later that fields with the same name 
159         -- from different constructors have the same type.
160      [ (fld, ty, mkRecordSelId tycon fld ty) 
161      | (fld, ty) <- nubBy eq_fld all_fld_tys ]
162   where
163     all_fld_tys    = concatMap fld_tys_of (visibleDataCons rhs)
164     fld_tys_of con = dataConFieldLabels con `zipLazy` 
165                      dataConOrigArgTys con
166                 -- The laziness means that the type isn't sucked in prematurely
167                 -- Only vanilla datacons have fields at all, and they
168                 -- share the tycon's type variables => datConOrigArgTys will do
169
170     eq_fld (f1,_) (f2,_) = f1 == f2
171 \end{code}
172
173
174 ------------------------------------------------------
175 \begin{code}
176 buildClass :: Name -> [TyVar] -> ThetaType
177            -> [FunDep TyVar]            -- Functional dependencies
178            -> [(Name, DefMeth, Type)]   -- Method info
179            -> RecFlag -> ArgVrcs        -- Info for type constructor
180            -> TcRnIf m n Class
181
182 buildClass class_name tvs sc_theta fds sig_stuff tc_isrec tc_vrcs
183   = do  { tycon_name <- newImplicitBinder class_name mkClassTyConOcc
184         ; datacon_name <- newImplicitBinder class_name mkClassDataConOcc
185                 -- The class name is the 'parent' for this datacon, not its tycon,
186                 -- because one should import the class to get the binding for 
187                 -- the datacon
188         ; sc_sel_names <- mapM (newImplicitBinder class_name . mkSuperDictSelOcc) 
189                                 [1..length sc_theta]
190               -- We number off the superclass selectors, 1, 2, 3 etc so that we 
191               -- can construct names for the selectors.  Thus
192               --      class (C a, C b) => D a b where ...
193               -- gives superclass selectors
194               --      D_sc1, D_sc2
195               -- (We used to call them D_C, but now we can have two different
196               --  superclasses both called C!)
197
198         ; fixM (\ clas -> do {  -- Only name generation inside loop
199
200           let { op_tys             = [ty | (_,_,ty) <- sig_stuff]
201               ; sc_tys             = mkPredTys sc_theta
202               ; dict_component_tys = sc_tys ++ op_tys
203               ; sc_sel_ids         = [mkDictSelId sc_name clas | sc_name <- sc_sel_names]
204               ; op_items = [ (mkDictSelId op_name clas, dm_info)
205                            | (op_name, dm_info, _) <- sig_stuff ] }
206                         -- Build the selector id and default method id
207
208         ; dict_con <- buildDataCon datacon_name 
209                                    False        -- Not declared infix
210                                    True         -- Is vanilla; tyvars same as tycon
211                                    (map (const NotMarkedStrict) dict_component_tys)
212                                    [{- No labelled fields -}]
213                                    tvs [{-No context-}] dict_component_tys
214                                    (classTyCon clas) (mkTyVarTys tvs)
215
216         ; let { clas = mkClass class_name tvs fds
217                        sc_theta sc_sel_ids op_items
218                        tycon
219
220               ; tycon = mkClassTyCon tycon_name clas_kind tvs
221                              tc_vrcs rhs clas tc_isrec
222                 -- A class can be recursive, and in the case of newtypes 
223                 -- this matters.  For example
224                 --      class C a where { op :: C b => a -> b -> Int }
225                 -- Because C has only one operation, it is represented by
226                 -- a newtype, and it should be a *recursive* newtype.
227                 -- [If we don't make it a recursive newtype, we'll expand the
228                 -- newtype like a synonym, but that will lead to an infinite type]
229
230               ; clas_kind = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
231
232               ; rhs = case dict_component_tys of
233                             [rep_ty] -> mkNewTyConRhs tycon dict_con
234                             other    -> mkDataTyConRhs [dict_con]
235               }
236         ; return clas
237         })}
238 \end{code}
239
240