2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1995
4 \section[TcClassDcl]{Typechecking class declarations}
7 #include "HsVersions.h"
9 module TcClassDcl ( tcClassDecl1, tcClassDecls2 ) where
13 import HsSyn ( HsDecl(..), ClassDecl(..), HsBinds(..), Bind(..), MonoBinds(..),
14 Match(..), GRHSsAndBinds(..), GRHS(..), HsExpr(..),
15 DefaultDecl, TyDecl, InstDecl, IfaceSig, Fixity,
16 HsLit(..), OutPat(..), Sig(..), HsType(..), HsTyVar,
17 Stmt, DoOrListComp, ArithSeqInfo, InPat, Fake )
18 import HsTypes ( getTyVarName )
19 import HsPragmas ( ClassPragmas(..) )
20 import RnHsSyn ( RenamedClassDecl(..), RenamedClassPragmas(..),
21 RenamedClassOpSig(..), SYN_IE(RenamedMonoBinds),
22 RenamedGenPragmas(..), RenamedContext(..), SYN_IE(RenamedHsDecl)
24 import TcHsSyn ( TcIdOcc(..), SYN_IE(TcHsBinds), SYN_IE(TcMonoBinds), SYN_IE(TcExpr),
25 mkHsTyApp, mkHsTyLam, mkHsDictApp, mkHsDictLam, tcIdType )
27 import Inst ( Inst, InstOrigin(..), SYN_IE(LIE), emptyLIE, plusLIE, newDicts, newMethod )
28 import TcEnv ( tcLookupClass, tcLookupTyVar, tcLookupTyCon, newLocalIds, tcAddImportedIdInfo,
29 tcExtendGlobalTyVars )
30 import TcInstDcls ( processInstBinds )
31 import TcKind ( unifyKind, TcKind )
33 import TcMonoType ( tcHsType, tcContext )
34 import TcSimplify ( tcSimplifyAndCheck )
35 import TcType ( SYN_IE(TcType), SYN_IE(TcTyVar), tcInstType, tcInstSigTyVars, tcInstSigType )
37 import Bag ( foldBag, unionManyBags )
38 import Class ( GenClass, GenClassOp, mkClass, mkClassOp, classBigSig,
39 classOps, classOpString, classOpLocalType,
40 classOpTagByOccName, SYN_IE(ClassOp)
42 import Id ( GenId, mkSuperDictSelId, mkMethodSelId, mkDefaultMethodId, getIdUnfolding,
44 import CoreUnfold ( getUnfoldingTemplate )
46 import Name ( Name, isLocallyDefined, moduleString, modAndOcc, nameString )
47 import PrelVals ( nO_DEFAULT_METHOD_ERROR_ID )
50 import PprType ( GenType, GenTyVar, GenClassOp )
51 import SpecEnv ( SpecEnv )
52 import SrcLoc ( mkGeneratedSrcLoc )
53 import Type ( mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy,
54 mkForAllTy, mkSigmaTy, splitSigmaTy)
55 import TysWiredIn ( stringTy )
56 import TyVar ( unitTyVarSet, GenTyVar )
57 import Unique ( Unique )
61 -- import TcPragmas ( tcGenPragmas, tcClassOpPragmas )
62 tcGenPragmas ty id ps = returnNF_Tc noIdInfo
63 tcClassOpPragmas ty sel def spec ps = returnNF_Tc (noIdInfo `addSpecInfo` spec,
71 Every class implicitly declares a new data type, corresponding to dictionaries
72 of that class. So, for example:
74 class (D a) => C a where
76 op2 :: forall b. Ord b => a -> b -> b
78 would implicitly declare
80 data CDict a = CDict (D a)
82 (forall b. Ord b => a -> b -> b)
84 (We could use a record decl, but that means changing more of the existing apparatus.
87 For classes with just one superclass+method, we use a newtype decl instead:
90 op :: forallb. a -> b -> b
94 newtype CDict a = CDict (forall b. a -> b -> b)
96 Now DictTy in Type is just a form of type synomym:
97 DictTy c t = TyConTy CDict `AppTy` t
99 Death to "ExpandingDicts".
103 tcClassDecl1 rec_inst_mapper
104 (ClassDecl context class_name
105 tyvar_name class_sigs def_methods pragmas src_loc)
106 = tcAddSrcLoc src_loc $
107 tcAddErrCtxt (classDeclCtxt class_name) $
109 -- LOOK THINGS UP IN THE ENVIRONMENT
110 tcLookupClass class_name `thenTc` \ (class_kind, rec_class) ->
111 tcLookupTyVar (getTyVarName tyvar_name) `thenNF_Tc` \ (tyvar_kind, rec_tyvar) ->
113 (rec_class_inst_env, rec_class_op_inst_fn) = rec_inst_mapper rec_class
116 -- FORCE THE CLASS AND ITS TYVAR TO HAVE SAME KIND
117 unifyKind class_kind tyvar_kind `thenTc_`
120 tcClassContext rec_class rec_tyvar context pragmas
121 `thenTc` \ (scs, sc_sel_ids) ->
123 -- CHECK THE CLASS SIGNATURES,
124 mapTc (tcClassSig rec_class rec_tyvar rec_class_op_inst_fn) class_sigs
125 `thenTc` \ sig_stuff ->
127 -- MAKE THE CLASS OBJECT ITSELF
129 (ops, op_sel_ids, defm_ids) = unzip3 sig_stuff
130 clas = mkClass (uniqueOf class_name) (getName class_name) rec_tyvar
131 scs sc_sel_ids ops op_sel_ids defm_ids
139 clas_ty = mkTyVarTy clas_tyvar
140 dict_component_tys = [mkDictTy sc clas_ty | sc <- scs] ++
141 [classOpLocalType op | op <- ops])
142 new_or_data = case dict_component_tys of
146 dict_con_id = mkDataCon class_name
148 [{- No labelled fields -}]
154 tycon = mkDataTyCon class_name
155 (tyVarKind rec_tyvar `mkArrowKind` mkBoxedTypeKind)
157 [{- Empty context -}]
159 [{- No derived classes -}]
165 tcClassContext :: Class -> TyVar
166 -> RenamedContext -- class context
167 -> RenamedClassPragmas -- pragmas for superclasses
168 -> TcM s ([Class], -- the superclasses
169 [Id]) -- superclass selector Ids
171 tcClassContext rec_class rec_tyvar context pragmas
172 = -- Check the context.
173 -- The renamer has already checked that the context mentions
174 -- only the type variable of the class decl.
175 tcContext context `thenTc` \ theta ->
177 super_classes = [ supers | (supers, _) <- theta ]
180 -- Make super-class selector ids
181 mapTc (mk_super_id rec_class) super_classes `thenTc` \ sc_sel_ids ->
184 returnTc (super_classes, sc_sel_ids)
187 rec_tyvar_ty = mkTyVarTy rec_tyvar
189 mk_super_id rec_class super_class
190 = tcGetUnique `thenNF_Tc` \ uniq ->
192 ty = mkForAllTy rec_tyvar $
193 mkFunTy (mkDictTy rec_class rec_tyvar_ty)
194 (mkDictTy super_class rec_tyvar_ty)
196 returnTc (mkSuperDictSelId uniq rec_class super_class ty)
199 tcClassSig :: Class -- Knot tying only!
200 -> TyVar -- The class type variable, used for error check only
201 -> (ClassOp -> SpecEnv) -- Ditto; the spec info for the class ops
203 -> TcM s (ClassOp, -- class op
205 Id) -- default-method ids
207 tcClassSig rec_clas rec_clas_tyvar rec_classop_spec_fn
208 (ClassOpSig op_name dm_name
211 = tcAddSrcLoc src_loc $
212 fixTc ( \ ~(_, rec_sel_id, rec_defm_id) -> -- Knot for pragmas
214 -- Check the type signature. NB that the envt *already has*
215 -- bindings for the type variables; see comments in TcTyAndClassDcls.
217 -- NB: Renamer checks that the class type variable is mentioned in local_ty,
218 -- and that it is not constrained by theta
219 tcHsType op_ty `thenTc` \ local_ty ->
221 global_ty = mkSigmaTy [rec_clas_tyvar]
222 [(rec_clas, mkTyVarTy rec_clas_tyvar)]
224 class_op_nm = getOccName op_name
225 class_op = mkClassOp class_op_nm
226 (classOpTagByOccName rec_clas{-yeeps!-} class_op_nm)
230 -- Build the selector id and default method id
232 sel_id = mkMethodSelId op_name rec_clas class_op global_ty
233 defm_id = mkDefaultMethodId dm_name rec_clas class_op False global_ty
234 -- ToDo: improve the "False"
236 tcAddImportedIdInfo defm_id `thenNF_Tc` \ final_defm_id ->
237 returnTc (class_op, sel_id, final_defm_id)
242 %************************************************************************
244 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
246 %************************************************************************
248 The purpose of pass 2 is
251 to beat on the explicitly-provided default-method decls (if any),
252 using them to produce a complete set of default-method decls.
253 (Omitted ones elicit an error message.)
255 to produce a definition for the selector function for each method
256 and superclass dictionary.
259 Pass~2 only applies to locally-defined class declarations.
261 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
262 each local class decl.
265 tcClassDecls2 :: [RenamedHsDecl]
266 -> NF_TcM s (LIE s, TcHsBinds s)
270 (returnNF_Tc (emptyLIE, EmptyBinds))
271 [tcClassDecl2 cls_decl | ClD cls_decl <- decls]
273 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
274 tc2 `thenNF_Tc` \ (lie2, binds2) ->
275 returnNF_Tc (lie1 `plusLIE` lie2,
276 binds1 `ThenBinds` binds2)
279 @tcClassDecl2@ is the business end of things.
282 tcClassDecl2 :: RenamedClassDecl -- The class declaration
283 -> NF_TcM s (LIE s, TcHsBinds s)
285 tcClassDecl2 (ClassDecl context class_name
286 tyvar_name class_sigs default_binds pragmas src_loc)
288 | not (isLocallyDefined class_name)
289 = returnNF_Tc (emptyLIE, EmptyBinds)
291 | otherwise -- It is locally defined
292 = recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyBinds)) $
293 tcAddSrcLoc src_loc $
295 -- Get the relevant class
296 tcLookupClass class_name `thenTc` \ (_, clas) ->
298 (tyvar, scs, sc_sel_ids, ops, op_sel_ids, defm_ids)
301 -- The selector binds are already in the selector Id's unfoldings
302 sel_binds = SingleBind $ NonRecBind $ foldr AndMonoBinds EmptyMonoBinds $
303 [ CoreMonoBind (RealId sel_id) (getUnfoldingTemplate (getIdUnfolding sel_id))
304 | sel_id <- sc_sel_ids ++ op_sel_ids,
305 isLocallyDefined sel_id
308 -- Generate bindings for the default methods
309 tcInstSigTyVars [tyvar] `thenNF_Tc` \ ([clas_tyvar], _, _) ->
310 buildDefaultMethodBinds clas clas_tyvar defm_ids default_binds
311 `thenTc` \ (const_insts, meth_binds) ->
313 returnTc (const_insts, sel_binds `ThenBinds` meth_binds)
316 %************************************************************************
318 \subsection[Default methods]{Default methods}
320 %************************************************************************
322 The default methods for a class are each passed a dictionary for the
323 class, so that they get access to the other methods at the same type.
324 So, given the class decl
328 op2 :: Ord b => a -> b -> b -> b
331 op2 x y z = if (op1 x) && (y < z) then y else z
333 we get the default methods:
335 defm.Foo.op1 :: forall a. Foo a => a -> Bool
336 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
338 ====================== OLD ==================
340 defm.Foo.op2 :: forall a, b. (Foo a, Ord b) => a -> b -> b -> b
341 defm.Foo.op2 = /\ a b -> \ dfoo dord -> \x y z ->
342 if (op1 a dfoo x) && (< b dord y z) then y else z
344 Notice that, like all ids, the foralls of defm.Foo.op2 are at the top.
345 ====================== END OF OLD ===================
349 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
350 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
351 if (op1 a dfoo x) && (< b dord y z) then y else z
355 When we come across an instance decl, we may need to use the default
358 instance Foo Int where {}
362 const.Foo.Int.op1 :: Int -> Bool
363 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
365 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
366 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
368 dfun.Foo.Int :: Foo Int
369 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
371 Notice that, as with method selectors above, we assume that dictionary
372 application is curried, so there's no need to mention the Ord dictionary
373 in const.Foo.Int.op2 (or the type variable).
376 instance Foo a => Foo [a] where {}
378 dfun.Foo.List :: forall a. Foo a -> Foo [a]
380 = /\ a -> \ dfoo_a ->
382 op1 = defm.Foo.op1 [a] dfoo_list
383 op2 = defm.Foo.op2 [a] dfoo_list
384 dfoo_list = (op1, op2)
390 buildDefaultMethodBinds
395 -> TcM s (LIE s, TcHsBinds s)
397 buildDefaultMethodBinds clas clas_tyvar
398 default_method_ids default_binds
399 = newDicts origin [(clas,inst_ty)] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
400 mapAndUnzipNF_Tc mk_method default_method_ids `thenNF_Tc` \ (insts_s, local_defm_ids) ->
402 avail_insts = this_dict `plusLIE` unionManyBags insts_s -- Insts available
403 clas_tyvar_set = unitTyVarSet clas_tyvar
405 tcExtendGlobalTyVars clas_tyvar_set (
408 (makeClassDeclDefaultMethodRhs clas local_defm_ids)
412 ) `thenTc` \ (insts_needed, default_binds') ->
417 insts_needed `thenTc` \ (const_lie, dict_binds) ->
421 defm_binds = AbsBinds
424 (local_defm_ids `zip` map RealId default_method_ids)
426 (RecBind default_binds')
428 returnTc (const_lie, defm_binds)
430 inst_ty = mkTyVarTy clas_tyvar
431 mk_method defm_id = newMethod origin (RealId defm_id) [inst_ty]
432 origin = ClassDeclOrigin
436 buildDefaultMethodBinds
441 -> TcM s (LIE s, TcHsBinds s)
443 buildDefaultMethodBinds clas clas_tyvar
444 default_method_ids default_binds
445 = newDicts origin [(clas,inst_ty)] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
446 tcExtendGlobalTyVars clas_tyvar_set (
447 tcDefaultMethodBinds default_binds
450 tcDefaultMethodBinds default_meth_ids default_binds
452 go (AndMonoBinds b1 b2)
453 = go b1 `thenTc` \ (new_b1, lie1) ->
454 go b2 `thenTc` \ (new_b2, lie2) ->
455 returnTc (new_b1 `ThenBinds` new_b2, lie1 `plusLIE` lie2)
457 go EmptyMonoBinds = EmptyBinds
459 go mbind = processInstBinds1 clas clas_dict meth_ids mbind `thenTc` \ (tags
461 tcDefaultMethodBinds EmptyMonoBinds
467 (makeClassDeclDefaultMethodRhs clas local_defm_ids)
471 ) `thenTc` \ (insts_needed, default_binds') ->
474 mapAndUnzipNF_Tc mk_method default_method_ids `thenNF_Tc` \ (insts_s, local_defm_ids) ->
476 avail_insts = this_dict `plusLIE` unionManyBags insts_s -- Insts available
477 clas_tyvar_set = unitTyVarSet clas_tyvar
483 insts_needed `thenTc` \ (const_lie, dict_binds) ->
487 defm_binds = AbsBinds
490 (local_defm_ids `zip` map RealId default_method_ids)
492 (RecBind default_binds')
494 returnTc (const_lie, defm_binds)
496 inst_ty = mkTyVarTy clas_tyvar
497 mk_method defm_id = newMethod origin (RealId defm_id) [inst_ty]
498 origin = ClassDeclOrigin
501 @makeClassDeclDefaultMethodRhs@ builds the default method for a
502 class declaration when no explicit default method is given.
505 makeClassDeclDefaultMethodRhs
509 -> NF_TcM s (TcExpr s)
511 makeClassDeclDefaultMethodRhs clas method_ids tag
512 = -- Return the expression
513 -- error ty "No default method for ..."
514 -- The interesting thing is that method_ty is a for-all type;
515 -- this is fun, although unusual in a type application!
517 returnNF_Tc (HsApp (mkHsTyApp (HsVar (RealId nO_DEFAULT_METHOD_ERROR_ID)) [tcIdType method_id])
518 (HsLitOut (HsString (_PK_ error_msg)) stringTy))
521 (clas_mod, clas_name) = modAndOcc clas
523 method_id = method_ids !! (tag-1)
524 class_op = (classOps clas) !! (tag-1)
526 error_msg = _UNPK_ (nameString (getName clas))
527 ++ (ppShow 80 (ppr PprForUser class_op))
528 -- ++ "\"" Don't know what this trailing quote is for!
535 classDeclCtxt class_name sty
536 = ppCat [ppPStr SLIT("In the class declaration for"), ppr sty class_name]