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