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