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