Remove Linear Implicit Parameters, and all their works
[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, mkOpenDataTyConRhs, mkOpenNewTyConRhs,
10         mkNewTyConRhs, mkDataTyConRhs 
11     ) where
12
13 #include "HsVersions.h"
14
15 import IfaceEnv         ( newImplicitBinder )
16 import TcRnMonad
17
18 import DataCon          ( DataCon, isNullarySrcDataCon, 
19                           mkDataCon, dataConFieldLabels, dataConInstOrigArgTys )
20 import Var              ( tyVarKind, TyVar, Id )
21 import VarSet           ( isEmptyVarSet, intersectVarSet, elemVarSet )
22 import TysWiredIn       ( unitTy )
23 import BasicTypes       ( RecFlag, StrictnessMark(..) )
24 import Name             ( Name )
25 import OccName          ( mkDataConWrapperOcc, mkDataConWorkerOcc,
26                           mkClassTyConOcc, mkClassDataConOcc,
27                           mkSuperDictSelOcc, mkNewTyCoOcc, 
28                           mkInstTyCoOcc ) 
29 import MkId             ( mkDataConIds, mkRecordSelId, mkDictSelId )
30 import Class            ( mkClass, Class( classTyCon), FunDep, DefMeth(..) )
31 import TyCon            ( mkSynTyCon, mkAlgTyCon, visibleDataCons,
32                           tyConStupidTheta, tyConDataCons, isNewTyCon,
33                           mkClassTyCon, TyCon( tyConTyVars ),
34                           isRecursiveTyCon, AlgTyConRhs(..),
35                           SynTyConRhs(..), newTyConRhs, AlgTyConParent(..) )
36 import Type             ( mkArrowKinds, liftedTypeKind, typeKind, 
37                           tyVarsOfType, tyVarsOfTypes, tyVarsOfPred,
38                           splitTyConApp_maybe, splitAppTy_maybe,
39                           getTyVar_maybe, 
40                           mkPredTys, mkTyVarTys, ThetaType, Type, 
41                           TyThing(..), 
42                           substTyWith, zipTopTvSubst, substTheta )
43 import Coercion         ( mkNewTypeCoercion, mkDataInstCoercion )
44 import Outputable
45 import List             ( nub )
46
47 \end{code}
48         
49
50 \begin{code}
51 ------------------------------------------------------
52 buildSynTyCon :: Name -> [TyVar] -> SynTyConRhs -> TyCon
53 buildSynTyCon name tvs rhs@(OpenSynTyCon rhs_ki)
54   = mkSynTyCon name kind tvs rhs
55   where
56     kind = mkArrowKinds (map tyVarKind tvs) rhs_ki
57 buildSynTyCon name tvs rhs@(SynonymTyCon rhs_ty)
58   = mkSynTyCon name kind tvs rhs
59   where
60     kind = mkArrowKinds (map tyVarKind tvs) (typeKind rhs_ty)
61
62
63 ------------------------------------------------------
64 buildAlgTyCon :: Name -> [TyVar] 
65               -> ThetaType              -- Stupid theta
66               -> AlgTyConRhs
67               -> RecFlag
68               -> Bool                   -- True <=> want generics functions
69               -> Bool                   -- True <=> was declared in GADT syntax
70               -> Maybe (TyCon, [Type])  -- family instance if applicable
71               -> TcRnIf m n TyCon
72
73 buildAlgTyCon tc_name tvs stupid_theta rhs is_rec want_generics gadt_syn
74               mb_family
75   = do { -- We need to tie a knot as the coercion of a data instance depends
76          -- on the instance representation tycon and vice versa.
77        ; tycon <- fixM (\ tycon_rec -> do 
78          { parent <- parentInfo mb_family tycon_rec
79          ; let { tycon = mkAlgTyCon tc_name kind tvs stupid_theta rhs
80                                     fields parent is_rec want_generics gadt_syn
81                ; kind    = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
82                ; fields  = mkTyConSelIds tycon rhs
83                }
84          ; return tycon
85          })
86        ; return tycon 
87        }
88   where
89     -- If a family tycon with instance types is given, the current tycon is an
90     -- instance of that family and we need to
91     --
92     -- (1) create a coercion that identifies the family instance type and the
93     --     representation type from Step (1); ie, it is of the form 
94     --     `Co tvs :: F ts :=: R tvs', where `Co' is the name of the coercion,
95     --     `F' the family tycon and `R' the (derived) representation tycon,
96     --     and
97     -- (2) produce a `AlgTyConParent' value containing the parent and coercion
98     --     information.
99     --
100     parentInfo Nothing                  rep_tycon = 
101       return NoParentTyCon
102     parentInfo (Just (family, instTys)) rep_tycon =
103       do { -- Create the coercion
104          ; co_tycon_name <- newImplicitBinder tc_name mkInstTyCoOcc
105          ; let co_tycon = mkDataInstCoercion co_tycon_name tvs
106                                              family instTys rep_tycon
107          ; return $ FamilyTyCon family instTys co_tycon
108          }
109     
110
111 ------------------------------------------------------
112 mkAbstractTyConRhs :: AlgTyConRhs
113 mkAbstractTyConRhs = AbstractTyCon
114
115 mkOpenDataTyConRhs :: AlgTyConRhs
116 mkOpenDataTyConRhs = OpenDataTyCon
117
118 mkOpenNewTyConRhs :: AlgTyConRhs
119 mkOpenNewTyConRhs = OpenNewTyCon
120
121 mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
122 mkDataTyConRhs cons
123   = DataTyCon { data_cons = cons, is_enum = all isNullarySrcDataCon cons }
124
125 mkNewTyConRhs :: Name -> TyCon -> DataCon -> TcRnIf m n AlgTyConRhs
126 -- Monadic because it makes a Name for the coercion TyCon
127 -- We pass the Name of the parent TyCon, as well as the TyCon itself,
128 -- because the latter is part of a knot, whereas the former is not.
129 mkNewTyConRhs tycon_name tycon con 
130   = do  { co_tycon_name <- newImplicitBinder tycon_name mkNewTyCoOcc
131         ; let co_tycon = mkNewTypeCoercion co_tycon_name tycon etad_rhs
132               cocon_maybe | all_coercions || isRecursiveTyCon tycon 
133                           = Just co_tycon
134                           | otherwise              
135                           = Nothing
136         ; return (NewTyCon { data_con    = con, 
137                              nt_rhs      = rhs_ty,
138                              nt_etad_rhs = etad_rhs,
139                              nt_co = cocon_maybe, 
140                              -- Coreview looks through newtypes with a Nothing
141                              -- for nt_co, or uses explicit coercions otherwise
142                              nt_rep = mkNewTyConRep tycon rhs_ty }) }
143   where
144         -- If all_coercions is True then we use coercions for all newtypes
145         -- otherwise we use coercions for recursive newtypes and look through
146         -- non-recursive newtypes
147     all_coercions = True
148     tvs    = tyConTyVars tycon
149     rhs_ty = head (dataConInstOrigArgTys con (mkTyVarTys tvs))
150         -- Instantiate the data con with the 
151         -- type variables from the tycon
152
153     etad_rhs :: ([TyVar], Type)
154     etad_rhs = eta_reduce (reverse tvs) rhs_ty
155
156     eta_reduce :: [TyVar]               -- Reversed
157                -> Type                  -- Rhs type
158                -> ([TyVar], Type)       -- Eta-reduced version (tyvars in normal order)
159     eta_reduce (a:as) ty | Just (fun, arg) <- splitAppTy_maybe ty,
160                            Just tv <- getTyVar_maybe arg,
161                            tv == a,
162                            not (a `elemVarSet` tyVarsOfType fun)
163                          = eta_reduce as fun
164     eta_reduce tvs ty = (reverse tvs, ty)
165                                 
166
167 mkNewTyConRep :: TyCon          -- The original type constructor
168               -> Type           -- The arg type of its constructor
169               -> Type           -- Chosen representation type
170 -- The "representation type" is guaranteed not to be another newtype
171 -- at the outermost level; but it might have newtypes in type arguments
172
173 -- Find the representation type for this newtype TyCon
174 -- Remember that the representation type is the *ultimate* representation
175 -- type, looking through other newtypes.
176 -- 
177 -- splitTyConApp_maybe no longer looks through newtypes, so we must
178 -- deal explicitly with this case
179 -- 
180 -- The trick is to to deal correctly with recursive newtypes
181 -- such as      newtype T = MkT T
182
183 mkNewTyConRep tc rhs_ty
184   | null (tyConDataCons tc) = unitTy
185         -- External Core programs can have newtypes with no data constructors
186   | otherwise               = go [tc] rhs_ty
187   where
188         -- Invariant: tcs have been seen before
189     go tcs rep_ty 
190         = case splitTyConApp_maybe rep_ty of
191             Just (tc, tys)
192                 | tc `elem` tcs -> unitTy       -- Recursive loop
193                 | isNewTyCon tc -> 
194                     if isRecursiveTyCon tc then
195                         go (tc:tcs) (substTyWith tvs tys rhs_ty)
196                     else
197                         substTyWith tvs tys rhs_ty
198                 where
199                   (tvs, rhs_ty) = newTyConRhs tc
200
201             other -> rep_ty 
202
203 ------------------------------------------------------
204 buildDataCon :: Name -> Bool
205             -> [StrictnessMark] 
206             -> [Name]                   -- Field labels
207             -> [TyVar] -> [TyVar]       -- Univ and ext 
208             -> [(TyVar,Type)]           -- Equality spec
209             -> ThetaType                -- Does not include the "stupid theta"
210                                         -- or the GADT equalities
211             -> [Type] -> TyCon
212             -> TcRnIf m n DataCon
213 -- A wrapper for DataCon.mkDataCon that
214 --   a) makes the worker Id
215 --   b) makes the wrapper Id if necessary, including
216 --      allocating its unique (hence monadic)
217 buildDataCon src_name declared_infix arg_stricts field_lbls
218              univ_tvs ex_tvs eq_spec ctxt arg_tys tycon
219   = do  { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
220         ; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
221         -- This last one takes the name of the data constructor in the source
222         -- code, which (for Haskell source anyway) will be in the DataName name
223         -- space, and puts it into the VarName name space
224
225         ; let
226                 stupid_ctxt = mkDataConStupidTheta tycon arg_tys univ_tvs
227                 data_con = mkDataCon src_name declared_infix
228                                      arg_stricts field_lbls
229                                      univ_tvs ex_tvs eq_spec ctxt
230                                      arg_tys tycon
231                                      stupid_ctxt dc_ids
232                 dc_ids = mkDataConIds wrap_name work_name data_con
233
234         ; returnM data_con }
235
236
237 -- The stupid context for a data constructor should be limited to
238 -- the type variables mentioned in the arg_tys
239 -- ToDo: Or functionally dependent on?  
240 --       This whole stupid theta thing is, well, stupid.
241 mkDataConStupidTheta tycon arg_tys univ_tvs
242   | null stupid_theta = []      -- The common case
243   | otherwise         = filter in_arg_tys stupid_theta
244   where
245     tc_subst     = zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs)
246     stupid_theta = substTheta tc_subst (tyConStupidTheta tycon)
247         -- Start by instantiating the master copy of the 
248         -- stupid theta, taken from the TyCon
249
250     arg_tyvars      = tyVarsOfTypes arg_tys
251     in_arg_tys pred = not $ isEmptyVarSet $ 
252                       tyVarsOfPred pred `intersectVarSet` arg_tyvars
253
254 ------------------------------------------------------
255 mkTyConSelIds :: TyCon -> AlgTyConRhs -> [Id]
256 mkTyConSelIds tycon rhs
257   =  [ mkRecordSelId tycon fld 
258      | fld <- nub (concatMap dataConFieldLabels (visibleDataCons rhs)) ]
259         -- We'll check later that fields with the same name 
260         -- from different constructors have the same type.
261 \end{code}
262
263
264 ------------------------------------------------------
265 \begin{code}
266 buildClass :: Name -> [TyVar] -> ThetaType
267            -> [FunDep TyVar]            -- Functional dependencies
268            -> [TyThing]                 -- Associated types
269            -> [(Name, DefMeth, Type)]   -- Method info
270            -> RecFlag                   -- Info for type constructor
271            -> TcRnIf m n Class
272
273 buildClass class_name tvs sc_theta fds ats sig_stuff tc_isrec
274   = do  { tycon_name <- newImplicitBinder class_name mkClassTyConOcc
275         ; datacon_name <- newImplicitBinder class_name mkClassDataConOcc
276                 -- The class name is the 'parent' for this datacon, not its tycon,
277                 -- because one should import the class to get the binding for 
278                 -- the datacon
279         ; sc_sel_names <- mapM (newImplicitBinder class_name . mkSuperDictSelOcc) 
280                                 [1..length sc_theta]
281               -- We number off the superclass selectors, 1, 2, 3 etc so that we 
282               -- can construct names for the selectors.  Thus
283               --      class (C a, C b) => D a b where ...
284               -- gives superclass selectors
285               --      D_sc1, D_sc2
286               -- (We used to call them D_C, but now we can have two different
287               --  superclasses both called C!)
288
289         ; fixM (\ rec_clas -> do {      -- Only name generation inside loop
290
291           let { rec_tycon          = classTyCon rec_clas
292               ; op_tys             = [ty | (_,_,ty) <- sig_stuff]
293               ; sc_tys             = mkPredTys sc_theta
294               ; dict_component_tys = sc_tys ++ op_tys
295               ; sc_sel_ids         = [mkDictSelId sc_name rec_clas | sc_name <- sc_sel_names]
296               ; op_items = [ (mkDictSelId op_name rec_clas, dm_info)
297                            | (op_name, dm_info, _) <- sig_stuff ] }
298                         -- Build the selector id and default method id
299
300         ; dict_con <- buildDataCon datacon_name
301                                    False        -- Not declared infix
302                                    (map (const NotMarkedStrict) dict_component_tys)
303                                    [{- No labelled fields -}]
304                                    tvs [{- no existentials -}]
305                                    [{- No equalities -}] [{-No context-}] 
306                                    dict_component_tys 
307                                    rec_tycon
308
309         ; rhs <- case dict_component_tys of
310                             [rep_ty] -> mkNewTyConRhs tycon_name rec_tycon dict_con
311                             other    -> return (mkDataTyConRhs [dict_con])
312
313         ; let { clas_kind = mkArrowKinds (map tyVarKind tvs) liftedTypeKind
314
315               ; tycon = mkClassTyCon tycon_name clas_kind tvs
316                              rhs rec_clas tc_isrec
317                 -- A class can be recursive, and in the case of newtypes 
318                 -- this matters.  For example
319                 --      class C a where { op :: C b => a -> b -> Int }
320                 -- Because C has only one operation, it is represented by
321                 -- a newtype, and it should be a *recursive* newtype.
322                 -- [If we don't make it a recursive newtype, we'll expand the
323                 -- newtype like a synonym, but that will lead to an infinite
324                 -- type]
325               ; atTyCons = [tycon | ATyCon tycon <- ats]
326               }
327         ; return (mkClass class_name tvs fds 
328                        sc_theta sc_sel_ids atTyCons op_items
329                        tycon)
330         })}
331 \end{code}
332
333