[project @ 2000-07-11 16:24:57 by simonmar]
[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 BasicTypes       ( NewOrData(..), TopLevelFlag(..), RecFlag(..) )
21 import RnHsSyn          ( RenamedTyClDecl, RenamedClassPragmas,
22                           RenamedClassOpSig, RenamedMonoBinds,
23                           RenamedContext, RenamedHsDecl, RenamedSig
24                         )
25 import TcHsSyn          ( TcMonoBinds, idsToMonoBinds )
26
27 import Inst             ( Inst, InstOrigin(..), LIE, emptyLIE, plusLIE, plusLIEs, newDicts, newMethod )
28 import TcEnv            ( TcId, ValueEnv, TcTyThing(..), tcAddImportedIdInfo,
29                           tcLookupTy, tcExtendTyVarEnvForMeths, tcExtendGlobalTyVars,
30                           tcExtendLocalValEnv
31                         )
32 import TcBinds          ( tcBindWithSigs, tcSpecSigs )
33 import TcTyDecls        ( mkNewTyConRep )
34 import TcMonad
35 import TcMonoType       ( kcHsType, tcHsTopType, tcExtendTopTyVarScope, 
36                           tcContext, checkSigTyVars, sigCtxt, mkTcSig
37                         )
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 )
50 import Outputable
51 import Type             ( Type, ThetaType, ClassContext,
52                           mkFunTy, mkTyVarTy, mkTyVarTys, mkDictTy, mkDictTys,
53                           mkSigmaTy, mkForAllTys, mkClassPred, classesOfPreds,
54                           boxedTypeKind, mkArrowKind
55                         )
56 import Var              ( tyVarKind, TyVar )
57 import VarSet           ( mkVarSet, emptyVarSet )
58 import TyCon            ( AlgTyConFlavour(..), mkClassTyCon )
59 import Maybes           ( seqMaybe )
60 import FiniteMap        ( lookupWithDefaultFM )
61 \end{code}
62
63
64
65 Dictionary handling
66 ~~~~~~~~~~~~~~~~~~~
67 Every class implicitly declares a new data type, corresponding to dictionaries
68 of that class. So, for example:
69
70         class (D a) => C a where
71           op1 :: a -> a
72           op2 :: forall b. Ord b => a -> b -> b
73
74 would implicitly declare
75
76         data CDict a = CDict (D a)      
77                              (a -> a)
78                              (forall b. Ord b => a -> b -> b)
79
80 (We could use a record decl, but that means changing more of the existing apparatus.
81 One step at at time!)
82
83 For classes with just one superclass+method, we use a newtype decl instead:
84
85         class C a where
86           op :: forallb. a -> b -> b
87
88 generates
89
90         newtype CDict a = CDict (forall b. a -> b -> b)
91
92 Now DictTy in Type is just a form of type synomym: 
93         DictTy c t = TyConTy CDict `AppTy` t
94
95 Death to "ExpandingDicts".
96
97
98 %************************************************************************
99 %*                                                                      *
100 \subsection{Kind checking}
101 %*                                                                      *
102 %************************************************************************
103
104 \begin{code}
105 kcClassDecl (ClassDecl  context class_name
106                         tyvar_names fundeps class_sigs def_methods pragmas
107                         _ _ _ _ src_loc)
108   =         -- CHECK ARITY 1 FOR HASKELL 1.4
109     checkTc (opt_GlasgowExts || length tyvar_names == 1)
110             (classArityErr class_name)          `thenTc_`
111
112         -- Get the (mutable) class kind
113     tcLookupTy class_name                       `thenNF_Tc` \ (kind, _) ->
114
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_`
120
121     returnTc ()
122   where
123     the_class_sigs = filter isClassOpSig class_sigs
124   
125     kc_sig (ClassOpSig _ _ _ op_ty loc) = tcAddSrcLoc loc (kcHsType op_ty)
126 \end{code}
127
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection{Type checking}
132 %*                                                                      *
133 %************************************************************************
134
135 \begin{code}
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
144         
145         -- CHECK THE CONTEXT
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_`
150
151         -- CHECK THE FUNCTIONAL DEPENDENCIES,
152     tcFundeps fundeps                           `thenTc` \ fds ->
153
154         -- CHECK THE CLASS SIGNATURES,
155     mapTc (tcClassSig rec_env rec_class tyvars) 
156           (filter isClassOpSig class_sigs)
157                                                 `thenTc` \ sig_stuff ->
158
159         -- MAKE THE CLASS OBJECT ITSELF
160     let
161         (op_tys, op_items) = unzip sig_stuff
162         clas = mkClass class_name tyvars fds
163                        sc_theta sc_sel_ids op_items
164                        tycon
165
166         dict_component_tys = sc_tys ++ op_tys
167         new_or_data = case dict_component_tys of
168                         [_]   -> NewTyCon (mkNewTyConRep tycon)
169                         other -> DataTyCon
170
171         dict_con = mkDataCon datacon_name
172                            [notMarkedStrict | _ <- dict_component_tys]
173                            [{- No labelled fields -}]
174                            tyvars
175                            [{-No context-}]
176                            [{-No existential tyvars-}] [{-Or context-}]
177                            dict_component_tys
178                            tycon dict_con_id dict_wrap_id
179
180         dict_con_id  = mkDataConId datacon_wkr_name dict_con
181         dict_wrap_id = mkDataConWrapId dict_con
182
183         argvrcs = lookupWithDefaultFM rec_vrcs (pprPanic "tcClassDecl1: argvrcs:" $
184                                                          ppr tycon_name)
185                                       tycon_name
186
187         tycon = mkClassTyCon tycon_name
188                              class_kind
189                              tyvars
190                              argvrcs
191                              dict_con           -- Constructors
192                              clas               -- Yes!  It's a dictionary 
193                              new_or_data
194     in
195     returnTc (class_name, AClass clas arity)
196 \end{code}
197
198 \begin{code}
199 tcFundeps = mapTc tc_fundep
200 tc_fundep (us, vs) =
201     mapTc tc_fd_tyvar us        `thenTc` \ us' ->
202     mapTc tc_fd_tyvar vs        `thenTc` \ vs' ->
203     returnTc (us', vs')
204 tc_fd_tyvar v =
205     tcLookupTy v         `thenTc` \(_, ATyVar tv) ->
206     returnTc tv
207 \end{code}
208
209 \begin{code}
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
216
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.
221
222         -- For std Haskell check that the context constrains only tyvars
223     (if opt_GlasgowExts then
224         returnTc []
225      else
226         mapTc check_constraint context
227     )                                   `thenTc_`
228
229     tcContext context                   `thenTc` \ sc_theta ->
230
231     let
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]
235     in
236         -- Done
237     returnTc (sc_theta', sc_tys, sc_sel_ids)
238
239   where
240     check_constraint sc@(HsPClass c tys) = checkTc (all is_tyvar tys)
241                                                    (superClassErr class_name sc)
242
243     is_tyvar (HsTyVar _) = True
244     is_tyvar other       = False
245
246
247 tcClassSig :: ValueEnv          -- Knot tying only!
248            -> Class                     -- ...ditto...
249            -> [TyVar]                   -- The class type variable, used for error check only
250            -> RenamedClassOpSig
251            -> TcM s (Type,              -- Type of the method
252                      ClassOpItem)       -- Selector Id, default-method Id, True if explicit default binding
253
254
255 tcClassSig rec_env rec_clas rec_clas_tyvars
256            (ClassOpSig op_name dm_name explicit_dm
257                        op_ty src_loc)
258   = tcAddSrcLoc src_loc $
259
260         -- Check the type signature.  NB that the envt *already has*
261         -- bindings for the type variables; see comments in TcTyAndClassDcls.
262
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 ->
267     let
268         global_ty   = mkSigmaTy rec_clas_tyvars 
269                                 [mkClassPred rec_clas (mkTyVarTys rec_clas_tyvars)]
270                                 local_ty
271
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
276     in
277 --  traceTc (text "tcClassSig done" <+> ppr op_name)    `thenTc_`
278     returnTc (local_ty, (sel_id, final_dm_id, explicit_dm))
279 \end{code}
280
281
282 %************************************************************************
283 %*                                                                      *
284 \subsection[ClassDcl-pass2]{Class decls pass 2: default methods}
285 %*                                                                      *
286 %************************************************************************
287
288 The purpose of pass 2 is
289 \begin{enumerate}
290 \item
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.)
294 \item
295 to produce a definition for the selector function for each method
296 and superclass dictionary.
297 \end{enumerate}
298
299 Pass~2 only applies to locally-defined class declarations.
300
301 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
302 each local class decl.
303
304 \begin{code}
305 tcClassDecls2 :: [RenamedHsDecl]
306               -> NF_TcM s (LIE, TcMonoBinds)
307
308 tcClassDecls2 decls
309   = foldr combine
310           (returnNF_Tc (emptyLIE, EmptyMonoBinds))
311           [tcClassDecl2 cls_decl | TyClD cls_decl <- decls, isClassDecl cls_decl]
312   where
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)
317 \end{code}
318
319 @tcClassDecl2@ is the business end of things.
320
321 \begin{code}
322 tcClassDecl2 :: RenamedTyClDecl         -- The class declaration
323              -> NF_TcM s (LIE, TcMonoBinds)
324
325 tcClassDecl2 (ClassDecl context class_name
326                         tyvar_names _ class_sigs default_binds pragmas _ _ _ _ src_loc)
327
328   | not (isLocallyDefined class_name)
329   = returnNF_Tc (emptyLIE, EmptyMonoBinds)
330
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
336 \end{code}
337
338 \begin{code}
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
343   where
344     (cls_ids_s, binds_s) = unzip (map mk_implicit classes)
345
346     mk_implicit clas = (all_cls_ids, binds)
347                      where
348                         dict_con    = classDataCon clas
349                         all_cls_ids = dataConId dict_con : cls_ids
350                         cls_ids     = dataConWrapId dict_con : classSelIds clas
351
352                         -- The wrapper and selectors get bindings, the worker does not
353                         binds | isLocallyDefined clas = idsToMonoBinds cls_ids
354                               | otherwise             = EmptyMonoBinds
355 \end{code}
356
357 %************************************************************************
358 %*                                                                      *
359 \subsection[Default methods]{Default methods}
360 %*                                                                      *
361 %************************************************************************
362
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
366 \begin{verbatim}
367 class Foo a where
368         op1 :: a -> Bool
369         op2 :: Ord b => a -> b -> b -> b
370
371         op1 x = True
372         op2 x y z = if (op1 x) && (y < z) then y else z
373 \end{verbatim}
374 we get the default methods:
375 \begin{verbatim}
376 defm.Foo.op1 :: forall a. Foo a => a -> Bool
377 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
378
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
382 \end{verbatim}
383
384 When we come across an instance decl, we may need to use the default
385 methods:
386 \begin{verbatim}
387 instance Foo Int where {}
388 \end{verbatim}
389 gives
390 \begin{verbatim}
391 const.Foo.Int.op1 :: Int -> Bool
392 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
393
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
396
397 dfun.Foo.Int :: Foo Int
398 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
399 \end{verbatim}
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).
403
404 \begin{verbatim}
405 instance Foo a => Foo [a] where {}
406
407 dfun.Foo.List :: forall a. Foo a -> Foo [a]
408 dfun.Foo.List
409   = /\ a -> \ dfoo_a ->
410     let rec
411         op1 = defm.Foo.op1 [a] dfoo_list
412         op2 = defm.Foo.op2 [a] dfoo_list
413         dfoo_list = (op1, op2)
414     in
415         dfoo_list
416 \end{verbatim}
417
418 \begin{code}
419 tcDefaultMethodBinds
420         :: Class
421         -> RenamedMonoBinds
422         -> [RenamedSig]
423         -> TcM s (LIE, TcMonoBinds)
424
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_`
428
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) ->
436
437     returnTc (plusLIEs const_lies, andMonoBindList defm_binds)
438   where
439     prags = filter isPragSig sigs
440
441     (tyvars, _, _, op_items) = classBigSig clas
442
443     origin = ClassDeclOrigin
444
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
453     
454     tc_dm op_item@(_, dm_id, _)
455       = tcInstTyVars tyvars             `thenNF_Tc` \ (clas_tyvars, inst_tys, _) ->
456         let
457             theta = [(mkClassPred clas inst_tys)]
458         in
459         newDicts origin theta                   `thenNF_Tc` \ (this_dict, [this_dict_id]) ->
460         let
461             avail_insts = this_dict
462         in
463         tcExtendTyVarEnvForMeths tyvars clas_tyvars (
464             tcMethodBind clas origin clas_tyvars inst_tys theta
465                          default_binds prags False
466                          op_item
467         )                                       `thenTc` \ (defm_bind, insts_needed, (_, local_dm_id)) ->
468     
469         tcAddErrCtxt (defltMethCtxt clas) $
470     
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' ->
475     
476             -- Check the context
477         tcSimplifyAndCheck
478             (ptext SLIT("class") <+> ppr clas)
479             (mkVarSet clas_tyvars')
480             avail_insts
481             insts_needed                        `thenTc` \ (const_lie, dict_binds) ->
482     
483         let
484             full_bind = AbsBinds
485                             clas_tyvars'
486                             [this_dict_id]
487                             [(clas_tyvars', dm_id, local_dm_id)]
488                             emptyNameSet        -- No inlines (yet)
489                             (dict_binds `andMonoBinds` defm_bind)
490         in
491         returnTc (full_bind, const_lie)
492 \end{code}
493
494 \begin{code}
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_`
498     returnNF_Tc ()
499   where
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)
506 \end{code}
507     
508
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
512 tyvar sets.
513
514 \begin{code}
515 tcMethodBind 
516         :: Class
517         -> InstOrigin
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))
531
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 -> 
536
537    newMethod origin sel_id inst_tys     `thenNF_Tc` \ meth@(_, meth_id) ->
538    mkTcSig meth_id loc                  `thenNF_Tc` \ sig_info -> 
539
540    let
541      meth_name       = idName meth_id
542      maybe_user_bind = find_bind meth_name meth_binds
543
544      no_user_bind    = case maybe_user_bind of {Nothing -> True; other -> False}
545
546      meth_bind = case maybe_user_bind of
547                         Just bind -> bind
548                         Nothing   -> mk_default_bind meth_name loc
549
550      meth_prags = find_prags meth_name prags
551    in
552
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_`
556
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, _) ->
565
566
567    tcExtendLocalValEnv [(meth_name, meth_id)] (
568         tcSpecSigs meth_prags
569    )                                            `thenTc` \ (prag_binds1, prag_lie) ->
570
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
573         -- outwards!
574    bindInstsOfLocalFuns prag_lie [meth_id]      `thenTc` \ (prag_lie', prag_binds2) ->
575
576
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_` 
582
583    returnTc (binds `AndMonoBinds` prag_binds1 `AndMonoBinds` prag_binds2, 
584              insts `plusLIE` prag_lie', 
585              meth)
586  where
587    sig_msg = ptext SLIT("When checking the expected type for class method") <+> ppr sel_name
588
589    sel_name = idName sel_id
590
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
598
599
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
610
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]
615                     loc
616
617    default_expr loc 
618         | explicit_dm = HsVar (getName dm_id)   -- There's a default method
619         | otherwise   = error_expr loc          -- No default method
620
621    error_expr loc = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID)) 
622                           (HsLit (HsString (_PK_ (error_msg loc))))
623
624    error_msg loc = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
625 \end{code}
626
627 Contexts and errors
628 ~~~~~~~~~~~~~~~~~~~
629 \begin{code}
630 classArityErr class_name
631   = ptext SLIT("Too many parameters for class") <+> quotes (ppr class_name)
632
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)
636
637 defltMethCtxt class_name
638   = ptext SLIT("When checking the default methods for class") <+> quotes (ppr class_name)
639
640 methodCtxt sel_id
641   = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
642
643 badMethodErr bndr clas
644   = hsep [ptext SLIT("Class"), quotes (ppr clas), 
645           ptext SLIT("does not have a method"), quotes (ppr bndr)]
646
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)]
650 \end{code}