[project @ 2000-07-07 12:13:43 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcClassDcl.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcClassDcl]{Typechecking class declarations}
5
6 \begin{code}
7 module TcClassDcl ( kcClassDecl, tcClassDecl1, tcClassDecls2, mkImplicitClassBinds,
8                     tcMethodBind, checkFromThisClass
9                   ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( HsDecl(..), TyClDecl(..), Sig(..), MonoBinds(..),
14                           InPat(..), HsBinds(..), GRHSs(..),
15                           HsExpr(..), HsLit(..), HsType(..), HsPred(..),
16                           mkSimpleMatch,
17                           andMonoBinds, andMonoBindList, getTyVarName, 
18                           isClassDecl, isClassOpSig, isPragSig, collectMonoBinders
19                         )
20 import HsPragmas        ( ClassPragmas(..) )
21 import BasicTypes       ( NewOrData(..), TopLevelFlag(..), RecFlag(..) )
22 import RnHsSyn          ( RenamedTyClDecl, RenamedClassPragmas,
23                           RenamedClassOpSig, RenamedMonoBinds,
24                           RenamedContext, RenamedHsDecl, RenamedSig
25                         )
26 import TcHsSyn          ( TcMonoBinds, idsToMonoBinds )
27
28 import Inst             ( Inst, InstOrigin(..), LIE, emptyLIE, plusLIE, plusLIEs, newDicts, newMethod )
29 import TcEnv            ( TcId, ValueEnv, TcTyThing(..), tcAddImportedIdInfo,
30                           tcLookupTy, tcExtendTyVarEnvForMeths, tcExtendGlobalTyVars,
31                           tcExtendLocalValEnv
32                         )
33 import TcBinds          ( tcBindWithSigs, tcSpecSigs )
34 import TcTyDecls        ( mkNewTyConRep )
35 import TcUnify          ( unifyKinds )
36 import TcMonad
37 import TcMonoType       ( kcHsType, tcHsTopType, tcExtendTopTyVarScope, 
38                           tcContext, checkSigTyVars, sigCtxt, mkTcSig
39                         )
40 import TcSimplify       ( tcSimplifyAndCheck, bindInstsOfLocalFuns )
41 import TcType           ( TcType, TcTyVar, tcInstTyVars, zonkTcTyVarBndr, tcGetTyVar )
42 import TcInstUtil       ( classDataCon )
43 import PrelInfo         ( nO_METHOD_BINDING_ERROR_ID )
44 import FieldLabel       ( firstFieldLabelTag )
45 import Bag              ( unionManyBags, bagToList )
46 import Class            ( mkClass, classBigSig, classSelIds, Class, ClassOpItem )
47 import CmdLineOpts      ( opt_GlasgowExts, opt_WarnMissingMethods )
48 import MkId             ( mkDictSelId, mkDataConId, mkDataConWrapId, mkDefaultMethodId )
49 import DataCon          ( mkDataCon, dataConId, dataConWrapId, notMarkedStrict )
50 import Id               ( Id, setInlinePragma, idUnfolding, idType, idName )
51 import CoreUnfold       ( unfoldingTemplate )
52 import IdInfo
53 import Name             ( Name, nameOccName, isLocallyDefined, NamedThing(..) )
54 import NameSet          ( emptyNameSet )
55 import Outputable
56 import Type             ( Type, ThetaType, ClassContext,
57                           mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy, mkDictTys,
58                           mkSigmaTy, mkForAllTys, mkClassPred, classesOfPreds,
59                           boxedTypeKind, mkArrowKind
60                         )
61 import Var              ( tyVarKind, TyVar )
62 import VarSet           ( mkVarSet, emptyVarSet )
63 import TyCon            ( AlgTyConFlavour(..), mkClassTyCon )
64 import Unique           ( Unique, Uniquable(..) )
65 import Util
66 import Maybes           ( seqMaybe )
67 import FiniteMap        ( lookupWithDefaultFM )
68 \end{code}
69
70
71
72 Dictionary handling
73 ~~~~~~~~~~~~~~~~~~~
74 Every class implicitly declares a new data type, corresponding to dictionaries
75 of that class. So, for example:
76
77         class (D a) => C a where
78           op1 :: a -> a
79           op2 :: forall b. Ord b => a -> b -> b
80
81 would implicitly declare
82
83         data CDict a = CDict (D a)      
84                              (a -> a)
85                              (forall b. Ord b => a -> b -> b)
86
87 (We could use a record decl, but that means changing more of the existing apparatus.
88 One step at at time!)
89
90 For classes with just one superclass+method, we use a newtype decl instead:
91
92         class C a where
93           op :: forallb. a -> b -> b
94
95 generates
96
97         newtype CDict a = CDict (forall b. a -> b -> b)
98
99 Now DictTy in Type is just a form of type synomym: 
100         DictTy c t = TyConTy CDict `AppTy` t
101
102 Death to "ExpandingDicts".
103
104
105 %************************************************************************
106 %*                                                                      *
107 \subsection{Kind checking}
108 %*                                                                      *
109 %************************************************************************
110
111 \begin{code}
112 kcClassDecl (ClassDecl  context class_name
113                         tyvar_names fundeps class_sigs def_methods pragmas
114                         _ _ _ _ src_loc)
115   =         -- CHECK ARITY 1 FOR HASKELL 1.4
116     checkTc (opt_GlasgowExts || length tyvar_names == 1)
117             (classArityErr class_name)          `thenTc_`
118
119         -- Get the (mutable) class kind
120     tcLookupTy class_name                       `thenNF_Tc` \ (kind, _) ->
121
122         -- Make suitable tyvars and do kind checking
123         -- The net effect is to mutate the class kind
124     tcExtendTopTyVarScope kind tyvar_names      $ \ _ _ ->
125     tcContext context                           `thenTc_`
126     mapTc kc_sig the_class_sigs                 `thenTc_`
127
128     returnTc ()
129   where
130     the_class_sigs = filter isClassOpSig class_sigs
131   
132     kc_sig (ClassOpSig _ _ _ op_ty loc) = tcAddSrcLoc loc (kcHsType op_ty)
133 \end{code}
134
135
136 %************************************************************************
137 %*                                                                      *
138 \subsection{Type checking}
139 %*                                                                      *
140 %************************************************************************
141
142 \begin{code}
143 tcClassDecl1 rec_env rec_vrcs
144              (ClassDecl context class_name
145                         tyvar_names fundeps class_sigs def_methods pragmas 
146                         tycon_name datacon_name datacon_wkr_name sc_sel_names src_loc)
147   =     -- LOOK THINGS UP IN THE ENVIRONMENT
148     tcLookupTy class_name                               `thenTc` \ (class_kind, AClass rec_class arity) ->
149     tcExtendTopTyVarScope class_kind tyvar_names        $ \ tyvars _ ->
150         -- The class kind is by now immutable
151         
152         -- CHECK THE CONTEXT
153 --  traceTc (text "tcClassCtxt" <+> ppr class_name)     `thenTc_`
154     tcClassContext class_name rec_class tyvars context sc_sel_names
155                                                 `thenTc` \ (sc_theta, sc_tys, sc_sel_ids) ->
156 --  traceTc (text "tcClassCtxt done" <+> ppr class_name)        `thenTc_`
157
158         -- CHECK THE FUNCTIONAL DEPENDENCIES,
159     tcFundeps fundeps                           `thenTc` \ fds ->
160
161         -- CHECK THE CLASS SIGNATURES,
162     mapTc (tcClassSig rec_env rec_class tyvars) 
163           (filter isClassOpSig class_sigs)
164                                                 `thenTc` \ sig_stuff ->
165
166         -- MAKE THE CLASS OBJECT ITSELF
167     let
168         (op_tys, op_items) = unzip sig_stuff
169         clas = mkClass class_name tyvars fds
170                        sc_theta sc_sel_ids op_items
171                        tycon
172
173         dict_component_tys = sc_tys ++ op_tys
174         new_or_data = case dict_component_tys of
175                         [_]   -> NewTyCon (mkNewTyConRep tycon)
176                         other -> DataTyCon
177
178         dict_con = mkDataCon datacon_name
179                            [notMarkedStrict | _ <- dict_component_tys]
180                            [{- No labelled fields -}]
181                            tyvars
182                            [{-No context-}]
183                            [{-No existential tyvars-}] [{-Or context-}]
184                            dict_component_tys
185                            tycon dict_con_id dict_wrap_id
186
187         dict_con_id  = mkDataConId datacon_wkr_name dict_con
188         dict_wrap_id = mkDataConWrapId dict_con
189
190         argvrcs = lookupWithDefaultFM rec_vrcs (pprPanic "tcClassDecl1: argvrcs:" $
191                                                          ppr tycon_name)
192                                       tycon_name
193
194         tycon = mkClassTyCon tycon_name
195                              class_kind
196                              tyvars
197                              argvrcs
198                              dict_con           -- Constructors
199                              clas               -- Yes!  It's a dictionary 
200                              new_or_data
201     in
202     returnTc (class_name, AClass clas arity)
203 \end{code}
204
205 \begin{code}
206 tcFundeps = mapTc tc_fundep
207 tc_fundep (us, vs) =
208     mapTc tc_fd_tyvar us        `thenTc` \ us' ->
209     mapTc tc_fd_tyvar vs        `thenTc` \ vs' ->
210     returnTc (us', vs')
211 tc_fd_tyvar v =
212     tcLookupTy v         `thenTc` \(_, ATyVar tv) ->
213     returnTc tv
214 \end{code}
215
216 \begin{code}
217 tcClassContext :: Name -> Class -> [TyVar]
218                -> RenamedContext        -- class context
219                -> [Name]                -- Names for superclass selectors
220                -> TcM s (ClassContext,  -- the superclass context
221                          [Type],        -- types of the superclass dictionaries
222                          [Id])          -- superclass selector Ids
223
224 tcClassContext class_name rec_class rec_tyvars context sc_sel_names
225   =     -- Check the context.
226         -- The renamer has already checked that the context mentions
227         -- only the type variable of the class decl.
228
229         -- For std Haskell check that the context constrains only tyvars
230     (if opt_GlasgowExts then
231         returnTc []
232      else
233         mapTc check_constraint context
234     )                                   `thenTc_`
235
236     tcContext context                   `thenTc` \ sc_theta ->
237
238     let
239        sc_theta' = classesOfPreds sc_theta
240        sc_tys = mkDictTys sc_theta'
241        sc_sel_ids = [mkDictSelId sc_name rec_class | sc_name <- sc_sel_names]
242     in
243         -- Done
244     returnTc (sc_theta', sc_tys, sc_sel_ids)
245
246   where
247     check_constraint sc@(HsPClass c tys) = checkTc (all is_tyvar tys)
248                                                    (superClassErr class_name sc)
249
250     is_tyvar (HsTyVar _) = True
251     is_tyvar other       = False
252
253
254 tcClassSig :: ValueEnv          -- Knot tying only!
255            -> Class                     -- ...ditto...
256            -> [TyVar]                   -- The class type variable, used for error check only
257            -> RenamedClassOpSig
258            -> TcM s (Type,              -- Type of the method
259                      ClassOpItem)       -- Selector Id, default-method Id, True if explicit default binding
260
261
262 tcClassSig rec_env rec_clas rec_clas_tyvars
263            (ClassOpSig op_name dm_name explicit_dm
264                        op_ty src_loc)
265   = tcAddSrcLoc src_loc $
266
267         -- Check the type signature.  NB that the envt *already has*
268         -- bindings for the type variables; see comments in TcTyAndClassDcls.
269
270     -- NB: Renamer checks that the class type variable is mentioned in local_ty,
271     -- and that it is not constrained by theta
272 --  traceTc (text "tcClassSig" <+> ppr op_name) `thenTc_`
273     tcHsTopType op_ty                           `thenTc` \ local_ty ->
274     let
275         global_ty   = mkSigmaTy rec_clas_tyvars 
276                                 [mkClassPred rec_clas (mkTyVarTys rec_clas_tyvars)]
277                                 local_ty
278
279         -- Build the selector id and default method id
280         sel_id      = mkDictSelId op_name rec_clas
281         dm_id       = mkDefaultMethodId dm_name rec_clas global_ty
282         final_dm_id = tcAddImportedIdInfo rec_env dm_id
283     in
284 --  traceTc (text "tcClassSig done" <+> ppr op_name)    `thenTc_`
285     returnTc (local_ty, (sel_id, final_dm_id, explicit_dm))
286 \end{code}
287
288
289 %************************************************************************
290 %*                                                                      *
291 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
292 %*                                                                      *
293 %************************************************************************
294
295 The purpose of pass 2 is
296 \begin{enumerate}
297 \item
298 to beat on the explicitly-provided default-method decls (if any),
299 using them to produce a complete set of default-method decls.
300 (Omitted ones elicit an error message.)
301 \item
302 to produce a definition for the selector function for each method
303 and superclass dictionary.
304 \end{enumerate}
305
306 Pass~2 only applies to locally-defined class declarations.
307
308 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
309 each local class decl.
310
311 \begin{code}
312 tcClassDecls2 :: [RenamedHsDecl]
313               -> NF_TcM s (LIE, TcMonoBinds)
314
315 tcClassDecls2 decls
316   = foldr combine
317           (returnNF_Tc (emptyLIE, EmptyMonoBinds))
318           [tcClassDecl2 cls_decl | TyClD cls_decl <- decls, isClassDecl cls_decl]
319   where
320     combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
321                       tc2 `thenNF_Tc` \ (lie2, binds2) ->
322                       returnNF_Tc (lie1 `plusLIE` lie2,
323                                    binds1 `AndMonoBinds` binds2)
324 \end{code}
325
326 @tcClassDecl2@ is the business end of things.
327
328 \begin{code}
329 tcClassDecl2 :: RenamedTyClDecl         -- The class declaration
330              -> NF_TcM s (LIE, TcMonoBinds)
331
332 tcClassDecl2 (ClassDecl context class_name
333                         tyvar_names _ class_sigs default_binds pragmas _ _ _ _ src_loc)
334
335   | not (isLocallyDefined class_name)
336   = returnNF_Tc (emptyLIE, EmptyMonoBinds)
337
338   | otherwise   -- It is locally defined
339   = recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $ 
340     tcAddSrcLoc src_loc                                   $
341     tcLookupTy class_name                               `thenNF_Tc` \ (_, AClass clas _) ->
342     tcDefaultMethodBinds clas default_binds class_sigs
343 \end{code}
344
345 \begin{code}
346 mkImplicitClassBinds :: [Class] -> NF_TcM s ([Id], TcMonoBinds)
347 mkImplicitClassBinds classes
348   = returnNF_Tc (concat cls_ids_s, andMonoBindList binds_s)
349         -- The selector binds are already in the selector Id's unfoldings
350   where
351     (cls_ids_s, binds_s) = unzip (map mk_implicit classes)
352
353     mk_implicit clas = (all_cls_ids, binds)
354                      where
355                         dict_con    = classDataCon clas
356                         all_cls_ids = dataConId dict_con : cls_ids
357                         cls_ids     = dataConWrapId dict_con : classSelIds clas
358
359                         -- The wrapper and selectors get bindings, the worker does not
360                         binds | isLocallyDefined clas = idsToMonoBinds cls_ids
361                               | otherwise             = EmptyMonoBinds
362 \end{code}
363
364 %************************************************************************
365 %*                                                                      *
366 \subsection[Default methods]{Default methods}
367 %*                                                                      *
368 %************************************************************************
369
370 The default methods for a class are each passed a dictionary for the
371 class, so that they get access to the other methods at the same type.
372 So, given the class decl
373 \begin{verbatim}
374 class Foo a where
375         op1 :: a -> Bool
376         op2 :: Ord b => a -> b -> b -> b
377
378         op1 x = True
379         op2 x y z = if (op1 x) && (y < z) then y else z
380 \end{verbatim}
381 we get the default methods:
382 \begin{verbatim}
383 defm.Foo.op1 :: forall a. Foo a => a -> Bool
384 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
385
386 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
387 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
388                   if (op1 a dfoo x) && (< b dord y z) then y else z
389 \end{verbatim}
390
391 When we come across an instance decl, we may need to use the default
392 methods:
393 \begin{verbatim}
394 instance Foo Int where {}
395 \end{verbatim}
396 gives
397 \begin{verbatim}
398 const.Foo.Int.op1 :: Int -> Bool
399 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
400
401 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
402 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
403
404 dfun.Foo.Int :: Foo Int
405 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
406 \end{verbatim}
407 Notice that, as with method selectors above, we assume that dictionary
408 application is curried, so there's no need to mention the Ord dictionary
409 in const.Foo.Int.op2 (or the type variable).
410
411 \begin{verbatim}
412 instance Foo a => Foo [a] where {}
413
414 dfun.Foo.List :: forall a. Foo a -> Foo [a]
415 dfun.Foo.List
416   = /\ a -> \ dfoo_a ->
417     let rec
418         op1 = defm.Foo.op1 [a] dfoo_list
419         op2 = defm.Foo.op2 [a] dfoo_list
420         dfoo_list = (op1, op2)
421     in
422         dfoo_list
423 \end{verbatim}
424
425 \begin{code}
426 tcDefaultMethodBinds
427         :: Class
428         -> RenamedMonoBinds
429         -> [RenamedSig]
430         -> TcM s (LIE, TcMonoBinds)
431
432 tcDefaultMethodBinds clas default_binds sigs
433   =     -- Check that the default bindings come from this class
434     checkFromThisClass clas op_items default_binds      `thenNF_Tc_`
435
436         -- Do each default method separately
437         -- For Hugs compatibility we make a default-method for every
438         -- class op, regardless of whether or not the programmer supplied an
439         -- explicit default decl for the class.  GHC will actually never
440         -- call the default method for such operations, because it'll whip up
441         -- a more-informative default method at each instance decl.
442     mapAndUnzipTc tc_dm op_items                `thenTc` \ (defm_binds, const_lies) ->
443
444     returnTc (plusLIEs const_lies, andMonoBindList defm_binds)
445   where
446     prags = filter isPragSig sigs
447
448     (tyvars, _, _, op_items) = classBigSig clas
449
450     origin = ClassDeclOrigin
451
452     -- We make a separate binding for each default method.
453     -- At one time I used a single AbsBinds for all of them, thus
454     --  AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
455     -- But that desugars into
456     --  ds = \d -> (..., ..., ...)
457     --  dm1 = \d -> case ds d of (a,b,c) -> a
458     -- And since ds is big, it doesn't get inlined, so we don't get good
459     -- default methods.  Better to make separate AbsBinds for each
460     
461     tc_dm op_item@(_, dm_id, _)
462       = tcInstTyVars tyvars             `thenNF_Tc` \ (clas_tyvars, inst_tys, _) ->
463         let
464             theta = [(mkClassPred clas inst_tys)]
465         in
466         newDicts origin theta                   `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
467         let
468             avail_insts = this_dict
469         in
470         tcExtendTyVarEnvForMeths tyvars clas_tyvars (
471             tcMethodBind clas origin clas_tyvars inst_tys theta
472                          default_binds prags False
473                          op_item
474         )                                       `thenTc` \ (defm_bind, insts_needed, (_, local_dm_id)) ->
475     
476         tcAddErrCtxt (defltMethCtxt clas) $
477     
478             -- tcMethodBind has checked that the class_tyvars havn't
479             -- been unified with each other or another type, but we must
480             -- still zonk them before passing them to tcSimplifyAndCheck
481         mapNF_Tc zonkTcTyVarBndr clas_tyvars    `thenNF_Tc` \ clas_tyvars' ->
482     
483             -- Check the context
484         tcSimplifyAndCheck
485             (ptext SLIT("class") <+> ppr clas)
486             (mkVarSet clas_tyvars')
487             avail_insts
488             insts_needed                        `thenTc` \ (const_lie, dict_binds) ->
489     
490         let
491             full_bind = AbsBinds
492                             clas_tyvars'
493                             [this_dict_id]
494                             [(clas_tyvars', dm_id, local_dm_id)]
495                             emptyNameSet        -- No inlines (yet)
496                             (dict_binds `andMonoBinds` defm_bind)
497         in
498         returnTc (full_bind, const_lie)
499 \end{code}
500
501 \begin{code}
502 checkFromThisClass :: Class -> [ClassOpItem] -> RenamedMonoBinds -> NF_TcM s ()
503 checkFromThisClass clas op_items mono_binds
504   = mapNF_Tc check_from_this_class bndrs        `thenNF_Tc_`
505     returnNF_Tc ()
506   where
507     check_from_this_class (bndr, loc)
508           | nameOccName bndr `elem` sel_names = returnNF_Tc ()
509           | otherwise                         = tcAddSrcLoc loc $
510                                                 addErrTc (badMethodErr bndr clas)
511     sel_names = [getOccName sel_id | (sel_id,_,_) <- op_items]
512     bndrs = bagToList (collectMonoBinders mono_binds)
513 \end{code}
514     
515
516 @tcMethodBind@ is used to type-check both default-method and
517 instance-decl method declarations.  We must type-check methods one at a
518 time, because their signatures may have different contexts and
519 tyvar sets.
520
521 \begin{code}
522 tcMethodBind 
523         :: Class
524         -> InstOrigin
525         -> [TcTyVar]            -- Instantiated type variables for the
526                                 --  enclosing class/instance decl. 
527                                 --  They'll be signature tyvars, and we
528                                 --  want to check that they don't get bound
529         -> [TcType]             -- Instance types
530         -> TcThetaType          -- Available theta; this could be used to check
531                                 --  the method signature, but actually that's done by
532                                 --  the caller;  here, it's just used for the error message
533         -> RenamedMonoBinds     -- Method binding (pick the right one from in here)
534         -> [RenamedSig]         -- Pramgas (just for this one)
535         -> Bool                 -- True <=> This method is from an instance declaration
536         -> ClassOpItem          -- The method selector and default-method Id
537         -> TcM s (TcMonoBinds, LIE, (LIE, TcId))
538
539 tcMethodBind clas origin inst_tyvars inst_tys inst_theta
540              meth_binds prags is_inst_decl
541              (sel_id, dm_id, explicit_dm)
542  = tcGetSrcLoc          `thenNF_Tc` \ loc -> 
543
544    newMethod origin sel_id inst_tys     `thenNF_Tc` \ meth@(_, meth_id) ->
545    mkTcSig meth_id loc                  `thenNF_Tc` \ sig_info -> 
546
547    let
548      meth_name       = idName meth_id
549      maybe_user_bind = find_bind meth_name meth_binds
550
551      no_user_bind    = case maybe_user_bind of {Nothing -> True; other -> False}
552
553      meth_bind = case maybe_user_bind of
554                         Just bind -> bind
555                         Nothing   -> mk_default_bind meth_name loc
556
557      meth_prags = find_prags meth_name prags
558    in
559
560         -- Warn if no method binding, only if -fwarn-missing-methods
561    warnTc (is_inst_decl && opt_WarnMissingMethods && no_user_bind && not explicit_dm)
562           (omittedMethodWarn sel_id clas)               `thenNF_Tc_`
563
564         -- Check the bindings; first add inst_tyvars to the envt
565         -- so that we don't quantify over them in nested places
566         -- The *caller* put the class/inst decl tyvars into the envt
567    tcExtendGlobalTyVars (mkVarSet inst_tyvars) (
568      tcAddErrCtxt (methodCtxt sel_id)           $
569      tcBindWithSigs NotTopLevel meth_bind 
570                     [sig_info] meth_prags NonRecursive 
571    )                                            `thenTc` \ (binds, insts, _) ->
572
573
574    tcExtendLocalValEnv [(meth_name, meth_id)] (
575         tcSpecSigs meth_prags
576    )                                            `thenTc` \ (prag_binds1, prag_lie) ->
577
578         -- The prag_lie for a SPECIALISE pragma will mention the function
579         -- itself, so we have to simplify them away right now lest they float
580         -- outwards!
581    bindInstsOfLocalFuns prag_lie [meth_id]      `thenTc` \ (prag_lie', prag_binds2) ->
582
583
584         -- Now check that the instance type variables
585         -- (or, in the case of a class decl, the class tyvars)
586         -- have not been unified with anything in the environment
587    tcAddErrCtxtM (sigCtxt sig_msg inst_tyvars inst_theta (idType meth_id))      $
588    checkSigTyVars inst_tyvars emptyVarSet                                       `thenTc_` 
589
590    returnTc (binds `AndMonoBinds` prag_binds1 `AndMonoBinds` prag_binds2, 
591              insts `plusLIE` prag_lie', 
592              meth)
593  where
594    sig_msg = ptext SLIT("When checking the expected type for class method") <+> ppr sel_name
595
596    sel_name = idName sel_id
597
598         -- The renamer just puts the selector ID as the binder in the method binding
599         -- but we must use the method name; so we substitute it here.  Crude but simple.
600    find_bind meth_name (FunMonoBind op_name fix matches loc)
601         | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
602    find_bind meth_name (AndMonoBinds b1 b2)
603                               = find_bind meth_name b1 `seqMaybe` find_bind meth_name b2
604    find_bind meth_name other  = Nothing -- Default case
605
606
607         -- Find the prags for this method, and replace the
608         -- selector name with the method name
609    find_prags meth_name [] = []
610    find_prags meth_name (SpecSig name ty loc : prags)
611         | name == sel_name = SpecSig meth_name ty loc : find_prags meth_name prags
612    find_prags meth_name (InlineSig name phase loc : prags)
613         | name == sel_name = InlineSig meth_name phase loc : find_prags meth_name prags
614    find_prags meth_name (NoInlineSig name phase loc : prags)
615         | name == sel_name = NoInlineSig meth_name phase loc : find_prags meth_name prags
616    find_prags meth_name (prag:prags) = find_prags meth_name prags
617
618    mk_default_bind local_meth_name loc
619       = FunMonoBind local_meth_name
620                     False       -- Not infix decl
621                     [mkSimpleMatch [] (default_expr loc) Nothing loc]
622                     loc
623
624    default_expr loc 
625         | explicit_dm = HsVar (getName dm_id)   -- There's a default method
626         | otherwise   = error_expr loc          -- No default method
627
628    error_expr loc = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID)) 
629                           (HsLit (HsString (_PK_ (error_msg loc))))
630
631    error_msg loc = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
632 \end{code}
633
634 Contexts and errors
635 ~~~~~~~~~~~~~~~~~~~
636 \begin{code}
637 classArityErr class_name
638   = ptext SLIT("Too many parameters for class") <+> quotes (ppr class_name)
639
640 superClassErr class_name sc
641   = ptext SLIT("Illegal superclass constraint") <+> quotes (ppr sc)
642     <+> ptext SLIT("in declaration for class") <+> quotes (ppr class_name)
643
644 defltMethCtxt class_name
645   = ptext SLIT("When checking the default methods for class") <+> quotes (ppr class_name)
646
647 methodCtxt sel_id
648   = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
649
650 badMethodErr bndr clas
651   = hsep [ptext SLIT("Class"), quotes (ppr clas), 
652           ptext SLIT("does not have a method"), quotes (ppr bndr)]
653
654 omittedMethodWarn sel_id clas
655   = sep [ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id), 
656          ptext SLIT("in an instance declaration for") <+> quotes (ppr clas)]
657 \end{code}