2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcClassDcl]{Typechecking class declarations}
7 module TcClassDcl ( tcClassDecl1, tcClassDecls2, tcMethodBind, badMethodErr ) where
9 #include "HsVersions.h"
11 import HsSyn ( HsDecl(..), ClassDecl(..), Sig(..), MonoBinds(..),
12 InPat(..), HsBinds(..), GRHSsAndBinds(..),
13 HsExpr(..), HsLit(..), HsType(..), pprClassAssertion,
14 unguardedRHS, andMonoBinds, andMonoBindList, getTyVarName
16 import HsPragmas ( ClassPragmas(..) )
17 import BasicTypes ( NewOrData(..), TopLevelFlag(..), RecFlag(..), StrictnessMark(..) )
18 import RnHsSyn ( RenamedClassDecl, RenamedClassPragmas,
19 RenamedClassOpSig, RenamedMonoBinds,
20 RenamedContext, RenamedHsDecl, RenamedSig
22 import TcHsSyn ( TcMonoBinds )
24 import Inst ( Inst, InstOrigin(..), LIE, emptyLIE, plusLIE, newDicts, newMethod )
25 import TcEnv ( TcIdOcc(..), GlobalValueEnv, tcAddImportedIdInfo,
26 tcLookupClass, tcLookupTyVar,
27 tcExtendGlobalTyVars, tcExtendLocalValEnv
29 import TcBinds ( tcBindWithSigs, tcPragmaSigs )
30 import TcUnify ( unifyKinds )
32 import TcMonoType ( tcHsType, tcContext, checkSigTyVars, sigCtxt, mkTcSig )
33 import TcSimplify ( tcSimplifyAndCheck, bindInstsOfLocalFuns )
34 import TcType ( TcType, TcTyVar, tcInstTyVars, zonkTcTyVarBndr )
35 import PrelVals ( nO_METHOD_BINDING_ERROR_ID )
36 import FieldLabel ( firstFieldLabelTag )
37 import Bag ( unionManyBags )
38 import Class ( mkClass, classBigSig, Class )
39 import CmdLineOpts ( opt_GlasgowExts, opt_WarnMissingMethods )
40 import MkId ( mkSuperDictSelId, mkDataConId,
41 mkMethodSelId, mkDefaultMethodId
43 import DataCon ( mkDataCon )
45 getIdUnfolding, idType, idName
47 import CoreUnfold ( getUnfoldingTemplate )
49 import Name ( Name, isLocallyDefined, NamedThing(..) )
51 import Type ( mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy,
52 mkSigmaTy, mkForAllTys, Type, ThetaType,
53 boxedTypeKind, mkArrowKind
55 import Var ( tyVarKind, TyVar )
56 import VarSet ( mkVarSet )
57 import TyCon ( mkAlgTyCon )
58 import Unique ( Unique, Uniquable(..) )
60 import Maybes ( seqMaybe )
63 -- import TcPragmas ( tcGenPragmas, tcClassOpPragmas )
64 tcGenPragmas ty id ps = returnNF_Tc noIdInfo
65 tcClassOpPragmas ty sel def spec ps = returnNF_Tc (spec `setSpecInfo` noIdInfo,
73 Every class implicitly declares a new data type, corresponding to dictionaries
74 of that class. So, for example:
76 class (D a) => C a where
78 op2 :: forall b. Ord b => a -> b -> b
80 would implicitly declare
82 data CDict a = CDict (D a)
84 (forall b. Ord b => a -> b -> b)
86 (We could use a record decl, but that means changing more of the existing apparatus.
89 For classes with just one superclass+method, we use a newtype decl instead:
92 op :: forallb. a -> b -> b
96 newtype CDict a = CDict (forall b. a -> b -> b)
98 Now DictTy in Type is just a form of type synomym:
99 DictTy c t = TyConTy CDict `AppTy` t
101 Death to "ExpandingDicts".
105 tcClassDecl1 rec_env rec_inst_mapper
106 (ClassDecl context class_name
107 tyvar_names class_sigs def_methods pragmas
108 tycon_name datacon_name src_loc)
109 = tcAddSrcLoc src_loc $
110 tcAddErrCtxt (classDeclCtxt class_name) $
112 -- CHECK ARITY 1 FOR HASKELL 1.4
113 checkTc (opt_GlasgowExts || length tyvar_names == 1)
114 (classArityErr class_name) `thenTc_`
116 -- LOOK THINGS UP IN THE ENVIRONMENT
117 tcLookupClass class_name `thenTc` \ (class_kinds, rec_class) ->
118 mapAndUnzipNF_Tc (tcLookupTyVar . getTyVarName) tyvar_names
119 `thenNF_Tc` \ (tyvar_kinds, rec_tyvars) ->
121 -- FORCE THE CLASS AND ITS TYVAR TO HAVE SAME KIND
122 unifyKinds class_kinds tyvar_kinds `thenTc_`
125 tcClassContext class_name rec_class rec_tyvars context pragmas
126 `thenTc` \ (sc_theta, sc_tys, sc_sel_ids) ->
128 -- CHECK THE CLASS SIGNATURES,
129 mapTc (tcClassSig rec_env rec_class rec_tyvars) class_sigs
130 `thenTc` \ sig_stuff ->
132 -- MAKE THE CLASS OBJECT ITSELF
134 (op_tys, op_sel_ids, defm_ids) = unzip3 sig_stuff
135 rec_class_inst_env = rec_inst_mapper rec_class
136 clas = mkClass (getName class_name) rec_tyvars
137 sc_theta sc_sel_ids op_sel_ids defm_ids
141 dict_component_tys = sc_tys ++ op_tys
142 new_or_data = case dict_component_tys of
146 dict_con = mkDataCon datacon_name
147 [NotMarkedStrict | _ <- dict_component_tys]
148 [{- No labelled fields -}]
151 [{-No existential tyvars-}] [{-Or context-}]
154 dict_con_id = mkDataConId dict_con
156 tycon = mkAlgTyCon tycon_name
157 (foldr (mkArrowKind . tyVarKind) boxedTypeKind rec_tyvars)
160 [dict_con] -- Constructors
162 (Just clas) -- Yes! It's a dictionary
171 tcClassContext :: Name -> Class -> [TyVar]
172 -> RenamedContext -- class context
173 -> RenamedClassPragmas -- pragmas for superclasses
174 -> TcM s (ThetaType, -- the superclass context
175 [Type], -- types of the superclass dictionaries
176 [Id]) -- superclass selector Ids
178 tcClassContext class_name rec_class rec_tyvars context pragmas
179 = -- Check the context.
180 -- The renamer has already checked that the context mentions
181 -- only the type variable of the class decl.
183 -- For std Haskell check that the context constrains only tyvars
184 (if opt_GlasgowExts then
187 mapTc check_constraint context
190 tcContext context `thenTc` \ sc_theta ->
193 sc_tys = [mkDictTy sc tys | (sc,tys) <- sc_theta]
196 -- Make super-class selector ids
197 -- We number them off, 1, 2, 3 etc so that we can construct
198 -- names for the selectors. Thus
199 -- class (C a, C b) => D a b where ...
200 -- gives superclass selectors
202 -- (We used to call them D_C, but now we can have two different
203 -- superclasses both called C!)
204 mapTc mk_super_id (sc_theta `zip` [firstFieldLabelTag..]) `thenTc` \ sc_sel_ids ->
207 returnTc (sc_theta, sc_tys, sc_sel_ids)
210 rec_tyvar_tys = mkTyVarTys rec_tyvars
212 mk_super_id ((super_class, tys), index)
213 = tcGetUnique `thenNF_Tc` \ uniq ->
215 ty = mkForAllTys rec_tyvars $
216 mkFunTy (mkDictTy rec_class rec_tyvar_tys) (mkDictTy super_class tys)
218 returnTc (mkSuperDictSelId uniq rec_class index ty)
220 check_constraint (c, tys) = checkTc (all is_tyvar tys)
221 (superClassErr class_name (c, tys))
223 is_tyvar (MonoTyVar _) = True
224 is_tyvar other = False
227 tcClassSig :: GlobalValueEnv -- Knot tying only!
228 -> Class -- ...ditto...
229 -> [TyVar] -- The class type variable, used for error check only
231 -> TcM s (Type, -- Type of the method
233 Maybe Id) -- default-method ids
235 tcClassSig rec_env rec_clas rec_clas_tyvars
236 (ClassOpSig op_name maybe_dm_name
239 = tcAddSrcLoc src_loc $
241 -- Check the type signature. NB that the envt *already has*
242 -- bindings for the type variables; see comments in TcTyAndClassDcls.
244 -- NB: Renamer checks that the class type variable is mentioned in local_ty,
245 -- and that it is not constrained by theta
246 tcHsType op_ty `thenTc` \ local_ty ->
248 global_ty = mkSigmaTy rec_clas_tyvars
249 [(rec_clas, mkTyVarTys rec_clas_tyvars)]
253 -- Build the selector id and default method id
255 sel_id = mkMethodSelId op_name rec_clas global_ty
256 maybe_dm_id = case maybe_dm_name of
259 dm_id = mkDefaultMethodId dm_name rec_clas global_ty
261 Just (tcAddImportedIdInfo rec_env dm_id)
263 returnTc (local_ty, sel_id, maybe_dm_id)
267 %************************************************************************
269 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
271 %************************************************************************
273 The purpose of pass 2 is
276 to beat on the explicitly-provided default-method decls (if any),
277 using them to produce a complete set of default-method decls.
278 (Omitted ones elicit an error message.)
280 to produce a definition for the selector function for each method
281 and superclass dictionary.
284 Pass~2 only applies to locally-defined class declarations.
286 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
287 each local class decl.
290 tcClassDecls2 :: [RenamedHsDecl]
291 -> NF_TcM s (LIE s, TcMonoBinds s)
295 (returnNF_Tc (emptyLIE, EmptyMonoBinds))
296 [tcClassDecl2 cls_decl | ClD cls_decl <- decls]
298 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
299 tc2 `thenNF_Tc` \ (lie2, binds2) ->
300 returnNF_Tc (lie1 `plusLIE` lie2,
301 binds1 `AndMonoBinds` binds2)
304 @tcClassDecl2@ is the business end of things.
307 tcClassDecl2 :: RenamedClassDecl -- The class declaration
308 -> NF_TcM s (LIE s, TcMonoBinds s)
310 tcClassDecl2 (ClassDecl context class_name
311 tyvar_names class_sigs default_binds pragmas _ _ src_loc)
313 | not (isLocallyDefined class_name)
314 = returnNF_Tc (emptyLIE, EmptyMonoBinds)
316 | otherwise -- It is locally defined
317 = recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
318 tcAddSrcLoc src_loc $
320 -- Get the relevant class
321 tcLookupClass class_name `thenTc` \ (_, clas) ->
323 (tyvars, sc_theta, sc_sel_ids, op_sel_ids, defm_ids) = classBigSig clas
325 -- The selector binds are already in the selector Id's unfoldings
326 -- sel_binds = [ CoreMonoBind (RealId sel_id) (getUnfoldingTemplate (getIdUnfolding sel_id))
327 -- | sel_id <- sc_sel_ids ++ op_sel_ids,
328 -- isLocallyDefined sel_id
331 -- final_sel_binds = andMonoBindList sel_binds
333 -- Generate bindings for the default methods
334 tcDefaultMethodBinds clas default_binds `thenTc` \ (const_insts, meth_binds) ->
336 returnTc (const_insts, meth_binds)
337 -- final_sel_binds `AndMonoBinds` meth_binds)
338 -- Leave 'em out for now. They always get inlined anyway. SLPJ June '98
341 %************************************************************************
343 \subsection[Default methods]{Default methods}
345 %************************************************************************
347 The default methods for a class are each passed a dictionary for the
348 class, so that they get access to the other methods at the same type.
349 So, given the class decl
353 op2 :: Ord b => a -> b -> b -> b
356 op2 x y z = if (op1 x) && (y < z) then y else z
358 we get the default methods:
360 defm.Foo.op1 :: forall a. Foo a => a -> Bool
361 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
363 ====================== OLD ==================
365 defm.Foo.op2 :: forall a, b. (Foo a, Ord b) => a -> b -> b -> b
366 defm.Foo.op2 = /\ a b -> \ dfoo dord -> \x y z ->
367 if (op1 a dfoo x) && (< b dord y z) then y else z
369 Notice that, like all ids, the foralls of defm.Foo.op2 are at the top.
370 ====================== END OF OLD ===================
374 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
375 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
376 if (op1 a dfoo x) && (< b dord y z) then y else z
380 When we come across an instance decl, we may need to use the default
383 instance Foo Int where {}
387 const.Foo.Int.op1 :: Int -> Bool
388 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
390 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
391 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
393 dfun.Foo.Int :: Foo Int
394 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
396 Notice that, as with method selectors above, we assume that dictionary
397 application is curried, so there's no need to mention the Ord dictionary
398 in const.Foo.Int.op2 (or the type variable).
401 instance Foo a => Foo [a] where {}
403 dfun.Foo.List :: forall a. Foo a -> Foo [a]
405 = /\ a -> \ dfoo_a ->
407 op1 = defm.Foo.op1 [a] dfoo_list
408 op2 = defm.Foo.op2 [a] dfoo_list
409 dfoo_list = (op1, op2)
418 -> TcM s (LIE s, TcMonoBinds s)
420 tcDefaultMethodBinds clas default_binds
421 = -- Construct suitable signatures
422 tcInstTyVars tyvars `thenNF_Tc` \ (clas_tyvars, inst_tys, inst_env) ->
424 -- Typecheck the default bindings
426 tc_dm sel_id_w_dm@(_, Just dm_id)
427 = tcMethodBind clas origin inst_tys clas_tyvars
428 default_binds [{-no prags-}] False
429 sel_id_w_dm `thenTc` \ (bind, insts, (_, local_dm_id)) ->
430 returnTc (bind, insts, (clas_tyvars, RealId dm_id, local_dm_id))
432 mapAndUnzip3Tc tc_dm sel_ids_w_dms `thenTc` \ (defm_binds, insts_needed, abs_bind_stuff) ->
435 newDicts origin [(clas,inst_tys)] `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
437 avail_insts = this_dict
439 tcAddErrCtxt (classDeclCtxt clas) $
441 -- tcMethodBind has checked that the class_tyvars havn't
442 -- been unified with each other or another type, but we must
444 mapNF_Tc zonkTcTyVarBndr clas_tyvars `thenNF_Tc` \ clas_tyvars' ->
447 (ptext SLIT("class") <+> ppr clas)
448 (mkVarSet clas_tyvars')
450 (unionManyBags insts_needed) `thenTc` \ (const_lie, dict_binds) ->
453 full_binds = AbsBinds
457 (dict_binds `andMonoBinds` andMonoBindList defm_binds)
459 returnTc (const_lie, full_binds)
462 (tyvars, sc_theta, sc_sel_ids, op_sel_ids, defm_ids) = classBigSig clas
464 sel_ids_w_dms = [pair | pair@(_, Just _) <- op_sel_ids `zip` defm_ids]
465 -- Just the ones for which there is an explicit
466 -- user default declaration
468 origin = ClassDeclOrigin
471 @tcMethodBind@ is used to type-check both default-method and
472 instance-decl method declarations. We must type-check methods one at a
473 time, because their signatures may have different contexts and
480 -> [TcType s] -- Instance types
481 -> [TcTyVar s] -- Free variables of those instance types
482 -- they'll be signature tyvars, and we
483 -- want to check that they don't bound
484 -> RenamedMonoBinds -- Method binding (pick the right one from in here)
485 -> [RenamedSig] -- Pramgas (just for this one)
486 -> Bool -- True <=> supply default decl if no explicit decl
487 -- This is true for instance decls,
488 -- false for class decls
489 -> (Id, Maybe Id) -- The method selector and default-method Id
490 -> TcM s (TcMonoBinds s, LIE s, (LIE s, TcIdOcc s))
492 tcMethodBind clas origin inst_tys inst_tyvars
493 meth_binds prags supply_default_bind
494 (sel_id, maybe_dm_id)
495 = tcGetSrcLoc `thenNF_Tc` \ loc ->
497 newMethod origin (RealId sel_id) inst_tys `thenNF_Tc` \ meth@(_, TcId meth_id) ->
498 mkTcSig meth_id loc `thenNF_Tc` \ sig_info ->
501 meth_name = idName meth_id
502 maybe_user_bind = find_bind meth_name meth_binds
504 no_user_bind = case maybe_user_bind of {Nothing -> True; other -> False}
505 no_user_default = case maybe_dm_id of {Nothing -> True; other -> False}
507 meth_bind = case maybe_user_bind of
509 Nothing -> mk_default_bind meth_name loc
511 meth_prags = find_prags meth_name prags
514 -- Warn if no method binding, only if -fwarn-missing-methods
515 if no_user_bind && not supply_default_bind then
516 pprPanic "tcMethodBind" (ppr clas <+> ppr inst_tys)
518 warnTc (opt_WarnMissingMethods && no_user_bind && no_user_default)
519 (omittedMethodWarn sel_id clas) `thenNF_Tc_`
522 tcExtendLocalValEnv [meth_name] [meth_id] (
523 tcPragmaSigs meth_prags
524 ) `thenTc` \ (prag_info_fn, prag_binds1, prag_lie) ->
526 -- Check the bindings
527 tcExtendGlobalTyVars (mkVarSet inst_tyvars) (
528 tcAddErrCtxt (methodCtxt sel_id) $
529 tcBindWithSigs NotTopLevel meth_bind [sig_info]
530 NonRecursive prag_info_fn
531 ) `thenTc` \ (binds, insts, _) ->
534 -- The prag_lie for a SPECIALISE pragma will mention the function
535 -- itself, so we have to simplify them away right now lest they float
537 bindInstsOfLocalFuns prag_lie [meth_id] `thenTc` \ (prag_lie', prag_binds2) ->
540 -- Now check that the instance type variables
541 -- (or, in the case of a class decl, the class tyvars)
542 -- have not been unified with anything in the environment
543 tcAddErrCtxtM (sigCtxt (quotes (ppr sel_id)) (idType meth_id)) (
544 checkSigTyVars inst_tyvars `thenTc_`
546 returnTc (binds `AndMonoBinds` prag_binds1 `AndMonoBinds` prag_binds2,
547 insts `plusLIE` prag_lie',
551 sel_name = idName sel_id
553 -- The renamer just puts the selector ID as the binder in the method binding
554 -- but we must use the method name; so we substitute it here. Crude but simple.
555 find_bind meth_name (FunMonoBind op_name fix matches loc)
556 | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
557 find_bind meth_name (PatMonoBind (VarPatIn op_name) rhs loc)
558 | op_name == sel_name = Just (PatMonoBind (VarPatIn meth_name) rhs loc)
559 find_bind meth_name (AndMonoBinds b1 b2)
560 = find_bind meth_name b1 `seqMaybe` find_bind meth_name b2
561 find_bind meth_name other = Nothing -- Default case
564 -- Find the prags for this method, and replace the
565 -- selector name with the method name
566 find_prags meth_name [] = []
567 find_prags meth_name (SpecSig name ty spec loc : prags)
568 | name == sel_name = SpecSig meth_name ty spec loc : find_prags meth_name prags
569 find_prags meth_name (InlineSig name loc : prags)
570 | name == sel_name = InlineSig meth_name loc : find_prags meth_name prags
571 find_prags meth_name (NoInlineSig name loc : prags)
572 | name == sel_name = NoInlineSig meth_name loc : find_prags meth_name prags
573 find_prags meth_name (prag:prags) = find_prags meth_name prags
575 mk_default_bind local_meth_name loc
576 = PatMonoBind (VarPatIn local_meth_name)
577 (GRHSsAndBindsIn (unguardedRHS (default_expr loc) loc) EmptyBinds)
581 = case maybe_dm_id of
582 Just dm_id -> HsVar (getName dm_id) -- There's a default method
583 Nothing -> error_expr loc -- No default method
585 error_expr loc = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID))
586 (HsLit (HsString (_PK_ (error_msg loc))))
588 error_msg loc = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
594 classArityErr class_name
595 = ptext SLIT("Too many parameters for class") <+> quotes (ppr class_name)
597 classDeclCtxt class_name
598 = ptext SLIT("In the class declaration for") <+> quotes (ppr class_name)
600 superClassErr class_name sc
601 = ptext SLIT("Illegal superclass constraint") <+> quotes (pprClassAssertion sc)
602 <+> ptext SLIT("in declaration for class") <+> quotes (ppr class_name)
605 = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
607 badMethodErr bndr clas
608 = hsep [ptext SLIT("Class"), quotes (ppr clas),
609 ptext SLIT("does not have a method"), quotes (ppr bndr)]
611 omittedMethodWarn sel_id clas
612 = sep [ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id),
613 ptext SLIT("in an instance declaration for") <+> quotes (ppr clas)]