2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1995
4 \section[TcClassDcl]{Typechecking class declarations}
7 #include "HsVersions.h"
10 tcClassDecl1, tcClassDecls2
15 import HsSyn ( ClassDecl(..), HsBinds(..), Bind(..), MonoBinds(..),
16 Match(..), GRHSsAndBinds(..), GRHS(..), HsExpr(..),
17 HsLit(..), OutPat(..), Sig(..), PolyType(..), MonoType,
18 Stmt, Qual, ArithSeqInfo, InPat, Fake )
19 import HsPragmas ( ClassPragmas(..) )
20 import RnHsSyn ( RenamedClassDecl(..), RenamedClassPragmas(..),
21 RenamedClassOpSig(..), RenamedMonoBinds(..),
22 RenamedGenPragmas(..), RenamedContext(..),
23 RnName{-instance Uniquable-}
25 import TcHsSyn ( TcIdOcc(..), TcHsBinds(..), TcMonoBinds(..), TcExpr(..),
26 mkHsTyApp, mkHsTyLam, mkHsDictApp, mkHsDictLam )
28 import TcMonad hiding ( rnMtoTcM )
29 import Inst ( Inst, InstOrigin(..), LIE(..), emptyLIE, plusLIE, newDicts )
30 import TcEnv ( tcLookupClass, tcLookupTyVar, tcLookupTyCon, newLocalIds)
31 import TcInstDcls ( processInstBinds )
32 import TcKind ( unifyKind )
33 import TcMonoType ( tcMonoType, tcContext )
34 import TcType ( TcType(..), TcTyVar(..), tcInstType, tcInstSigTyVars )
35 import TcKind ( TcKind )
37 import Bag ( foldBag )
38 import Class ( GenClass, mkClass, mkClassOp, classBigSig,
39 classOps, classOpString, classOpLocalType,
42 import Id ( mkSuperDictSelId, mkMethodSelId, mkDefaultMethodId,
44 import IdInfo ( noIdInfo )
45 import Name ( isLocallyDefined, moduleNamePair, getLocalName )
46 import PrelVals ( nO_DEFAULT_METHOD_ERROR_ID )
49 import PprType ( GenType, GenTyVar, GenClassOp )
50 import SpecEnv ( SpecEnv(..) )
51 import SrcLoc ( mkGeneratedSrcLoc )
52 import Type ( mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy,
53 mkForAllTy, mkSigmaTy, splitSigmaTy)
54 import TysWiredIn ( stringTy )
55 import TyVar ( GenTyVar )
56 import Unique ( Unique )
59 -- import TcPragmas ( tcGenPragmas, tcClassOpPragmas )
60 tcGenPragmas ty id ps = returnNF_Tc noIdInfo
61 tcClassOpPragmas ty sel def spec ps = returnNF_Tc (noIdInfo, noIdInfo)
66 tcClassDecl1 rec_inst_mapper
67 (ClassDecl context class_name
68 tyvar_name class_sigs def_methods pragmas src_loc)
69 = tcAddSrcLoc src_loc $
70 tcAddErrCtxt (classDeclCtxt class_name) $
72 -- LOOK THINGS UP IN THE ENVIRONMENT
73 tcLookupClass class_name `thenNF_Tc` \ (class_kind, rec_class) ->
74 tcLookupTyVar tyvar_name `thenNF_Tc` \ (tyvar_kind, rec_tyvar) ->
76 (rec_class_inst_env, rec_class_op_inst_fn) = rec_inst_mapper rec_class
79 -- FORCE THE CLASS AND ITS TYVAR TO HAVE SAME KIND
80 unifyKind class_kind tyvar_kind `thenTc_`
83 tcClassContext rec_class rec_tyvar context pragmas
84 `thenTc` \ (scs, sc_sel_ids) ->
86 -- CHECK THE CLASS SIGNATURES,
87 mapTc (tcClassSig rec_class rec_tyvar rec_class_op_inst_fn) class_sigs
88 `thenTc` \ sig_stuff ->
90 -- MAKE THE CLASS OBJECT ITSELF
92 -- tcGetUnique `thenNF_Tc` \ uniq ->
94 (ops, op_sel_ids, defm_ids) = unzip3 sig_stuff
95 clas = mkClass (uniqueOf class_name) (getName class_name) rec_tyvar
96 scs sc_sel_ids ops op_sel_ids defm_ids
104 tcClassContext :: Class -> TyVar
105 -> RenamedContext -- class context
106 -> RenamedClassPragmas -- pragmas for superclasses
107 -> TcM s ([Class], -- the superclasses
108 [Id]) -- superclass selector Ids
110 tcClassContext rec_class rec_tyvar context pragmas
111 = -- Check the context.
112 -- The renamer has already checked that the context mentions
113 -- only the type variable of the class decl.
114 tcContext context `thenTc` \ theta ->
116 super_classes = [ supers | (supers, _) <- theta ]
119 -- Make super-class selector ids
120 mapTc (mk_super_id rec_class)
121 (super_classes `zip` maybe_pragmas) `thenTc` \ sc_sel_ids ->
122 -- NB: we worry about matching list lengths below
125 returnTc (super_classes, sc_sel_ids)
128 mk_super_id rec_class (super_class, maybe_pragma)
129 = fixTc ( \ rec_super_id ->
130 tcGetUnique `thenNF_Tc` \ uniq ->
132 -- GET THE PRAGMA INFO FOR THE SUPERCLASS
133 (case maybe_pragma of
134 Nothing -> returnNF_Tc noIdInfo
135 Just prag -> tcGenPragmas Nothing{-ty unknown-} rec_super_id prag
136 ) `thenNF_Tc` \ id_info ->
138 ty = mkForAllTy rec_tyvar (
139 mkFunTy (mkDictTy rec_class (mkTyVarTy rec_tyvar))
140 (mkDictTy super_class (mkTyVarTy rec_tyvar))
143 -- BUILD THE SUPERCLASS ID
144 returnTc (mkSuperDictSelId uniq rec_class super_class ty id_info)
147 maybe_pragmas :: [Maybe RenamedGenPragmas]
148 maybe_pragmas = case pragmas of
149 NoClassPragmas -> repeat Nothing
150 SuperDictPragmas prags -> ASSERT(length prags == length context)
152 -- If there are any pragmas there should
153 -- be one for each superclass
157 tcClassSig :: Class -- Knot tying only!
158 -> TyVar -- The class type variable, used for error check only
159 -> (ClassOp -> SpecEnv) -- Ditto; the spec info for the class ops
161 -> TcM s (ClassOp, -- class op
163 Id) -- default-method ids
165 tcClassSig rec_clas rec_clas_tyvar rec_classop_spec_fn
167 (HsForAllTy tyvar_names context monotype)
169 = tcAddSrcLoc src_loc $
170 fixTc ( \ ~(_, rec_sel_id, rec_defm_id) -> -- Knot for pragmas
172 -- Check the type signature. NB that the envt *already has*
173 -- bindings for the type variables; see comments in TcTyAndClassDcls.
174 tcContext context `thenTc` \ theta ->
175 tcMonoType monotype `thenTc` \ tau ->
176 mapAndUnzipNF_Tc tcLookupTyVar tyvar_names `thenNF_Tc` \ (_,tyvars) ->
178 full_tyvars = rec_clas_tyvar : tyvars
179 full_theta = (rec_clas, mkTyVarTy rec_clas_tyvar) : theta
180 global_ty = mkSigmaTy full_tyvars full_theta tau
181 local_ty = mkSigmaTy tyvars theta tau
182 class_op_nm = getLocalName op_name
183 class_op = mkClassOp class_op_nm
184 (classOpTagByString rec_clas{-yeeps!-} class_op_nm)
191 rec_sel_id rec_defm_id
192 (rec_classop_spec_fn class_op)
193 pragmas `thenNF_Tc` \ (op_info, defm_info) ->
195 -- Build the selector id and default method id
196 tcGetUnique `thenNF_Tc` \ d_uniq ->
198 op_uniq = uniqueOf op_name
199 sel_id = mkMethodSelId op_uniq rec_clas class_op global_ty op_info
200 defm_id = mkDefaultMethodId d_uniq rec_clas class_op False global_ty defm_info
201 -- ToDo: improve the "False"
203 returnTc (class_op, sel_id, defm_id)
208 %************************************************************************
210 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
212 %************************************************************************
214 The purpose of pass 2 is
217 to beat on the explicitly-provided default-method decls (if any),
218 using them to produce a complete set of default-method decls.
219 (Omitted ones elicit an error message.)
221 to produce a definition for the selector function for each method
222 and superclass dictionary.
225 Pass~2 only applies to locally-defined class declarations.
227 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
228 each local class decl.
231 tcClassDecls2 :: Bag RenamedClassDecl
232 -> NF_TcM s (LIE s, TcHsBinds s)
237 (returnNF_Tc (emptyLIE, EmptyBinds))
240 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
241 tc2 `thenNF_Tc` \ (lie2, binds2) ->
242 returnNF_Tc (lie1 `plusLIE` lie2,
243 binds1 `ThenBinds` binds2)
246 @tcClassDecl2@ is the business end of things.
249 tcClassDecl2 :: RenamedClassDecl -- The class declaration
250 -> NF_TcM s (LIE s, TcHsBinds s)
252 tcClassDecl2 (ClassDecl context class_name
253 tyvar_name class_sigs default_binds pragmas src_loc)
255 | not (isLocallyDefined class_name)
256 = returnNF_Tc (emptyLIE, EmptyBinds)
258 | otherwise -- It is locally defined
259 = recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyBinds)) $
260 tcAddSrcLoc src_loc $
262 -- Get the relevant class
263 tcLookupClass class_name `thenNF_Tc` \ (_, clas) ->
265 (tyvar, scs, sc_sel_ids, ops, op_sel_ids, defm_ids)
268 tcInstSigTyVars [tyvar] `thenNF_Tc` \ ([clas_tyvar], _, _) ->
270 -- Generate bindings for the selector functions
271 buildSelectors clas tyvar clas_tyvar scs sc_sel_ids ops op_sel_ids
272 `thenNF_Tc` \ sel_binds ->
273 -- Ditto for the methods
274 buildDefaultMethodBinds clas clas_tyvar defm_ids default_binds
275 `thenTc` \ (const_insts, meth_binds) ->
277 returnTc (const_insts, sel_binds `ThenBinds` meth_binds)
280 %************************************************************************
282 \subsection[ClassDcl-bld-sels]{Building the selector functions for methods and superclasses}
284 %************************************************************************
287 buildSelectors :: Class -- The class object
288 -> TyVar -- Class type variable
289 -> TcTyVar s -- Instantiated class type variable (TyVarTy)
290 -> [Class] -> [Id] -- Superclasses and selectors
291 -> [ClassOp] -> [Id] -- Class ops and selectors
292 -> NF_TcM s (TcHsBinds s)
294 buildSelectors clas clas_tyvar clas_tc_tyvar scs sc_sel_ids ops op_sel_ids
296 -- Make new Ids for the components of the dictionary
298 clas_tyvar_ty = mkTyVarTy clas_tc_tyvar
299 mk_op_ty = tcInstType [(clas_tyvar, clas_tyvar_ty)] . classOpLocalType
301 mapNF_Tc mk_op_ty ops `thenNF_Tc` \ op_tys ->
302 newLocalIds (map classOpString ops) op_tys `thenNF_Tc` \ method_ids ->
304 newDicts ClassDeclOrigin
305 [ (super_clas, clas_tyvar_ty)
306 | super_clas <- scs ] `thenNF_Tc` \ (_,dict_ids) ->
308 newDicts ClassDeclOrigin
309 [ (clas, clas_tyvar_ty) ] `thenNF_Tc` \ (_,[clas_dict]) ->
311 -- Make suitable bindings for the selectors
313 mk_sel sel_id method_or_dict
314 = mkSelBind sel_id clas_tc_tyvar clas_dict dict_ids method_ids method_or_dict
316 listNF_Tc (zipWithEqual "mk_sel1" mk_sel op_sel_ids method_ids) `thenNF_Tc` \ op_sel_binds ->
317 listNF_Tc (zipWithEqual "mk_sel2" mk_sel sc_sel_ids dict_ids) `thenNF_Tc` \ sc_sel_binds ->
319 returnNF_Tc (SingleBind (
322 (foldr AndMonoBinds EmptyMonoBinds op_sel_binds)
327 %************************************************************************
329 \subsection[ClassDcl-misc]{Miscellaneous}
331 %************************************************************************
333 Make a selector expression for @sel_id@ from a dictionary @clas_dict@
334 consisting of @dicts@ and @methods@.
336 We have to do a bit of jiggery pokery to get the type variables right.
337 Suppose we have the class decl:
340 op1 :: Ord b => a -> b -> a
343 Then the method selector for \tr{op1} is like this:
345 op1_sel = /\a b -> \dFoo dOrd -> case dFoo of
346 (op1_method,op2_method) -> op1_method b dOrd
348 Note that the type variable for \tr{b} and the (Ord b) dictionary
349 are lifted to the top lambda, and
350 \tr{op1_method} is applied to them. This is preferable to the alternative:
352 op1_sel' = /\a -> \dFoo -> case dFoo of
353 (op1_method,op2_method) -> op1_method
355 because \tr{op1_sel'} then has the rather strange type
357 op1_sel' :: forall a. Foo a -> forall b. Ord b -> a -> b -> a
359 whereas \tr{op1_sel} (the one we use) has the decent type
361 op1_sel :: forall a b. Foo a -> Ord b -> a -> b -> a
364 NOTE that we return a TcMonoBinds (which is later zonked) even though
365 there's no real back-substitution to do. It's just simpler this way!
367 NOTE ALSO that the selector has no free type variables, so we
368 don't bother to instantiate the class-op's local type; instead
369 we just use the variables inside it.
372 mkSelBind :: Id -- the selector id
373 -> TcTyVar s -> TcIdOcc s -- class tyvar and dict
374 -> [TcIdOcc s] -> [TcIdOcc s] -- superclasses and methods in class dict
375 -> TcIdOcc s -- the superclass/method being slected
376 -> NF_TcM s (TcMonoBinds s)
378 mkSelBind sel_id clas_tyvar clas_dict dicts methods method_or_dict@(TcId op)
380 (op_tyvars,op_theta,op_tau) = splitSigmaTy (idType op)
381 op_tys = mkTyVarTys op_tyvars
383 newDicts ClassDeclOrigin op_theta `thenNF_Tc` \ (_, op_dicts) ->
385 -- sel_id = /\ clas_tyvar op_tyvars -> \ clas_dict op_dicts ->
387 -- <dicts..methods> -> method_or_dict op_tyvars op_dicts
389 returnNF_Tc (VarMonoBind (RealId sel_id) (
390 TyLam (clas_tyvar:op_tyvars) (
391 DictLam (clas_dict:op_dicts) (
394 ([PatMatch (DictPat dicts methods) (
395 GRHSMatch (GRHSsAndBindsOut
397 (mkHsDictApp (mkHsTyApp (HsVar method_or_dict) op_tys) op_dicts)
406 %************************************************************************
408 \subsection[Default methods]{Default methods}
410 %************************************************************************
412 The default methods for a class are each passed a dictionary for the
413 class, so that they get access to the other methods at the same type.
414 So, given the class decl
418 op2 :: Ord b => a -> b -> b -> b
421 op2 x y z = if (op1 x) && (y < z) then y else z
423 we get the default methods:
425 defm.Foo.op1 :: forall a. Foo a => a -> Bool
426 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
428 defm.Foo.op2 :: forall a, b. (Foo a, Ord b) => a -> b -> b -> b
429 defm.Foo.op2 = /\ a b -> \ dfoo dord -> \x y z ->
430 if (op1 a dfoo x) && (< b dord y z) then y else z
432 Notice that, like all ids, the foralls of defm.Foo.op2 are at the top.
434 When we come across an instance decl, we may need to use the default
437 instance Foo Int where {}
441 const.Foo.Int.op1 :: Int -> Bool
442 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
444 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
445 const.Foo.Int.op2 = /\b -> defm.Foo.op2 Int b dfun.Foo.Int
447 dfun.Foo.Int :: Foo Int
448 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
450 Notice that, as with method selectors above, we assume that dictionary
451 application is curried, so there's no need to mention the Ord dictionary
454 instance Foo a => Foo [a] where {}
456 dfun.Foo.List :: forall a. Foo a -> Foo [a]
458 = /\ a -> \ dfoo_a ->
460 op1 = defm.Foo.op1 [a] dfoo_list
461 op2 = /\b -> \dord -> defm.Foo.op2 [a] b dfoo_list dord
462 dfoo_list = (op1, op2)
468 buildDefaultMethodBinds
473 -> TcM s (LIE s, TcHsBinds s)
475 buildDefaultMethodBinds clas clas_tyvar
476 default_method_ids default_binds
477 = -- Deal with the method declarations themselves
480 (makeClassDeclDefaultMethodRhs clas default_method_ids)
481 [] -- No tyvars in scope for "this inst decl"
482 emptyLIE -- No insts available
483 (map RealId default_method_ids)
484 default_binds `thenTc` \ (dicts_needed, default_binds') ->
486 returnTc (dicts_needed, SingleBind (NonRecBind default_binds'))
489 @makeClassDeclDefaultMethodRhs@ builds the default method for a
490 class declaration when no explicit default method is given.
493 makeClassDeclDefaultMethodRhs
497 -> NF_TcM s (TcExpr s)
499 makeClassDeclDefaultMethodRhs clas method_ids tag
500 = tcInstType [] (idType method_id) `thenNF_Tc` \ method_ty ->
502 (tyvars, theta, tau) = splitSigmaTy method_ty
504 newDicts ClassDeclOrigin theta `thenNF_Tc` \ (lie, dict_ids) ->
506 returnNF_Tc (mkHsTyLam tyvars (
507 mkHsDictLam dict_ids (
508 HsApp (mkHsTyApp (HsVar (RealId nO_DEFAULT_METHOD_ERROR_ID)) [tau])
509 (HsLitOut (HsString (_PK_ error_msg)) stringTy))))
511 (clas_mod, clas_name) = moduleNamePair clas
513 method_id = method_ids !! (tag-1)
514 class_op = (classOps clas) !! (tag-1)
516 error_msg = _UNPK_ clas_mod ++ "." ++ _UNPK_ clas_name ++ "."
517 ++ (ppShow 80 (ppr PprForUser class_op))
525 classDeclCtxt class_name sty
526 = ppCat [ppStr "In the class declaration for", ppr sty class_name]