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 import TcHsSyn ( TcIdOcc(..), TcHsBinds(..), TcMonoBinds(..), TcExpr(..),
24 mkHsTyApp, mkHsTyLam, mkHsDictApp, mkHsDictLam, unZonkId )
27 import Inst ( Inst, InstOrigin(..), LIE(..), emptyLIE, plusLIE, newDicts )
28 import TcEnv ( tcLookupClass, tcLookupTyVar, tcLookupTyCon, newLocalIds)
29 import TcInstDcls ( processInstBinds )
30 import TcKind ( unifyKind )
31 import TcMonoType ( tcMonoType, tcContext )
32 import TcType ( TcType(..), TcTyVar(..), tcInstType, tcInstSigTyVars )
33 import TcKind ( TcKind )
35 import Bag ( foldBag )
36 import Class ( GenClass, mkClass, mkClassOp, getClassBigSig,
37 getClassOps, getClassOpString, getClassOpLocalType )
38 import CoreUtils ( escErrorMsg )
39 import Id ( mkSuperDictSelId, mkMethodSelId, mkDefaultMethodId,
41 import IdInfo ( noIdInfo )
42 import Name ( Name, getNameFullName, getTagFromClassOpName )
43 import PrelVals ( pAT_ERROR_ID )
46 import PprType ( GenType, GenTyVar, GenClassOp )
47 import SpecEnv ( SpecEnv(..) )
48 import SrcLoc ( mkGeneratedSrcLoc )
49 import Type ( mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy,
50 mkForAllTy, mkSigmaTy, splitSigmaTy)
51 import TysWiredIn ( stringTy )
52 import TyVar ( GenTyVar )
53 import Unique ( Unique )
56 -- import TcPragmas ( tcGenPragmas, tcClassOpPragmas )
57 tcGenPragmas ty id ps = returnNF_Tc noIdInfo
58 tcClassOpPragmas ty sel def spec ps = returnNF_Tc (noIdInfo, noIdInfo)
63 tcClassDecl1 rec_inst_mapper
64 (ClassDecl context class_name
65 tyvar_name class_sigs def_methods pragmas src_loc)
66 = tcAddSrcLoc src_loc $
67 tcAddErrCtxt (classDeclCtxt class_name) $
69 -- LOOK THINGS UP IN THE ENVIRONMENT
70 tcLookupClass class_name `thenNF_Tc` \ (class_kind, rec_class) ->
71 tcLookupTyVar tyvar_name `thenNF_Tc` \ (tyvar_kind, rec_tyvar) ->
73 (rec_class_inst_env, rec_class_op_inst_fn) = rec_inst_mapper rec_class
76 -- FORCE THE CLASS AND ITS TYVAR TO HAVE SAME KIND
77 unifyKind class_kind tyvar_kind `thenTc_`
80 tcClassContext rec_class rec_tyvar context pragmas
81 `thenTc` \ (scs, sc_sel_ids) ->
83 -- CHECK THE CLASS SIGNATURES,
84 mapTc (tcClassSig rec_class rec_tyvar rec_class_op_inst_fn) class_sigs
85 `thenTc` \ sig_stuff ->
87 -- MAKE THE CLASS OBJECT ITSELF
88 tcGetUnique `thenNF_Tc` \ uniq ->
90 (ops, op_sel_ids, defm_ids) = unzip3 sig_stuff
91 clas = mkClass uniq (getNameFullName class_name) rec_tyvar
92 scs sc_sel_ids ops op_sel_ids defm_ids
100 tcClassContext :: Class -> TyVar
101 -> RenamedContext -- class context
102 -> RenamedClassPragmas -- pragmas for superclasses
103 -> TcM s ([Class], -- the superclasses
104 [Id]) -- superclass selector Ids
106 tcClassContext rec_class rec_tyvar context pragmas
107 = -- Check the context.
108 -- The renamer has already checked that the context mentions
109 -- only the type variable of the class decl.
110 tcContext context `thenTc` \ theta ->
112 super_classes = [ supers | (supers, _) <- theta ]
115 -- Make super-class selector ids
116 mapTc (mk_super_id rec_class)
117 (super_classes `zip` maybe_pragmas) `thenTc` \ sc_sel_ids ->
120 returnTc (super_classes, sc_sel_ids)
123 mk_super_id rec_class (super_class, maybe_pragma)
124 = fixTc ( \ rec_super_id ->
125 tcGetUnique `thenNF_Tc` \ uniq ->
127 -- GET THE PRAGMA INFO FOR THE SUPERCLASS
128 (case maybe_pragma of
129 Nothing -> returnNF_Tc noIdInfo
130 Just prag -> tcGenPragmas Nothing{-ty unknown-} rec_super_id prag
131 ) `thenNF_Tc` \ id_info ->
133 ty = mkForAllTy rec_tyvar (
134 mkFunTy (mkDictTy rec_class (mkTyVarTy rec_tyvar))
135 (mkDictTy super_class (mkTyVarTy rec_tyvar))
138 -- BUILD THE SUPERCLASS ID
139 returnTc (mkSuperDictSelId uniq rec_class super_class ty id_info)
142 maybe_pragmas :: [Maybe RenamedGenPragmas]
143 maybe_pragmas = case pragmas of
144 NoClassPragmas -> repeat Nothing
145 SuperDictPragmas prags -> ASSERT(length prags == length context)
147 -- If there are any pragmas there should
148 -- be one for each superclass
152 tcClassSig :: Class -- Knot tying only!
153 -> TyVar -- The class type variable, used for error check only
154 -> (ClassOp -> SpecEnv) -- Ditto; the spec info for the class ops
156 -> TcM s (ClassOp, -- class op
158 Id) -- default-method ids
160 tcClassSig rec_clas rec_clas_tyvar rec_classop_spec_fn
162 (HsForAllTy tyvar_names context monotype)
164 = tcAddSrcLoc src_loc $
165 fixTc ( \ ~(_, rec_sel_id, rec_defm_id) -> -- Knot for pragmas
167 -- Check the type signature. NB that the envt *already has*
168 -- bindings for the type variables; see comments in TcTyAndClassDcls.
169 tcContext context `thenTc` \ theta ->
170 tcMonoType monotype `thenTc` \ tau ->
171 mapAndUnzipNF_Tc tcLookupTyVar tyvar_names `thenNF_Tc` \ (_,tyvars) ->
173 full_tyvars = rec_clas_tyvar : tyvars
174 full_theta = (rec_clas, mkTyVarTy rec_clas_tyvar) : theta
175 global_ty = mkSigmaTy full_tyvars full_theta tau
176 local_ty = mkSigmaTy tyvars theta tau
177 class_op = mkClassOp (getOccurrenceName op_name)
178 (getTagFromClassOpName op_name)
185 rec_sel_id rec_defm_id
186 (rec_classop_spec_fn class_op)
187 pragmas `thenNF_Tc` \ (op_info, defm_info) ->
189 -- Build the selector id and default method id
190 tcGetUnique `thenNF_Tc` \ d_uniq ->
192 op_uniq = getItsUnique op_name
193 sel_id = mkMethodSelId op_uniq rec_clas class_op global_ty op_info
194 defm_id = mkDefaultMethodId d_uniq rec_clas class_op False global_ty defm_info
195 -- ToDo: improve the "False"
197 returnTc (class_op, sel_id, defm_id)
202 %************************************************************************
204 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
206 %************************************************************************
208 The purpose of pass 2 is
211 to beat on the explicitly-provided default-method decls (if any),
212 using them to produce a complete set of default-method decls.
213 (Omitted ones elicit an error message.)
215 to produce a definition for the selector function for each method
216 and superclass dictionary.
219 Pass~2 only applies to locally-defined class declarations.
221 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
222 each local class decl.
225 tcClassDecls2 :: Bag RenamedClassDecl
226 -> NF_TcM s (LIE s, TcHsBinds s)
231 (returnNF_Tc (emptyLIE, EmptyBinds))
234 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
235 tc2 `thenNF_Tc` \ (lie2, binds2) ->
236 returnNF_Tc (lie1 `plusLIE` lie2,
237 binds1 `ThenBinds` binds2)
240 @tcClassDecl2@ is the business end of things.
243 tcClassDecl2 :: RenamedClassDecl -- The class declaration
244 -> NF_TcM s (LIE s, TcHsBinds s)
246 tcClassDecl2 (ClassDecl context class_name
247 tyvar_name class_sigs default_binds pragmas src_loc)
249 | not (isLocallyDefined class_name)
250 = returnNF_Tc (emptyLIE, EmptyBinds)
252 | otherwise -- It is locally defined
253 = recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyBinds)) $
254 tcAddSrcLoc src_loc $
256 -- Get the relevant class
257 tcLookupClass class_name `thenNF_Tc` \ (_, clas) ->
259 (tyvar, scs, sc_sel_ids, ops, op_sel_ids, defm_ids)
260 = getClassBigSig clas
262 tcInstSigTyVars [tyvar] `thenNF_Tc` \ ([clas_tyvar], _, _) ->
264 -- Generate bindings for the selector functions
265 buildSelectors clas tyvar clas_tyvar scs sc_sel_ids ops op_sel_ids
266 `thenNF_Tc` \ sel_binds ->
267 -- Ditto for the methods
268 buildDefaultMethodBinds clas clas_tyvar defm_ids default_binds
269 `thenTc` \ (const_insts, meth_binds) ->
271 returnTc (const_insts, sel_binds `ThenBinds` meth_binds)
274 %************************************************************************
276 \subsection[ClassDcl-bld-sels]{Building the selector functions for methods and superclasses}
278 %************************************************************************
281 buildSelectors :: Class -- The class object
282 -> TyVar -- Class type variable
283 -> TcTyVar s -- Instantiated class type variable (TyVarTy)
284 -> [Class] -> [Id] -- Superclasses and selectors
285 -> [ClassOp] -> [Id] -- Class ops and selectors
286 -> NF_TcM s (TcHsBinds s)
288 buildSelectors clas clas_tyvar clas_tc_tyvar scs sc_sel_ids ops op_sel_ids
290 -- Make new Ids for the components of the dictionary
292 clas_tyvar_ty = mkTyVarTy clas_tc_tyvar
293 mk_op_ty = tcInstType [(clas_tyvar, clas_tyvar_ty)] . getClassOpLocalType
295 mapNF_Tc mk_op_ty ops `thenNF_Tc` \ op_tys ->
296 newLocalIds (map getClassOpString ops) op_tys `thenNF_Tc` \ method_ids ->
298 newDicts ClassDeclOrigin
299 [ (super_clas, clas_tyvar_ty)
300 | super_clas <- scs ] `thenNF_Tc` \ (_,dict_ids) ->
302 newDicts ClassDeclOrigin
303 [ (clas, clas_tyvar_ty) ] `thenNF_Tc` \ (_,[clas_dict]) ->
305 -- Make suitable bindings for the selectors
307 mk_sel sel_id method_or_dict
308 = mkSelBind sel_id clas_tc_tyvar clas_dict dict_ids method_ids method_or_dict
310 listNF_Tc (zipWithEqual mk_sel op_sel_ids method_ids) `thenNF_Tc` \ op_sel_binds ->
311 listNF_Tc (zipWithEqual mk_sel sc_sel_ids dict_ids) `thenNF_Tc` \ sc_sel_binds ->
313 returnNF_Tc (SingleBind (
316 (foldr AndMonoBinds EmptyMonoBinds op_sel_binds)
321 %************************************************************************
323 \subsection[ClassDcl-misc]{Miscellaneous}
325 %************************************************************************
327 Make a selector expression for @sel_id@ from a dictionary @clas_dict@
328 consisting of @dicts@ and @methods@.
330 We have to do a bit of jiggery pokery to get the type variables right.
331 Suppose we have the class decl:
334 op1 :: Ord b => a -> b -> a
337 Then the method selector for \tr{op1} is like this:
339 op1_sel = /\a b -> \dFoo dOrd -> case dFoo of
340 (op1_method,op2_method) -> op1_method b dOrd
342 Note that the type variable for \tr{b} and the (Ord b) dictionary
343 are lifted to the top lambda, and
344 \tr{op1_method} is applied to them. This is preferable to the alternative:
346 op1_sel' = /\a -> \dFoo -> case dFoo of
347 (op1_method,op2_method) -> op1_method
349 because \tr{op1_sel'} then has the rather strange type
351 op1_sel' :: forall a. Foo a -> forall b. Ord b -> a -> b -> a
353 whereas \tr{op1_sel} (the one we use) has the decent type
355 op1_sel :: forall a b. Foo a -> Ord b -> a -> b -> a
358 NOTE that we return a TcMonoBinds (which is later zonked) even though
359 there's no real back-substitution to do. It's just simpler this way!
361 NOTE ALSO that the selector has no free type variables, so we
362 don't bother to instantiate the class-op's local type; instead
363 we just use the variables inside it.
366 mkSelBind :: Id -- the selector id
367 -> TcTyVar s -> TcIdOcc s -- class tyvar and dict
368 -> [TcIdOcc s] -> [TcIdOcc s] -- superclasses and methods in class dict
369 -> TcIdOcc s -- the superclass/method being slected
370 -> NF_TcM s (TcMonoBinds s)
372 mkSelBind sel_id clas_tyvar clas_dict dicts methods method_or_dict@(TcId op)
374 (op_tyvars,op_theta,op_tau) = splitSigmaTy (idType op)
375 op_tys = mkTyVarTys op_tyvars
377 newDicts ClassDeclOrigin op_theta `thenNF_Tc` \ (_, op_dicts) ->
379 -- sel_id = /\ clas_tyvar op_tyvars -> \ clas_dict op_dicts ->
381 -- <dicts..methods> -> method_or_dict op_tyvars op_dicts
383 returnNF_Tc (VarMonoBind (RealId sel_id) (
384 TyLam (clas_tyvar:op_tyvars) (
385 DictLam (clas_dict:op_dicts) (
388 ([PatMatch (DictPat dicts methods) (
389 GRHSMatch (GRHSsAndBindsOut
391 (mkHsDictApp (mkHsTyApp (HsVar method_or_dict) op_tys) op_dicts)
400 %************************************************************************
402 \subsection[Default methods]{Default methods}
404 %************************************************************************
406 The default methods for a class are each passed a dictionary for the
407 class, so that they get access to the other methods at the same type.
408 So, given the class decl
412 op2 :: Ord b => a -> b -> b -> b
415 op2 x y z = if (op1 x) && (y < z) then y else z
417 we get the default methods:
419 defm.Foo.op1 :: forall a. Foo a => a -> Bool
420 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
422 defm.Foo.op2 :: forall a, b. (Foo a, Ord b) => a -> b -> b -> b
423 defm.Foo.op2 = /\ a b -> \ dfoo dord -> \x y z ->
424 if (op1 a dfoo x) && (< b dord y z) then y else z
426 Notice that, like all ids, the foralls of defm.Foo.op2 are at the top.
428 When we come across an instance decl, we may need to use the default
431 instance Foo Int where {}
435 const.Foo.Int.op1 :: Int -> Bool
436 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
438 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
439 const.Foo.Int.op2 = /\b -> defm.Foo.op2 Int b dfun.Foo.Int
441 dfun.Foo.Int :: Foo Int
442 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
444 Notice that, as with method selectors above, we assume that dictionary
445 application is curried, so there's no need to mention the Ord dictionary
448 instance Foo a => Foo [a] where {}
450 dfun.Foo.List :: forall a. Foo a -> Foo [a]
452 = /\ a -> \ dfoo_a ->
454 op1 = defm.Foo.op1 [a] dfoo_list
455 op2 = /\b -> \dord -> defm.Foo.op2 [a] b dfoo_list dord
456 dfoo_list = (op1, op2)
462 buildDefaultMethodBinds
467 -> TcM s (LIE s, TcHsBinds s)
469 buildDefaultMethodBinds clas clas_tyvar
470 default_method_ids default_binds
471 = -- Deal with the method declarations themselves
472 mapNF_Tc unZonkId default_method_ids `thenNF_Tc` \ tc_defm_ids ->
474 (makeClassDeclDefaultMethodRhs clas default_method_ids)
475 [] -- No tyvars in scope for "this inst decl"
476 emptyLIE -- No insts available
477 (map TcId tc_defm_ids)
478 default_binds `thenTc` \ (dicts_needed, default_binds') ->
480 returnTc (dicts_needed, SingleBind (NonRecBind default_binds'))
483 @makeClassDeclDefaultMethodRhs@ builds the default method for a
484 class declaration when no explicit default method is given.
487 makeClassDeclDefaultMethodRhs
491 -> NF_TcM s (TcExpr s)
493 makeClassDeclDefaultMethodRhs clas method_ids tag
494 = tcInstType [] (idType method_id) `thenNF_Tc` \ method_ty ->
496 (tyvars, theta, tau) = splitSigmaTy method_ty
498 newDicts ClassDeclOrigin theta `thenNF_Tc` \ (lie, dict_ids) ->
500 returnNF_Tc (mkHsTyLam tyvars (
501 mkHsDictLam dict_ids (
502 HsApp (mkHsTyApp (HsVar (RealId pAT_ERROR_ID)) [tau])
503 (HsLitOut (HsString (_PK_ error_msg)) stringTy))))
505 (clas_mod, clas_name) = getOrigName clas
507 method_id = method_ids !! (tag-1)
508 class_op = (getClassOps clas) !! (tag-1)
510 error_msg = "%D" -- => No default method for \"
511 ++ unencoded_part_of_msg
513 unencoded_part_of_msg = escErrorMsg (
514 _UNPK_ clas_mod ++ "." ++ _UNPK_ clas_name ++ "."
515 ++ (ppShow 80 (ppr PprForUser class_op))
523 classDeclCtxt class_name sty
524 = ppCat [ppStr "In the class declaration for", ppr sty class_name]