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