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(..), MonoBinds(..),
14 Match(..), GRHSsAndBinds(..), GRHS(..), HsExpr(..),
15 DefaultDecl, TyDecl, InstDecl, IfaceSig, Fixity,
16 HsLit(..), OutPat(..), Sig(..), HsType(..), HsTyVar,
17 SYN_IE(RecFlag), nonRecursive, andMonoBinds,
18 Stmt, DoOrListComp, ArithSeqInfo, InPat, Fake )
19 import HsTypes ( getTyVarName )
20 import HsPragmas ( ClassPragmas(..) )
21 import RnHsSyn ( RenamedClassDecl(..), RenamedClassPragmas(..),
22 RenamedClassOpSig(..), SYN_IE(RenamedMonoBinds),
23 RenamedGenPragmas(..), RenamedContext(..), SYN_IE(RenamedHsDecl)
25 import TcHsSyn ( TcIdOcc(..), SYN_IE(TcHsBinds), SYN_IE(TcMonoBinds), SYN_IE(TcExpr),
26 mkHsTyApp, mkHsTyLam, mkHsDictApp, mkHsDictLam, tcIdType )
28 import Inst ( Inst, InstOrigin(..), SYN_IE(LIE), emptyLIE, plusLIE, newDicts, newMethod )
29 import TcEnv ( tcLookupClass, tcLookupTyVar, tcLookupTyCon, newLocalIds, tcAddImportedIdInfo,
30 tcExtendGlobalTyVars )
31 import TcInstDcls ( tcMethodBind )
32 import TcKind ( unifyKind, TcKind )
34 import TcMonoType ( tcHsType, tcContext )
35 import TcSimplify ( tcSimplifyAndCheck )
36 import TcType ( SYN_IE(TcType), SYN_IE(TcTyVar), tcInstType, tcInstSigTyVars, tcInstSigType )
37 import PragmaInfo ( PragmaInfo(..) )
39 import Bag ( foldBag, unionManyBags )
40 import Class ( GenClass, GenClassOp, mkClass, mkClassOp, classBigSig,
41 classOps, classOpString, classOpLocalType, classDefaultMethodId,
42 classOpTagByOccName, SYN_IE(ClassOp), SYN_IE(Class)
44 import CmdLineOpts ( opt_PprUserLength )
45 import Id ( GenId, mkSuperDictSelId, mkMethodSelId,
46 mkDefaultMethodId, getIdUnfolding,
49 import CoreUnfold ( getUnfoldingTemplate )
51 import Name ( Name, isLocallyDefined, moduleString,
52 nameString, NamedThing(..) )
54 import PrelVals ( nO_DEFAULT_METHOD_ERROR_ID )
56 import PprType ( GenClass, GenType, GenTyVar, GenClassOp )
57 import SpecEnv ( SpecEnv )
58 import SrcLoc ( mkGeneratedSrcLoc )
59 import Type ( mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy,
60 mkForAllTy, mkSigmaTy, splitSigmaTy, SYN_IE(Type)
62 import TysWiredIn ( stringTy )
63 import TyVar ( unitTyVarSet, GenTyVar, SYN_IE(TyVar) )
64 import Unique ( Unique )
65 import UniqFM ( Uniquable(..) )
69 -- import TcPragmas ( tcGenPragmas, tcClassOpPragmas )
70 tcGenPragmas ty id ps = returnNF_Tc noIdInfo
71 tcClassOpPragmas ty sel def spec ps = returnNF_Tc (noIdInfo `addSpecInfo` spec,
79 Every class implicitly declares a new data type, corresponding to dictionaries
80 of that class. So, for example:
82 class (D a) => C a where
84 op2 :: forall b. Ord b => a -> b -> b
86 would implicitly declare
88 data CDict a = CDict (D a)
90 (forall b. Ord b => a -> b -> b)
92 (We could use a record decl, but that means changing more of the existing apparatus.
95 For classes with just one superclass+method, we use a newtype decl instead:
98 op :: forallb. a -> b -> b
102 newtype CDict a = CDict (forall b. a -> b -> b)
104 Now DictTy in Type is just a form of type synomym:
105 DictTy c t = TyConTy CDict `AppTy` t
107 Death to "ExpandingDicts".
111 tcClassDecl1 rec_inst_mapper
112 (ClassDecl context class_name
113 tyvar_name class_sigs def_methods pragmas src_loc)
114 = tcAddSrcLoc src_loc $
115 tcAddErrCtxt (classDeclCtxt class_name) $
117 -- LOOK THINGS UP IN THE ENVIRONMENT
118 tcLookupClass class_name `thenTc` \ (class_kind, rec_class) ->
119 tcLookupTyVar (getTyVarName tyvar_name) `thenNF_Tc` \ (tyvar_kind, rec_tyvar) ->
121 (rec_class_inst_env, rec_class_op_inst_fn) = rec_inst_mapper rec_class
124 -- FORCE THE CLASS AND ITS TYVAR TO HAVE SAME KIND
125 unifyKind class_kind tyvar_kind `thenTc_`
128 tcClassContext rec_class rec_tyvar context pragmas
129 `thenTc` \ (scs, sc_sel_ids) ->
131 -- CHECK THE CLASS SIGNATURES,
132 mapTc (tcClassSig rec_class rec_tyvar rec_class_op_inst_fn) class_sigs
133 `thenTc` \ sig_stuff ->
135 -- MAKE THE CLASS OBJECT ITSELF
137 (ops, op_sel_ids, defm_ids) = unzip3 sig_stuff
138 clas = mkClass (uniqueOf class_name) (getName class_name) rec_tyvar
139 scs sc_sel_ids ops op_sel_ids defm_ids
147 clas_ty = mkTyVarTy clas_tyvar
148 dict_component_tys = [mkDictTy sc clas_ty | sc <- scs] ++
149 [classOpLocalType op | op <- ops])
150 new_or_data = case dict_component_tys of
154 dict_con_id = mkDataCon class_name
156 [{- No labelled fields -}]
162 tycon = mkDataTyCon class_name
163 (tyVarKind rec_tyvar `mkArrowKind` mkBoxedTypeKind)
165 [{- Empty context -}]
167 [{- No derived classes -}]
173 tcClassContext :: Class -> TyVar
174 -> RenamedContext -- class context
175 -> RenamedClassPragmas -- pragmas for superclasses
176 -> TcM s ([Class], -- the superclasses
177 [Id]) -- superclass selector Ids
179 tcClassContext rec_class rec_tyvar context pragmas
180 = -- Check the context.
181 -- The renamer has already checked that the context mentions
182 -- only the type variable of the class decl.
183 tcContext context `thenTc` \ theta ->
185 super_classes = [ supers | (supers, _) <- theta ]
188 -- Make super-class selector ids
189 mapTc (mk_super_id rec_class) super_classes `thenTc` \ sc_sel_ids ->
192 returnTc (super_classes, sc_sel_ids)
195 rec_tyvar_ty = mkTyVarTy rec_tyvar
197 mk_super_id rec_class super_class
198 = tcGetUnique `thenNF_Tc` \ uniq ->
200 ty = mkForAllTy rec_tyvar $
201 mkFunTy (mkDictTy rec_class rec_tyvar_ty)
202 (mkDictTy super_class rec_tyvar_ty)
204 returnTc (mkSuperDictSelId uniq rec_class super_class ty)
207 tcClassSig :: Class -- Knot tying only!
208 -> TyVar -- The class type variable, used for error check only
209 -> (ClassOp -> SpecEnv) -- Ditto; the spec info for the class ops
211 -> TcM s (ClassOp, -- class op
213 Id) -- default-method ids
215 tcClassSig rec_clas rec_clas_tyvar rec_classop_spec_fn
216 (ClassOpSig op_name dm_name
219 = tcAddSrcLoc src_loc $
220 fixTc ( \ ~(_, rec_sel_id, rec_defm_id) -> -- Knot for pragmas
222 -- Check the type signature. NB that the envt *already has*
223 -- bindings for the type variables; see comments in TcTyAndClassDcls.
225 -- NB: Renamer checks that the class type variable is mentioned in local_ty,
226 -- and that it is not constrained by theta
227 tcHsType op_ty `thenTc` \ local_ty ->
229 global_ty = mkSigmaTy [rec_clas_tyvar]
230 [(rec_clas, mkTyVarTy rec_clas_tyvar)]
232 class_op_nm = getOccName op_name
233 class_op = mkClassOp class_op_nm
234 (classOpTagByOccName rec_clas{-yeeps!-} class_op_nm)
238 -- Build the selector id and default method id
240 sel_id = mkMethodSelId op_name rec_clas class_op global_ty
241 defm_id = mkDefaultMethodId dm_name rec_clas class_op False global_ty
242 -- ToDo: improve the "False"
244 tcAddImportedIdInfo defm_id `thenNF_Tc` \ final_defm_id ->
245 returnTc (class_op, sel_id, final_defm_id)
250 %************************************************************************
252 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
254 %************************************************************************
256 The purpose of pass 2 is
259 to beat on the explicitly-provided default-method decls (if any),
260 using them to produce a complete set of default-method decls.
261 (Omitted ones elicit an error message.)
263 to produce a definition for the selector function for each method
264 and superclass dictionary.
267 Pass~2 only applies to locally-defined class declarations.
269 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
270 each local class decl.
273 tcClassDecls2 :: [RenamedHsDecl]
274 -> NF_TcM s (LIE s, TcHsBinds s)
278 (returnNF_Tc (emptyLIE, EmptyBinds))
279 [tcClassDecl2 cls_decl | ClD cls_decl <- decls]
281 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
282 tc2 `thenNF_Tc` \ (lie2, binds2) ->
283 returnNF_Tc (lie1 `plusLIE` lie2,
284 binds1 `ThenBinds` binds2)
287 @tcClassDecl2@ is the business end of things.
290 tcClassDecl2 :: RenamedClassDecl -- The class declaration
291 -> NF_TcM s (LIE s, TcHsBinds s)
293 tcClassDecl2 (ClassDecl context class_name
294 tyvar_name class_sigs default_binds pragmas src_loc)
296 | not (isLocallyDefined class_name)
297 = returnNF_Tc (emptyLIE, EmptyBinds)
299 | otherwise -- It is locally defined
300 = recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyBinds)) $
301 tcAddSrcLoc src_loc $
303 -- Get the relevant class
304 tcLookupClass class_name `thenTc` \ (_, clas) ->
306 (tyvar, scs, sc_sel_ids, ops, op_sel_ids, defm_ids)
309 -- The selector binds are already in the selector Id's unfoldings
310 sel_binds = [ CoreMonoBind (RealId sel_id) (getUnfoldingTemplate (getIdUnfolding sel_id))
311 | sel_id <- sc_sel_ids ++ op_sel_ids,
312 isLocallyDefined sel_id
315 final_sel_binds = MonoBind (andMonoBinds sel_binds) [] nonRecursive
317 -- Generate bindings for the default methods
318 tcInstSigTyVars [tyvar] `thenNF_Tc` \ ([clas_tyvar], _, _) ->
319 mapAndUnzipTc (buildDefaultMethodBind clas clas_tyvar default_binds)
320 (op_sel_ids `zip` [0..])
321 `thenTc` \ (const_insts_s, meth_binds) ->
323 returnTc (unionManyBags const_insts_s,
324 final_sel_binds `ThenBinds`
325 MonoBind (andMonoBinds meth_binds) [] nonRecursive)
328 %************************************************************************
330 \subsection[Default methods]{Default methods}
332 %************************************************************************
334 The default methods for a class are each passed a dictionary for the
335 class, so that they get access to the other methods at the same type.
336 So, given the class decl
340 op2 :: Ord b => a -> b -> b -> b
343 op2 x y z = if (op1 x) && (y < z) then y else z
345 we get the default methods:
347 defm.Foo.op1 :: forall a. Foo a => a -> Bool
348 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
350 ====================== OLD ==================
352 defm.Foo.op2 :: forall a, b. (Foo a, Ord b) => a -> b -> b -> b
353 defm.Foo.op2 = /\ a b -> \ dfoo dord -> \x y z ->
354 if (op1 a dfoo x) && (< b dord y z) then y else z
356 Notice that, like all ids, the foralls of defm.Foo.op2 are at the top.
357 ====================== END OF OLD ===================
361 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
362 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
363 if (op1 a dfoo x) && (< b dord y z) then y else z
367 When we come across an instance decl, we may need to use the default
370 instance Foo Int where {}
374 const.Foo.Int.op1 :: Int -> Bool
375 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
377 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
378 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
380 dfun.Foo.Int :: Foo Int
381 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
383 Notice that, as with method selectors above, we assume that dictionary
384 application is curried, so there's no need to mention the Ord dictionary
385 in const.Foo.Int.op2 (or the type variable).
388 instance Foo a => Foo [a] where {}
390 dfun.Foo.List :: forall a. Foo a -> Foo [a]
392 = /\ a -> \ dfoo_a ->
394 op1 = defm.Foo.op1 [a] dfoo_list
395 op2 = defm.Foo.op2 [a] dfoo_list
396 dfoo_list = (op1, op2)
402 buildDefaultMethodBind
407 -> TcM s (LIE s, TcMonoBinds s)
409 buildDefaultMethodBind clas clas_tyvar default_binds (sel_id, idx)
410 = newDicts origin [(clas,inst_ty)] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
412 avail_insts = this_dict
413 defm_id = classDefaultMethodId clas idx
414 no_prags name = NoPragmaInfo -- No pragmas yet for default methods
416 tcExtendGlobalTyVars clas_tyvar_set (
417 tcMethodBind noDefmExpr inst_ty no_prags default_binds (sel_id, idx)
418 ) `thenTc` \ (defm_bind, insts_needed, (_, local_defm_id)) ->
420 -- CHECK THE CONTEXT OF THE DEFAULT-METHOD BINDS
424 insts_needed `thenTc` \ (const_lie, dict_binds) ->
427 defm_binds = AbsBinds
430 [([clas_tyvar], RealId defm_id, local_defm_id)]
431 (dict_binds `AndMonoBinds` defm_bind)
433 returnTc (const_lie, defm_binds)
436 clas_tyvar_set = unitTyVarSet clas_tyvar
437 inst_ty = mkTyVarTy clas_tyvar
438 origin = ClassDeclOrigin
439 noDefmExpr _ = HsApp (HsVar (getName nO_DEFAULT_METHOD_ERROR_ID))
440 (HsLit (HsString (_PK_ error_msg)))
442 error_msg = show (sep [text "Class", ppr (PprForUser opt_PprUserLength) clas,
443 text "Method", ppr (PprForUser opt_PprUserLength) sel_id])
451 classDeclCtxt class_name sty
452 = hsep [ptext SLIT("In the class declaration for"), ppr sty class_name]