2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcClassDcl]{Typechecking class declarations}
7 module TcClassDcl ( kcClassDecl, tcClassDecl1, tcClassDecls2, mkImplicitClassBinds,
8 tcMethodBind, checkFromThisClass
11 #include "HsVersions.h"
13 import HsSyn ( HsDecl(..), TyClDecl(..), Sig(..), MonoBinds(..),
14 InPat(..), HsBinds(..), GRHSs(..),
15 HsExpr(..), HsLit(..), HsType(..), HsPred(..),
17 andMonoBinds, andMonoBindList, getTyVarName,
18 isClassDecl, isClassOpSig, isPragSig, collectMonoBinders
20 import BasicTypes ( NewOrData(..), TopLevelFlag(..), RecFlag(..) )
21 import RnHsSyn ( RenamedTyClDecl, RenamedClassPragmas,
22 RenamedClassOpSig, RenamedMonoBinds,
23 RenamedContext, RenamedHsDecl, RenamedSig
25 import TcHsSyn ( TcMonoBinds, idsToMonoBinds )
27 import Inst ( Inst, InstOrigin(..), LIE, emptyLIE, plusLIE, plusLIEs, newDicts, newMethod )
28 import TcEnv ( TcId, ValueEnv, TcTyThing(..), tcAddImportedIdInfo,
29 tcLookupTy, tcExtendTyVarEnvForMeths, tcExtendGlobalTyVars,
32 import TcBinds ( tcBindWithSigs, tcSpecSigs )
33 import TcTyDecls ( mkNewTyConRep )
35 import TcMonoType ( kcHsType, tcHsTopType, tcExtendTopTyVarScope,
36 tcContext, checkSigTyVars, sigCtxt, mkTcSig
38 import TcSimplify ( tcSimplifyAndCheck, bindInstsOfLocalFuns )
39 import TcType ( TcType, TcTyVar, tcInstTyVars, zonkTcTyVarBndr, tcGetTyVar )
40 import TcInstUtil ( classDataCon )
41 import PrelInfo ( nO_METHOD_BINDING_ERROR_ID )
42 import Bag ( unionManyBags, bagToList )
43 import Class ( mkClass, classBigSig, classSelIds, Class, ClassOpItem )
44 import CmdLineOpts ( opt_GlasgowExts, opt_WarnMissingMethods )
45 import MkId ( mkDictSelId, mkDataConId, mkDataConWrapId, mkDefaultMethodId )
46 import DataCon ( mkDataCon, dataConId, dataConWrapId, notMarkedStrict )
47 import Id ( Id, setInlinePragma, idUnfolding, idType, idName )
48 import Name ( Name, nameOccName, isLocallyDefined, NamedThing(..) )
49 import NameSet ( emptyNameSet )
51 import Type ( Type, ThetaType, ClassContext,
52 mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy, mkDictTys,
53 mkSigmaTy, mkForAllTys, mkClassPred, classesOfPreds,
54 boxedTypeKind, mkArrowKind
56 import Var ( tyVarKind, TyVar )
57 import VarSet ( mkVarSet, emptyVarSet )
58 import TyCon ( AlgTyConFlavour(..), mkClassTyCon )
59 import Maybes ( seqMaybe )
60 import FiniteMap ( lookupWithDefaultFM )
67 Every class implicitly declares a new data type, corresponding to dictionaries
68 of that class. So, for example:
70 class (D a) => C a where
72 op2 :: forall b. Ord b => a -> b -> b
74 would implicitly declare
76 data CDict a = CDict (D a)
78 (forall b. Ord b => a -> b -> b)
80 (We could use a record decl, but that means changing more of the existing apparatus.
83 For classes with just one superclass+method, we use a newtype decl instead:
86 op :: forallb. a -> b -> b
90 newtype CDict a = CDict (forall b. a -> b -> b)
92 Now DictTy in Type is just a form of type synomym:
93 DictTy c t = TyConTy CDict `AppTy` t
95 Death to "ExpandingDicts".
98 %************************************************************************
100 \subsection{Kind checking}
102 %************************************************************************
105 kcClassDecl (ClassDecl context class_name
106 tyvar_names fundeps class_sigs def_methods pragmas
108 = -- CHECK ARITY 1 FOR HASKELL 1.4
109 checkTc (opt_GlasgowExts || length tyvar_names == 1)
110 (classArityErr class_name) `thenTc_`
112 -- Get the (mutable) class kind
113 tcLookupTy class_name `thenNF_Tc` \ (kind, _) ->
115 -- Make suitable tyvars and do kind checking
116 -- The net effect is to mutate the class kind
117 tcExtendTopTyVarScope kind tyvar_names $ \ _ _ ->
118 tcContext context `thenTc_`
119 mapTc kc_sig the_class_sigs `thenTc_`
123 the_class_sigs = filter isClassOpSig class_sigs
125 kc_sig (ClassOpSig _ _ _ op_ty loc) = tcAddSrcLoc loc (kcHsType op_ty)
129 %************************************************************************
131 \subsection{Type checking}
133 %************************************************************************
136 tcClassDecl1 rec_env rec_vrcs
137 (ClassDecl context class_name
138 tyvar_names fundeps class_sigs def_methods pragmas
139 tycon_name datacon_name datacon_wkr_name sc_sel_names src_loc)
140 = -- LOOK THINGS UP IN THE ENVIRONMENT
141 tcLookupTy class_name `thenTc` \ (class_kind, AClass rec_class arity) ->
142 tcExtendTopTyVarScope class_kind tyvar_names $ \ tyvars _ ->
143 -- The class kind is by now immutable
146 -- traceTc (text "tcClassCtxt" <+> ppr class_name) `thenTc_`
147 tcClassContext class_name rec_class tyvars context sc_sel_names
148 `thenTc` \ (sc_theta, sc_tys, sc_sel_ids) ->
149 -- traceTc (text "tcClassCtxt done" <+> ppr class_name) `thenTc_`
151 -- CHECK THE FUNCTIONAL DEPENDENCIES,
152 tcFundeps fundeps `thenTc` \ fds ->
154 -- CHECK THE CLASS SIGNATURES,
155 mapTc (tcClassSig rec_env rec_class tyvars)
156 (filter isClassOpSig class_sigs)
157 `thenTc` \ sig_stuff ->
159 -- MAKE THE CLASS OBJECT ITSELF
161 (op_tys, op_items) = unzip sig_stuff
162 clas = mkClass class_name tyvars fds
163 sc_theta sc_sel_ids op_items
166 dict_component_tys = sc_tys ++ op_tys
167 new_or_data = case dict_component_tys of
168 [_] -> NewTyCon (mkNewTyConRep tycon)
171 dict_con = mkDataCon datacon_name
172 [notMarkedStrict | _ <- dict_component_tys]
173 [{- No labelled fields -}]
176 [{-No existential tyvars-}] [{-Or context-}]
178 tycon dict_con_id dict_wrap_id
180 dict_con_id = mkDataConId datacon_wkr_name dict_con
181 dict_wrap_id = mkDataConWrapId dict_con
183 argvrcs = lookupWithDefaultFM rec_vrcs (pprPanic "tcClassDecl1: argvrcs:" $
187 tycon = mkClassTyCon tycon_name
191 dict_con -- Constructors
192 clas -- Yes! It's a dictionary
195 returnTc (class_name, AClass clas arity)
199 tcFundeps = mapTc tc_fundep
201 mapTc tc_fd_tyvar us `thenTc` \ us' ->
202 mapTc tc_fd_tyvar vs `thenTc` \ vs' ->
205 tcLookupTy v `thenTc` \(_, ATyVar tv) ->
210 tcClassContext :: Name -> Class -> [TyVar]
211 -> RenamedContext -- class context
212 -> [Name] -- Names for superclass selectors
213 -> TcM s (ClassContext, -- the superclass context
214 [Type], -- types of the superclass dictionaries
215 [Id]) -- superclass selector Ids
217 tcClassContext class_name rec_class rec_tyvars context sc_sel_names
218 = -- Check the context.
219 -- The renamer has already checked that the context mentions
220 -- only the type variable of the class decl.
222 -- For std Haskell check that the context constrains only tyvars
223 (if opt_GlasgowExts then
226 mapTc check_constraint context
229 tcContext context `thenTc` \ sc_theta ->
232 sc_theta' = classesOfPreds sc_theta
233 sc_tys = mkDictTys sc_theta'
234 sc_sel_ids = [mkDictSelId sc_name rec_class | sc_name <- sc_sel_names]
237 returnTc (sc_theta', sc_tys, sc_sel_ids)
240 check_constraint sc@(HsPClass c tys) = checkTc (all is_tyvar tys)
241 (superClassErr class_name sc)
243 is_tyvar (HsTyVar _) = True
244 is_tyvar other = False
247 tcClassSig :: ValueEnv -- Knot tying only!
248 -> Class -- ...ditto...
249 -> [TyVar] -- The class type variable, used for error check only
251 -> TcM s (Type, -- Type of the method
252 ClassOpItem) -- Selector Id, default-method Id, True if explicit default binding
255 tcClassSig rec_env rec_clas rec_clas_tyvars
256 (ClassOpSig op_name dm_name explicit_dm
258 = tcAddSrcLoc src_loc $
260 -- Check the type signature. NB that the envt *already has*
261 -- bindings for the type variables; see comments in TcTyAndClassDcls.
263 -- NB: Renamer checks that the class type variable is mentioned in local_ty,
264 -- and that it is not constrained by theta
265 -- traceTc (text "tcClassSig" <+> ppr op_name) `thenTc_`
266 tcHsTopType op_ty `thenTc` \ local_ty ->
268 global_ty = mkSigmaTy rec_clas_tyvars
269 [mkClassPred rec_clas (mkTyVarTys rec_clas_tyvars)]
272 -- Build the selector id and default method id
273 sel_id = mkDictSelId op_name rec_clas
274 dm_id = mkDefaultMethodId dm_name rec_clas global_ty
275 final_dm_id = tcAddImportedIdInfo rec_env dm_id
277 -- traceTc (text "tcClassSig done" <+> ppr op_name) `thenTc_`
278 returnTc (local_ty, (sel_id, final_dm_id, explicit_dm))
282 %************************************************************************
284 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
286 %************************************************************************
288 The purpose of pass 2 is
291 to beat on the explicitly-provided default-method decls (if any),
292 using them to produce a complete set of default-method decls.
293 (Omitted ones elicit an error message.)
295 to produce a definition for the selector function for each method
296 and superclass dictionary.
299 Pass~2 only applies to locally-defined class declarations.
301 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
302 each local class decl.
305 tcClassDecls2 :: [RenamedHsDecl]
306 -> NF_TcM s (LIE, TcMonoBinds)
310 (returnNF_Tc (emptyLIE, EmptyMonoBinds))
311 [tcClassDecl2 cls_decl | TyClD cls_decl <- decls, isClassDecl cls_decl]
313 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
314 tc2 `thenNF_Tc` \ (lie2, binds2) ->
315 returnNF_Tc (lie1 `plusLIE` lie2,
316 binds1 `AndMonoBinds` binds2)
319 @tcClassDecl2@ is the business end of things.
322 tcClassDecl2 :: RenamedTyClDecl -- The class declaration
323 -> NF_TcM s (LIE, TcMonoBinds)
325 tcClassDecl2 (ClassDecl context class_name
326 tyvar_names _ class_sigs default_binds pragmas _ _ _ _ src_loc)
328 | not (isLocallyDefined class_name)
329 = returnNF_Tc (emptyLIE, EmptyMonoBinds)
331 | otherwise -- It is locally defined
332 = recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
333 tcAddSrcLoc src_loc $
334 tcLookupTy class_name `thenNF_Tc` \ (_, AClass clas _) ->
335 tcDefaultMethodBinds clas default_binds class_sigs
339 mkImplicitClassBinds :: [Class] -> NF_TcM s ([Id], TcMonoBinds)
340 mkImplicitClassBinds classes
341 = returnNF_Tc (concat cls_ids_s, andMonoBindList binds_s)
342 -- The selector binds are already in the selector Id's unfoldings
344 (cls_ids_s, binds_s) = unzip (map mk_implicit classes)
346 mk_implicit clas = (all_cls_ids, binds)
348 dict_con = classDataCon clas
349 all_cls_ids = dataConId dict_con : cls_ids
350 cls_ids = dataConWrapId dict_con : classSelIds clas
352 -- The wrapper and selectors get bindings, the worker does not
353 binds | isLocallyDefined clas = idsToMonoBinds cls_ids
354 | otherwise = EmptyMonoBinds
357 %************************************************************************
359 \subsection[Default methods]{Default methods}
361 %************************************************************************
363 The default methods for a class are each passed a dictionary for the
364 class, so that they get access to the other methods at the same type.
365 So, given the class decl
369 op2 :: Ord b => a -> b -> b -> b
372 op2 x y z = if (op1 x) && (y < z) then y else z
374 we get the default methods:
376 defm.Foo.op1 :: forall a. Foo a => a -> Bool
377 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
379 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
380 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
381 if (op1 a dfoo x) && (< b dord y z) then y else z
384 When we come across an instance decl, we may need to use the default
387 instance Foo Int where {}
391 const.Foo.Int.op1 :: Int -> Bool
392 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
394 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
395 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
397 dfun.Foo.Int :: Foo Int
398 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
400 Notice that, as with method selectors above, we assume that dictionary
401 application is curried, so there's no need to mention the Ord dictionary
402 in const.Foo.Int.op2 (or the type variable).
405 instance Foo a => Foo [a] where {}
407 dfun.Foo.List :: forall a. Foo a -> Foo [a]
409 = /\ a -> \ dfoo_a ->
411 op1 = defm.Foo.op1 [a] dfoo_list
412 op2 = defm.Foo.op2 [a] dfoo_list
413 dfoo_list = (op1, op2)
423 -> TcM s (LIE, TcMonoBinds)
425 tcDefaultMethodBinds clas default_binds sigs
426 = -- Check that the default bindings come from this class
427 checkFromThisClass clas op_items default_binds `thenNF_Tc_`
429 -- Do each default method separately
430 -- For Hugs compatibility we make a default-method for every
431 -- class op, regardless of whether or not the programmer supplied an
432 -- explicit default decl for the class. GHC will actually never
433 -- call the default method for such operations, because it'll whip up
434 -- a more-informative default method at each instance decl.
435 mapAndUnzipTc tc_dm op_items `thenTc` \ (defm_binds, const_lies) ->
437 returnTc (plusLIEs const_lies, andMonoBindList defm_binds)
439 prags = filter isPragSig sigs
441 (tyvars, _, _, op_items) = classBigSig clas
443 origin = ClassDeclOrigin
445 -- We make a separate binding for each default method.
446 -- At one time I used a single AbsBinds for all of them, thus
447 -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
448 -- But that desugars into
449 -- ds = \d -> (..., ..., ...)
450 -- dm1 = \d -> case ds d of (a,b,c) -> a
451 -- And since ds is big, it doesn't get inlined, so we don't get good
452 -- default methods. Better to make separate AbsBinds for each
454 tc_dm op_item@(_, dm_id, _)
455 = tcInstTyVars tyvars `thenNF_Tc` \ (clas_tyvars, inst_tys, _) ->
457 theta = [(mkClassPred clas inst_tys)]
459 newDicts origin theta `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
461 avail_insts = this_dict
463 tcExtendTyVarEnvForMeths tyvars clas_tyvars (
464 tcMethodBind clas origin clas_tyvars inst_tys theta
465 default_binds prags False
467 ) `thenTc` \ (defm_bind, insts_needed, (_, local_dm_id)) ->
469 tcAddErrCtxt (defltMethCtxt clas) $
471 -- tcMethodBind has checked that the class_tyvars havn't
472 -- been unified with each other or another type, but we must
473 -- still zonk them before passing them to tcSimplifyAndCheck
474 mapNF_Tc zonkTcTyVarBndr clas_tyvars `thenNF_Tc` \ clas_tyvars' ->
478 (ptext SLIT("class") <+> ppr clas)
479 (mkVarSet clas_tyvars')
481 insts_needed `thenTc` \ (const_lie, dict_binds) ->
487 [(clas_tyvars', dm_id, local_dm_id)]
488 emptyNameSet -- No inlines (yet)
489 (dict_binds `andMonoBinds` defm_bind)
491 returnTc (full_bind, const_lie)
495 checkFromThisClass :: Class -> [ClassOpItem] -> RenamedMonoBinds -> NF_TcM s ()
496 checkFromThisClass clas op_items mono_binds
497 = mapNF_Tc check_from_this_class bndrs `thenNF_Tc_`
500 check_from_this_class (bndr, loc)
501 | nameOccName bndr `elem` sel_names = returnNF_Tc ()
502 | otherwise = tcAddSrcLoc loc $
503 addErrTc (badMethodErr bndr clas)
504 sel_names = [getOccName sel_id | (sel_id,_,_) <- op_items]
505 bndrs = bagToList (collectMonoBinders mono_binds)
509 @tcMethodBind@ is used to type-check both default-method and
510 instance-decl method declarations. We must type-check methods one at a
511 time, because their signatures may have different contexts and
518 -> [TcTyVar] -- Instantiated type variables for the
519 -- enclosing class/instance decl.
520 -- They'll be signature tyvars, and we
521 -- want to check that they don't get bound
522 -> [TcType] -- Instance types
523 -> TcThetaType -- Available theta; this could be used to check
524 -- the method signature, but actually that's done by
525 -- the caller; here, it's just used for the error message
526 -> RenamedMonoBinds -- Method binding (pick the right one from in here)
527 -> [RenamedSig] -- Pramgas (just for this one)
528 -> Bool -- True <=> This method is from an instance declaration
529 -> ClassOpItem -- The method selector and default-method Id
530 -> TcM s (TcMonoBinds, LIE, (LIE, TcId))
532 tcMethodBind clas origin inst_tyvars inst_tys inst_theta
533 meth_binds prags is_inst_decl
534 (sel_id, dm_id, explicit_dm)
535 = tcGetSrcLoc `thenNF_Tc` \ loc ->
537 newMethod origin sel_id inst_tys `thenNF_Tc` \ meth@(_, meth_id) ->
538 mkTcSig meth_id loc `thenNF_Tc` \ sig_info ->
541 meth_name = idName meth_id
542 maybe_user_bind = find_bind meth_name meth_binds
544 no_user_bind = case maybe_user_bind of {Nothing -> True; other -> False}
546 meth_bind = case maybe_user_bind of
548 Nothing -> mk_default_bind meth_name loc
550 meth_prags = find_prags meth_name prags
553 -- Warn if no method binding, only if -fwarn-missing-methods
554 warnTc (is_inst_decl && opt_WarnMissingMethods && no_user_bind && not explicit_dm)
555 (omittedMethodWarn sel_id clas) `thenNF_Tc_`
557 -- Check the bindings; first add inst_tyvars to the envt
558 -- so that we don't quantify over them in nested places
559 -- The *caller* put the class/inst decl tyvars into the envt
560 tcExtendGlobalTyVars (mkVarSet inst_tyvars) (
561 tcAddErrCtxt (methodCtxt sel_id) $
562 tcBindWithSigs NotTopLevel meth_bind
563 [sig_info] meth_prags NonRecursive
564 ) `thenTc` \ (binds, insts, _) ->
567 tcExtendLocalValEnv [(meth_name, meth_id)] (
568 tcSpecSigs meth_prags
569 ) `thenTc` \ (prag_binds1, prag_lie) ->
571 -- The prag_lie for a SPECIALISE pragma will mention the function
572 -- itself, so we have to simplify them away right now lest they float
574 bindInstsOfLocalFuns prag_lie [meth_id] `thenTc` \ (prag_lie', prag_binds2) ->
577 -- Now check that the instance type variables
578 -- (or, in the case of a class decl, the class tyvars)
579 -- have not been unified with anything in the environment
580 tcAddErrCtxtM (sigCtxt sig_msg inst_tyvars inst_theta (idType meth_id)) $
581 checkSigTyVars inst_tyvars emptyVarSet `thenTc_`
583 returnTc (binds `AndMonoBinds` prag_binds1 `AndMonoBinds` prag_binds2,
584 insts `plusLIE` prag_lie',
587 sig_msg = ptext SLIT("When checking the expected type for class method") <+> ppr sel_name
589 sel_name = idName sel_id
591 -- The renamer just puts the selector ID as the binder in the method binding
592 -- but we must use the method name; so we substitute it here. Crude but simple.
593 find_bind meth_name (FunMonoBind op_name fix matches loc)
594 | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
595 find_bind meth_name (AndMonoBinds b1 b2)
596 = find_bind meth_name b1 `seqMaybe` find_bind meth_name b2
597 find_bind meth_name other = Nothing -- Default case
600 -- Find the prags for this method, and replace the
601 -- selector name with the method name
602 find_prags meth_name [] = []
603 find_prags meth_name (SpecSig name ty loc : prags)
604 | name == sel_name = SpecSig meth_name ty loc : find_prags meth_name prags
605 find_prags meth_name (InlineSig name phase loc : prags)
606 | name == sel_name = InlineSig meth_name phase loc : find_prags meth_name prags
607 find_prags meth_name (NoInlineSig name phase loc : prags)
608 | name == sel_name = NoInlineSig meth_name phase loc : find_prags meth_name prags
609 find_prags meth_name (prag:prags) = find_prags meth_name prags
611 mk_default_bind local_meth_name loc
612 = FunMonoBind local_meth_name
613 False -- Not infix decl
614 [mkSimpleMatch [] (default_expr loc) Nothing loc]
618 | explicit_dm = HsVar (getName dm_id) -- There's a default method
619 | otherwise = error_expr loc -- No default method
621 error_expr loc = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID))
622 (HsLit (HsString (_PK_ (error_msg loc))))
624 error_msg loc = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
630 classArityErr class_name
631 = ptext SLIT("Too many parameters for class") <+> quotes (ppr class_name)
633 superClassErr class_name sc
634 = ptext SLIT("Illegal superclass constraint") <+> quotes (ppr sc)
635 <+> ptext SLIT("in declaration for class") <+> quotes (ppr class_name)
637 defltMethCtxt class_name
638 = ptext SLIT("When checking the default methods for class") <+> quotes (ppr class_name)
641 = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
643 badMethodErr bndr clas
644 = hsep [ptext SLIT("Class"), quotes (ppr clas),
645 ptext SLIT("does not have a method"), quotes (ppr bndr)]
647 omittedMethodWarn sel_id clas
648 = sep [ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id),
649 ptext SLIT("in an instance declaration for") <+> quotes (ppr clas)]