[project @ 2005-11-09 11:36:43 by simonmar]
[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 DataCon          ( DataCon, isNullarySrcDataCon,
18                           mkDataCon, dataConFieldLabels, dataConOrigArgTys )
19 import Var              ( tyVarKind, TyVar, Id )
20 import VarSet           ( isEmptyVarSet, intersectVarSet )
21 import TysWiredIn       ( unitTy )
22 import BasicTypes       ( RecFlag, StrictnessMark(..) )
23 import Name             ( Name )
24 import OccName          ( mkDataConWrapperOcc, mkDataConWorkerOcc, mkClassTyConOcc,
25                           mkClassDataConOcc, mkSuperDictSelOcc )
26 import MkId             ( mkDataConIds, mkRecordSelId, mkDictSelId )
27 import Class            ( mkClass, Class( classTyCon), FunDep, DefMeth(..) )
28 import TyCon            ( mkSynTyCon, mkAlgTyCon, visibleDataCons, tyConStupidTheta,
29                           tyConDataCons, isNewTyCon, mkClassTyCon, TyCon( tyConTyVars ),
30                           ArgVrcs, AlgTyConRhs(..), newTyConRhs )
31 import Type             ( mkArrowKinds, liftedTypeKind, typeKind, tyVarsOfTypes, tyVarsOfPred,
32                           splitTyConApp_maybe, mkPredTys, mkTyVarTys, ThetaType, Type,
33                           substTyWith, zipTopTvSubst, substTheta )
34 import Outputable
35 import List             ( nub )
36
37 \end{code}
38         
39
40 \begin{code}
41 ------------------------------------------------------
42 buildSynTyCon name tvs rhs_ty arg_vrcs
43   = mkSynTyCon name kind tvs rhs_ty arg_vrcs
44   where
45     kind = mkArrowKinds (map tyVarKind tvs) (typeKind rhs_ty)
46
47
48 ------------------------------------------------------
49 buildAlgTyCon :: Name -> [TyVar] 
50               -> ThetaType              -- Stupid theta
51               -> AlgTyConRhs
52               -> ArgVrcs -> RecFlag
53               -> Bool                   -- True <=> want generics functions
54               -> TcRnIf m n TyCon
55
56 buildAlgTyCon tc_name tvs stupid_theta rhs arg_vrcs is_rec want_generics
57   = do  { let { tycon = mkAlgTyCon tc_name kind tvs arg_vrcs stupid_theta
58                                    rhs fields is_rec want_generics
59               ; kind    = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
60               ; fields  = mkTyConSelIds 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 isNullarySrcDataCon cons)
71
72 mkNewTyConRhs :: TyCon -> DataCon -> AlgTyConRhs
73 mkNewTyConRhs tycon con 
74   = NewTyCon con rhs_ty (mkNewTyConRep tycon)
75   where
76     rhs_ty = head (dataConOrigArgTys con)
77         -- Newtypes are guaranteed vanilla, so OrigArgTys will do
78                                 
79 mkNewTyConRep :: TyCon          -- The original type constructor
80               -> Type           -- Chosen representation type
81                                 -- (guaranteed not to be another newtype)
82                                 -- Free vars of rep = tyConTyVars tc
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 (tc1, tys) | isNewTyCon tc1
107                            -> ASSERT( length (tyConTyVars tc1) == length tys )
108                               substTyWith (tyConTyVars tc1) tys (go (tc:tcs) tc1)
109             other          -> rhs_ty 
110         where
111           (_tc_tvs, rhs_ty) = newTyConRhs tc
112
113
114 ------------------------------------------------------
115 buildDataCon :: Name -> Bool -> Bool
116             -> [StrictnessMark] 
117             -> [Name]                   -- Field labels
118             -> [TyVar] 
119             -> ThetaType                -- Does not include the "stupid theta"
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         -- Start by instantiating the master copy of the 
154         -- stupid theta, taken from the TyCon
155
156     arg_tyvars      = tyVarsOfTypes arg_tys
157     in_arg_tys pred = not $ isEmptyVarSet $ 
158                         tyVarsOfPred pred `intersectVarSet` arg_tyvars
159
160 ------------------------------------------------------
161 mkTyConSelIds :: TyCon -> AlgTyConRhs -> [Id]
162 mkTyConSelIds tycon rhs
163   =  [ mkRecordSelId tycon fld 
164      | fld <- nub (concatMap dataConFieldLabels (visibleDataCons rhs)) ]
165         -- We'll check later that fields with the same name 
166         -- from different constructors have the same type.
167 \end{code}
168
169
170 ------------------------------------------------------
171 \begin{code}
172 buildClass :: Name -> [TyVar] -> ThetaType
173            -> [FunDep TyVar]            -- Functional dependencies
174            -> [(Name, DefMeth, Type)]   -- Method info
175            -> RecFlag -> ArgVrcs        -- Info for type constructor
176            -> TcRnIf m n Class
177
178 buildClass class_name tvs sc_theta fds sig_stuff tc_isrec tc_vrcs
179   = do  { tycon_name <- newImplicitBinder class_name mkClassTyConOcc
180         ; datacon_name <- newImplicitBinder class_name mkClassDataConOcc
181                 -- The class name is the 'parent' for this datacon, not its tycon,
182                 -- because one should import the class to get the binding for 
183                 -- the datacon
184         ; sc_sel_names <- mapM (newImplicitBinder class_name . mkSuperDictSelOcc) 
185                                 [1..length sc_theta]
186               -- We number off the superclass selectors, 1, 2, 3 etc so that we 
187               -- can construct names for the selectors.  Thus
188               --      class (C a, C b) => D a b where ...
189               -- gives superclass selectors
190               --      D_sc1, D_sc2
191               -- (We used to call them D_C, but now we can have two different
192               --  superclasses both called C!)
193
194         ; fixM (\ clas -> do {  -- Only name generation inside loop
195
196           let { op_tys             = [ty | (_,_,ty) <- sig_stuff]
197               ; sc_tys             = mkPredTys sc_theta
198               ; dict_component_tys = sc_tys ++ op_tys
199               ; sc_sel_ids         = [mkDictSelId sc_name clas | sc_name <- sc_sel_names]
200               ; op_items = [ (mkDictSelId op_name clas, dm_info)
201                            | (op_name, dm_info, _) <- sig_stuff ] }
202                         -- Build the selector id and default method id
203
204         ; dict_con <- buildDataCon datacon_name 
205                                    False        -- Not declared infix
206                                    True         -- Is vanilla; tyvars same as tycon
207                                    (map (const NotMarkedStrict) dict_component_tys)
208                                    [{- No labelled fields -}]
209                                    tvs [{-No context-}] dict_component_tys
210                                    (classTyCon clas) (mkTyVarTys tvs)
211
212         ; let { clas = mkClass class_name tvs fds
213                        sc_theta sc_sel_ids op_items
214                        tycon
215
216               ; tycon = mkClassTyCon tycon_name clas_kind tvs
217                              tc_vrcs rhs clas tc_isrec
218                 -- A class can be recursive, and in the case of newtypes 
219                 -- this matters.  For example
220                 --      class C a where { op :: C b => a -> b -> Int }
221                 -- Because C has only one operation, it is represented by
222                 -- a newtype, and it should be a *recursive* newtype.
223                 -- [If we don't make it a recursive newtype, we'll expand the
224                 -- newtype like a synonym, but that will lead to an infinite type]
225
226               ; clas_kind = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
227
228               ; rhs = case dict_component_tys of
229                             [rep_ty] -> mkNewTyConRhs tycon dict_con
230                             other    -> mkDataTyConRhs [dict_con]
231               }
232         ; return clas
233         })}
234 \end{code}
235
236