[project @ 2003-02-21 13:27:53 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 ( tcClassDecl1, tcClassDecls2, 
8                     MethodSpec, tcMethodBind, mkMethodBind, badMethodErr
9                   ) where
10
11 #include "HsVersions.h"
12
13 import HsSyn            ( TyClDecl(..), Sig(..), MonoBinds(..),
14                           HsExpr(..), HsLit(..), Pat(WildPat),
15                           mkSimpleMatch, andMonoBinds, andMonoBindList, 
16                           isClassOpSig, isPragSig, 
17                           placeHolderType
18                         )
19 import BasicTypes       ( RecFlag(..) )
20 import RnHsSyn          ( RenamedTyClDecl, RenamedSig,
21                           RenamedClassOpSig, RenamedMonoBinds,
22                           maybeGenericMatch
23                         )
24 import RnEnv            ( lookupSysName )
25 import TcHsSyn          ( TcMonoBinds )
26
27 import Inst             ( Inst, InstOrigin(..), instToId, newDicts, newMethod )
28 import TcEnv            ( TyThingDetails(..), 
29                           tcLookupClass, tcExtendTyVarEnv2, 
30                           tcExtendTyVarEnv
31                         )
32 import TcTyDecls        ( tcMkDataCon )
33 import TcBinds          ( tcMonoBinds )
34 import TcMonoType       ( TcSigInfo(..), tcHsType, tcHsTheta, mkTcSig )
35 import TcSimplify       ( tcSimplifyCheck )
36 import TcUnify          ( checkSigTyVars, sigCtxt )
37 import TcMType          ( tcInstTyVars )
38 import TcType           ( Type, TyVarDetails(..), TcType, TcThetaType, TcTyVar, 
39                           mkTyVarTys, mkPredTys, mkClassPred, tcSplitSigmaTy, tcSplitFunTys,
40                           tcIsTyVarTy, tcSplitTyConApp_maybe, tcSplitForAllTys, tcSplitPhiTy,
41                           getClassPredTys_maybe, mkPhiTy
42                         )
43 import TcRnMonad
44 import Generics         ( mkGenericRhs )
45 import PrelInfo         ( nO_METHOD_BINDING_ERROR_ID )
46 import Class            ( classTyVars, classBigSig, classTyCon, 
47                           Class, ClassOpItem, DefMeth (..) )
48 import TyCon            ( tyConGenInfo )
49 import Subst            ( substTyWith )
50 import MkId             ( mkDictSelId, mkDefaultMethodId )
51 import Id               ( Id, idType, idName, mkUserLocal, setInlinePragma )
52 import Name             ( Name, NamedThing(..) )
53 import NameEnv          ( NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, plusNameEnv )
54 import NameSet          ( emptyNameSet, unitNameSet )
55 import OccName          ( mkClassTyConOcc, mkClassDataConOcc, mkSuperDictSelOcc, reportIfUnused )
56 import Outputable
57 import Var              ( TyVar )
58 import CmdLineOpts
59 import UnicodeUtil      ( stringToUtf8 )
60 import ErrUtils         ( dumpIfSet )
61 import Util             ( count, lengthIs, isSingleton )
62 import Maybes           ( seqMaybe )
63 import Maybe            ( isJust )
64 import FastString
65 \end{code}
66
67
68
69 Dictionary handling
70 ~~~~~~~~~~~~~~~~~~~
71 Every class implicitly declares a new data type, corresponding to dictionaries
72 of that class. So, for example:
73
74         class (D a) => C a where
75           op1 :: a -> a
76           op2 :: forall b. Ord b => a -> b -> b
77
78 would implicitly declare
79
80         data CDict a = CDict (D a)      
81                              (a -> a)
82                              (forall b. Ord b => a -> b -> b)
83
84 (We could use a record decl, but that means changing more of the existing apparatus.
85 One step at at time!)
86
87 For classes with just one superclass+method, we use a newtype decl instead:
88
89         class C a where
90           op :: forallb. a -> b -> b
91
92 generates
93
94         newtype CDict a = CDict (forall b. a -> b -> b)
95
96 Now DictTy in Type is just a form of type synomym: 
97         DictTy c t = TyConTy CDict `AppTy` t
98
99 Death to "ExpandingDicts".
100
101
102 %************************************************************************
103 %*                                                                      *
104 \subsection{Type checking}
105 %*                                                                      *
106 %************************************************************************
107
108 \begin{code}
109
110 tcClassDecl1 :: RenamedTyClDecl -> TcM (Name, TyThingDetails)
111 tcClassDecl1 (ClassDecl {tcdCtxt = context, tcdName = class_name,
112                          tcdTyVars = tyvar_names, tcdFDs = fundeps,
113                          tcdSigs = class_sigs, tcdMeths = def_methods,
114                          tcdLoc = src_loc})
115   =     -- LOOK THINGS UP IN THE ENVIRONMENT
116     tcLookupClass class_name                            `thenM` \ clas ->
117     let
118         tyvars     = classTyVars clas
119         op_sigs    = filter isClassOpSig class_sigs
120         op_names   = [n | ClassOpSig n _ _ _ <- op_sigs]
121     in
122     tcExtendTyVarEnv tyvars                             $ 
123
124     checkDefaultBinds clas op_names def_methods         `thenM` \ mb_dm_env ->
125         
126         -- CHECK THE CONTEXT
127         -- The renamer has already checked that the context mentions
128         -- only the type variable of the class decl.
129         -- Context is already kind-checked
130     tcHsTheta context                                   `thenM` \ sc_theta ->
131
132         -- CHECK THE CLASS SIGNATURES,
133     mappM (tcClassSig clas tyvars mb_dm_env) op_sigs    `thenM` \ sig_stuff ->
134
135         -- MAKE THE CLASS DETAILS
136     lookupSysName class_name mkClassTyConOcc            `thenM` \ tycon_name ->
137     lookupSysName class_name mkClassDataConOcc          `thenM` \ datacon_name ->
138     mapM (lookupSysName class_name . mkSuperDictSelOcc) 
139          [1..length context]                            `thenM` \ sc_sel_names ->
140       -- We number off the superclass selectors, 1, 2, 3 etc so that we 
141       -- can construct names for the selectors.  Thus
142       --      class (C a, C b) => D a b where ...
143       -- gives superclass selectors
144       --      D_sc1, D_sc2
145       -- (We used to call them D_C, but now we can have two different
146       --  superclasses both called C!)
147     let
148         (op_tys, op_items) = unzip sig_stuff
149         sc_tys             = mkPredTys sc_theta
150         dict_component_tys = sc_tys ++ op_tys
151         sc_sel_ids         = [mkDictSelId sc_name clas | sc_name <- sc_sel_names]
152     in
153     tcMkDataCon datacon_name
154                 [{- No strictness -}]
155                 [{- No labelled fields -}]
156                 tyvars [{-No context-}]
157                 [{-No existential tyvars-}] [{-Or context-}]
158                 dict_component_tys
159                 (classTyCon clas)                       `thenM` \ dict_con ->
160
161     returnM (class_name, ClassDetails sc_theta sc_sel_ids op_items dict_con tycon_name)
162 \end{code}
163
164 \begin{code}
165 checkDefaultBinds :: Class -> [Name] -> Maybe RenamedMonoBinds
166                   -> TcM (Maybe (NameEnv Bool))
167         -- The returned environment says
168         --      x not in env => no default method
169         --      x -> True    => generic default method
170         --      x -> False   => polymorphic default method
171
172   -- Check default bindings
173   --    a) must be for a class op for this class
174   --    b) must be all generic or all non-generic
175   -- and return a mapping from class-op to DefMeth info
176
177   -- But do all this only for source binds
178
179 checkDefaultBinds clas ops Nothing
180   = returnM Nothing
181
182 checkDefaultBinds clas ops (Just mbs)
183   = go mbs      `thenM` \ dm_env ->
184     returnM (Just dm_env)
185   where
186     go EmptyMonoBinds = returnM emptyNameEnv
187
188     go (AndMonoBinds b1 b2)
189       = go b1   `thenM` \ dm_info1 ->
190         go b2   `thenM` \ dm_info2 ->
191         returnM (dm_info1 `plusNameEnv` dm_info2)
192
193     go (FunMonoBind op _ matches loc)
194       = addSrcLoc loc                                   $
195
196         -- Check that the op is from this class
197         checkTc (op `elem` ops) (badMethodErr clas op)          `thenM_`
198
199         -- Check that all the defns ar generic, or none are
200         checkTc (all_generic || none_generic) (mixedGenericErr op)      `thenM_`
201
202         returnM (unitNameEnv op all_generic)
203       where
204         n_generic    = count (isJust . maybeGenericMatch) matches
205         none_generic = n_generic == 0
206         all_generic  = matches `lengthIs` n_generic
207 \end{code}
208
209
210 \begin{code}
211 tcClassSig :: Class                     -- ...ditto...
212            -> [TyVar]                   -- The class type variable, used for error check only
213            -> Maybe (NameEnv Bool)      -- Info about default methods; 
214                                         --      Nothing => imported class defn with no method binds
215            -> RenamedClassOpSig
216            -> TcM (Type,                -- Type of the method
217                      ClassOpItem)       -- Selector Id, default-method Id, True if explicit default binding
218
219 -- This warrants an explanation: we need to separate generic
220 -- default methods and default methods later on in the compiler
221 -- so we distinguish them in checkDefaultBinds, and pass this knowledge in the
222 -- Class.DefMeth data structure. 
223
224 tcClassSig clas clas_tyvars maybe_dm_env
225            (ClassOpSig op_name sig_dm op_ty src_loc)
226   = addSrcLoc src_loc $
227
228         -- Check the type signature.  NB that the envt *already has*
229         -- bindings for the type variables; see comments in TcTyAndClassDcls.
230     tcHsType op_ty                      `thenM` \ local_ty ->
231
232     let
233         theta = [mkClassPred clas (mkTyVarTys clas_tyvars)]
234
235         -- Build the selector id and default method id
236         sel_id = mkDictSelId op_name clas
237         DefMeth dm_name = sig_dm
238
239         dm_info = case maybe_dm_env of
240                     Nothing     -> sig_dm
241                     Just dm_env -> mk_src_dm_info dm_env
242
243         mk_src_dm_info dm_env = case lookupNameEnv dm_env op_name of
244                                    Nothing    -> NoDefMeth
245                                    Just True  -> GenDefMeth
246                                    Just False -> DefMeth dm_name
247     in
248     returnM (local_ty, (sel_id, dm_info))
249 \end{code}
250
251
252 %************************************************************************
253 %*                                                                      *
254 \subsection[Default methods]{Default methods}
255 %*                                                                      *
256 %************************************************************************
257
258 The default methods for a class are each passed a dictionary for the
259 class, so that they get access to the other methods at the same type.
260 So, given the class decl
261 \begin{verbatim}
262 class Foo a where
263         op1 :: a -> Bool
264         op2 :: Ord b => a -> b -> b -> b
265
266         op1 x = True
267         op2 x y z = if (op1 x) && (y < z) then y else z
268 \end{verbatim}
269 we get the default methods:
270 \begin{verbatim}
271 defm.Foo.op1 :: forall a. Foo a => a -> Bool
272 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
273
274 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
275 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
276                   if (op1 a dfoo x) && (< b dord y z) then y else z
277 \end{verbatim}
278
279 When we come across an instance decl, we may need to use the default
280 methods:
281 \begin{verbatim}
282 instance Foo Int where {}
283 \end{verbatim}
284 gives
285 \begin{verbatim}
286 const.Foo.Int.op1 :: Int -> Bool
287 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
288
289 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
290 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
291
292 dfun.Foo.Int :: Foo Int
293 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
294 \end{verbatim}
295 Notice that, as with method selectors above, we assume that dictionary
296 application is curried, so there's no need to mention the Ord dictionary
297 in const.Foo.Int.op2 (or the type variable).
298
299 \begin{verbatim}
300 instance Foo a => Foo [a] where {}
301
302 dfun.Foo.List :: forall a. Foo a -> Foo [a]
303 dfun.Foo.List
304   = /\ a -> \ dfoo_a ->
305     let rec
306         op1 = defm.Foo.op1 [a] dfoo_list
307         op2 = defm.Foo.op2 [a] dfoo_list
308         dfoo_list = (op1, op2)
309     in
310         dfoo_list
311 \end{verbatim}
312
313 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
314 each local class decl.
315
316 \begin{code}
317 tcClassDecls2 :: [RenamedTyClDecl] -> TcM (TcMonoBinds, [Id])
318
319 tcClassDecls2 decls
320   = foldr combine
321           (returnM (EmptyMonoBinds, []))
322           [tcClassDecl2 cls_decl | cls_decl@(ClassDecl {tcdMeths = Just _}) <- decls] 
323                 -- The 'Just' picks out source ClassDecls
324   where
325     combine tc1 tc2 = tc1 `thenM` \ (binds1, ids1) ->
326                       tc2 `thenM` \ (binds2, ids2) ->
327                       returnM (binds1 `AndMonoBinds` binds2,
328                                ids1 ++ ids2)
329 \end{code}
330
331 @tcClassDecl2@ generates bindings for polymorphic default methods
332 (generic default methods have by now turned into instance declarations)
333
334 \begin{code}
335 tcClassDecl2 :: RenamedTyClDecl         -- The class declaration
336              -> TcM (TcMonoBinds, [Id])
337
338 tcClassDecl2 (ClassDecl {tcdName = class_name, tcdSigs = sigs, 
339                          tcdMeths = Just default_binds, tcdLoc = src_loc})
340   =     -- The 'Just' picks out source ClassDecls
341     recoverM (returnM (EmptyMonoBinds, []))     $ 
342     addSrcLoc src_loc                                   $
343     tcLookupClass class_name                            `thenM` \ clas ->
344
345         -- We make a separate binding for each default method.
346         -- At one time I used a single AbsBinds for all of them, thus
347         -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
348         -- But that desugars into
349         --      ds = \d -> (..., ..., ...)
350         --      dm1 = \d -> case ds d of (a,b,c) -> a
351         -- And since ds is big, it doesn't get inlined, so we don't get good
352         -- default methods.  Better to make separate AbsBinds for each
353     let
354         (tyvars, _, _, op_items) = classBigSig clas
355         prags                    = filter isPragSig sigs
356         tc_dm                    = tcDefMeth clas tyvars default_binds prags
357     in
358     mapAndUnzipM tc_dm op_items `thenM` \ (defm_binds, dm_ids_s) ->
359
360     returnM (andMonoBindList defm_binds, concat dm_ids_s)
361     
362
363 tcDefMeth clas tyvars binds_in prags (_, NoDefMeth)  = returnM (EmptyMonoBinds, [])
364 tcDefMeth clas tyvars binds_in prags (_, GenDefMeth) = returnM (EmptyMonoBinds, [])
365         -- Generate code for polymorphic default methods only
366         -- (Generic default methods have turned into instance decls by now.)
367         -- This is incompatible with Hugs, which expects a polymorphic 
368         -- default method for every class op, regardless of whether or not 
369         -- the programmer supplied an explicit default decl for the class.  
370         -- (If necessary we can fix that, but we don't have a convenient Id to hand.)
371
372 tcDefMeth clas tyvars binds_in prags op_item@(sel_id, DefMeth dm_name)
373   = tcInstTyVars ClsTv tyvars           `thenM` \ (clas_tyvars, inst_tys, _) ->
374     let
375         dm_ty = idType sel_id   -- Same as dict selector!
376           -- The default method's type should really come from the
377           -- iface file, since it could be usage-generalised, but this
378           -- requires altering the mess of knots in TcModule and I'm
379           -- too scared to do that.  Instead, I have disabled generalisation
380           -- of types of default methods (and dict funs) by annotating them
381           -- TyGenNever (in MkId).  Ugh!  KSW 1999-09.
382
383         theta       = [mkClassPred clas inst_tys]
384         local_dm_id = mkDefaultMethodId dm_name dm_ty
385         xtve        = tyvars `zip` clas_tyvars
386     in
387     newDicts origin theta                               `thenM` \ [this_dict] ->
388
389     mkMethodBind origin clas inst_tys binds_in op_item  `thenM` \ (_, meth_info) ->
390     getLIE (tcMethodBind xtve clas_tyvars theta 
391                          [this_dict] prags meth_info)   `thenM` \ (defm_bind, insts_needed) ->
392     
393     addErrCtxt (defltMethCtxt clas) $
394     
395         -- Check the context
396     tcSimplifyCheck
397         (ptext SLIT("class") <+> ppr clas)
398         clas_tyvars
399         [this_dict]
400         insts_needed                    `thenM` \ dict_binds ->
401
402         -- Simplification can do unification
403     checkSigTyVars clas_tyvars          `thenM` \ clas_tyvars' ->
404     
405     let
406         (_,dm_inst_id,_) = meth_info
407         full_bind = AbsBinds
408                     clas_tyvars'
409                     [instToId this_dict]
410                     [(clas_tyvars', local_dm_id, dm_inst_id)]
411                     emptyNameSet        -- No inlines (yet)
412                     (dict_binds `andMonoBinds` defm_bind)
413     in
414     returnM (full_bind, [local_dm_id])
415   where
416     origin = ClassDeclOrigin
417 \end{code}
418
419     
420
421 %************************************************************************
422 %*                                                                      *
423 \subsection{Typechecking a method}
424 %*                                                                      *
425 %************************************************************************
426
427 @tcMethodBind@ is used to type-check both default-method and
428 instance-decl method declarations.  We must type-check methods one at a
429 time, because their signatures may have different contexts and
430 tyvar sets.
431
432 \begin{code}
433 type MethodSpec = (Id,                  -- Global selector Id
434                    Id,                  -- Local Id (class tyvars instantiated)
435                    RenamedMonoBinds)    -- Binding for the method
436
437 tcMethodBind 
438         :: [(TyVar,TcTyVar)]    -- Bindings for type environment
439         -> [TcTyVar]            -- Instantiated type variables for the
440                                 --      enclosing class/instance decl. 
441                                 --      They'll be signature tyvars, and we
442                                 --      want to check that they don't get bound
443                                 -- Always equal the range of the type envt
444         -> TcThetaType          -- Available theta; it's just used for the error message
445         -> [Inst]               -- Available from context, used to simplify constraints 
446                                 --      from the method body
447         -> [RenamedSig]         -- Pragmas (e.g. inline pragmas)
448         -> MethodSpec           -- Details of this method
449         -> TcM TcMonoBinds
450
451 tcMethodBind xtve inst_tyvars inst_theta avail_insts prags
452              (sel_id, meth_id, meth_bind)
453   =     -- Check the bindings; first adding inst_tyvars to the envt
454         -- so that we don't quantify over them in nested places
455     mkTcSig meth_id                             `thenM` \ meth_sig ->
456
457      tcExtendTyVarEnv2 xtve (
458         addErrCtxt (methodCtxt sel_id)          $
459         getLIE (tcMonoBinds meth_bind [meth_sig] NonRecursive)
460      )                                          `thenM` \ ((meth_bind, _, _), meth_lie) ->
461
462         -- Now do context reduction.   We simplify wrt both the local tyvars
463         -- and the ones of the class/instance decl, so that there is
464         -- no problem with
465         --      class C a where
466         --        op :: Eq a => a -> b -> a
467         --
468         -- We do this for each method independently to localise error messages
469
470      let
471         TySigInfo meth_id meth_tvs meth_theta _ local_meth_id _ _ = meth_sig
472      in
473      addErrCtxtM (sigCtxt sel_id inst_tyvars inst_theta (idType meth_id))       $
474      newDicts SignatureOrigin meth_theta        `thenM` \ meth_dicts ->
475      let
476         all_tyvars = meth_tvs ++ inst_tyvars
477         all_insts  = avail_insts ++ meth_dicts
478      in
479      tcSimplifyCheck
480          (ptext SLIT("class or instance method") <+> quotes (ppr sel_id))
481          all_tyvars all_insts meth_lie          `thenM` \ lie_binds ->
482
483      checkSigTyVars all_tyvars                  `thenM` \ all_tyvars' ->
484
485      let
486                 -- Attach inline pragmas as appropriate
487         (final_meth_id, inlines) 
488            | (InlineSig inl _ phase _ : _) <- filter is_inline prags
489            = (meth_id `setInlinePragma` phase,
490               if inl then unitNameSet (idName meth_id) else emptyNameSet)
491            | otherwise
492            = (meth_id, emptyNameSet)
493
494         is_inline (InlineSig _ name _ _) = name == idName sel_id
495         is_inline other                  = False
496
497         meth_tvs'      = take (length meth_tvs) all_tyvars'
498         poly_meth_bind = AbsBinds meth_tvs'
499                                   (map instToId meth_dicts)
500                                   [(meth_tvs', final_meth_id, local_meth_id)]
501                                   inlines
502                                   (lie_binds `andMonoBinds` meth_bind)
503      in
504      returnM poly_meth_bind
505
506
507 mkMethodBind :: InstOrigin
508              -> Class -> [TcType]       -- Class and instance types
509              -> RenamedMonoBinds        -- Method binding (pick the right one from in here)
510              -> ClassOpItem
511              -> TcM (Maybe Inst,                -- Method inst
512                      MethodSpec)
513 -- Find the binding for the specified method, or make
514 -- up a suitable default method if it isn't there
515
516 mkMethodBind origin clas inst_tys meth_binds (sel_id, dm_info)
517   = mkMethId origin clas sel_id inst_tys                `thenM` \ (mb_inst, meth_id) ->
518     let
519         meth_name  = idName meth_id
520     in
521         -- Figure out what method binding to use
522         -- If the user suppplied one, use it, else construct a default one
523     getSrcLocM                                  `thenM` \ loc -> 
524     (case find_bind (idName sel_id) meth_name meth_binds of
525         Just user_bind -> returnM user_bind 
526         Nothing        -> mkDefMethRhs origin clas inst_tys sel_id loc dm_info  `thenM` \ rhs ->
527                           returnM (FunMonoBind meth_name False  -- Not infix decl
528                                                [mkSimpleMatch [] rhs placeHolderType loc] loc)
529     )                                                           `thenM` \ meth_bind ->
530
531     returnM (mb_inst, (sel_id, meth_id, meth_bind))
532
533 mkMethId :: InstOrigin -> Class 
534          -> Id -> [TcType]      -- Selector, and instance types
535          -> TcM (Maybe Inst, Id)
536              
537 -- mkMethId instantiates the selector Id at the specified types
538 mkMethId origin clas sel_id inst_tys
539   = let
540         (tyvars,rho) = tcSplitForAllTys (idType sel_id)
541         rho_ty       = ASSERT( length tyvars == length inst_tys )
542                        substTyWith tyvars inst_tys rho
543         (preds,tau)  = tcSplitPhiTy rho_ty
544         first_pred   = head preds
545     in
546         -- The first predicate should be of form (C a b)
547         -- where C is the class in question
548     ASSERT( not (null preds) && 
549             case getClassPredTys_maybe first_pred of
550                 { Just (clas1,tys) -> clas == clas1 ; Nothing -> False }
551     )
552     if isSingleton preds then
553         -- If it's the only one, make a 'method'
554         getInstLoc origin                               `thenM` \ inst_loc ->
555         newMethod inst_loc sel_id inst_tys preds tau    `thenM` \ meth_inst ->
556         returnM (Just meth_inst, instToId meth_inst)
557     else
558         -- If it's not the only one we need to be careful
559         -- For example, given 'op' defined thus:
560         --      class Foo a where
561         --        op :: (?x :: String) => a -> a
562         -- (mkMethId op T) should return an Inst with type
563         --      (?x :: String) => T -> T
564         -- That is, the class-op's context is still there.  
565         -- BUT: it can't be a Method any more, because it breaks
566         --      INVARIANT 2 of methods.  (See the data decl for Inst.)
567         newUnique                       `thenM` \ uniq ->
568         getSrcLocM                      `thenM` \ loc ->
569         let 
570             real_tau = mkPhiTy (tail preds) tau
571             meth_id  = mkUserLocal (getOccName sel_id) uniq real_tau loc
572         in
573         returnM (Nothing, meth_id)
574
575      -- The user didn't supply a method binding, 
576      -- so we have to make up a default binding
577      -- The RHS of a default method depends on the default-method info
578 mkDefMethRhs origin clas inst_tys sel_id loc (DefMeth dm_name)
579   =  -- An polymorphic default method
580     traceRn (text "mkDefMeth" <+> ppr dm_name)  `thenM_`
581     returnM (HsVar dm_name)
582
583 mkDefMethRhs origin clas inst_tys sel_id loc NoDefMeth
584   =     -- No default method
585         -- Warn only if -fwarn-missing-methods
586     doptM Opt_WarnMissingMethods                `thenM` \ warn -> 
587     warnTc (isInstDecl origin
588            && warn
589            && reportIfUnused (getOccName sel_id))
590            (omittedMethodWarn sel_id)           `thenM_`
591     returnM error_rhs
592   where
593     error_rhs  = HsLam (mkSimpleMatch wild_pats simple_rhs placeHolderType loc)
594     simple_rhs = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID)) 
595                        (HsLit (HsStringPrim (mkFastString (stringToUtf8 error_msg))))
596     error_msg = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
597
598         -- When the type is of form t1 -> t2 -> t3
599         -- make a default method like (\ _ _ -> noMethBind "blah")
600         -- rather than simply        (noMethBind "blah")
601         -- Reason: if t1 or t2 are higher-ranked types we get n
602         --         silly ambiguity messages.
603         -- Example:     f :: (forall a. Eq a => a -> a) -> Int
604         --              f = error "urk"
605         -- Here, tcSub tries to force (error "urk") to have the right type,
606         -- thus:        f = \(x::forall a. Eq a => a->a) -> error "urk" (x t)
607         -- where 't' is fresh ty var.  This leads directly to "ambiguous t".
608         -- 
609         -- NB: technically this changes the meaning of the default-default
610         --     method slightly, because `seq` can see the lambdas.  Oh well.
611     (_,_,tau1)    = tcSplitSigmaTy (idType sel_id)
612     (_,_,tau2)    = tcSplitSigmaTy tau1
613         -- Need two splits because the  selector can have a type like
614         --      forall a. Foo a => forall b. Eq b => ...
615     (arg_tys, _) = tcSplitFunTys tau2
616     wild_pats    = [WildPat placeHolderType | ty <- arg_tys]
617
618 mkDefMethRhs origin clas inst_tys sel_id loc GenDefMeth 
619   =     -- A generic default method
620         -- If the method is defined generically, we can only do the job if the
621         -- instance declaration is for a single-parameter type class with
622         -- a type constructor applied to type arguments in the instance decl
623         --      (checkTc, so False provokes the error)
624      ASSERT( isInstDecl origin )        -- We never get here from a class decl
625
626      checkTc (isJust maybe_tycon)
627              (badGenericInstance sel_id (notSimple inst_tys))           `thenM_`
628      checkTc (isJust (tyConGenInfo tycon))
629              (badGenericInstance sel_id (notGeneric tycon))             `thenM_`
630
631      ioToTcRn (dumpIfSet opt_PprStyle_Debug "Generic RHS" stuff)        `thenM_`
632      returnM rhs
633   where
634     rhs = mkGenericRhs sel_id clas_tyvar tycon
635
636     stuff = vcat [ppr clas <+> ppr inst_tys,
637                   nest 4 (ppr sel_id <+> equals <+> ppr rhs)]
638
639           -- The tycon is only used in the generic case, and in that
640           -- case we require that the instance decl is for a single-parameter
641           -- type class with type variable arguments:
642           --    instance (...) => C (T a b)
643     clas_tyvar    = head (classTyVars clas)
644     Just tycon    = maybe_tycon
645     maybe_tycon   = case inst_tys of 
646                         [ty] -> case tcSplitTyConApp_maybe ty of
647                                   Just (tycon, arg_tys) | all tcIsTyVarTy arg_tys -> Just tycon
648                                   other                                           -> Nothing
649                         other -> Nothing
650
651 isInstDecl InstanceDeclOrigin = True
652 isInstDecl ClassDeclOrigin    = False
653 \end{code}
654
655
656 \begin{code}
657 -- The renamer just puts the selector ID as the binder in the method binding
658 -- but we must use the method name; so we substitute it here.  Crude but simple.
659 find_bind sel_name meth_name (FunMonoBind op_name fix matches loc)
660     | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
661 find_bind sel_name meth_name (AndMonoBinds b1 b2)
662     = find_bind sel_name meth_name b1 `seqMaybe` find_bind sel_name meth_name b2
663 find_bind sel_name meth_name other  = Nothing   -- Default case
664
665  -- Find the prags for this method, and replace the
666  -- selector name with the method name
667 find_prags sel_name meth_name [] = []
668 find_prags sel_name meth_name (SpecSig name ty loc : prags) 
669      | name == sel_name = SpecSig meth_name ty loc : find_prags sel_name meth_name prags
670 find_prags sel_name meth_name (InlineSig sense name phase loc : prags)
671    | name == sel_name = InlineSig sense meth_name phase loc : find_prags sel_name meth_name prags
672 find_prags sel_name meth_name (prag:prags) = find_prags sel_name meth_name prags
673 \end{code}
674
675
676 Contexts and errors
677 ~~~~~~~~~~~~~~~~~~~
678 \begin{code}
679 defltMethCtxt clas
680   = ptext SLIT("When checking the default methods for class") <+> quotes (ppr clas)
681
682 methodCtxt sel_id
683   = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
684
685 badMethodErr clas op
686   = hsep [ptext SLIT("Class"), quotes (ppr clas), 
687           ptext SLIT("does not have a method"), quotes (ppr op)]
688
689 omittedMethodWarn sel_id
690   = ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id)
691
692 badGenericInstance sel_id because
693   = sep [ptext SLIT("Can't derive generic code for") <+> quotes (ppr sel_id),
694          because]
695
696 notSimple inst_tys
697   = vcat [ptext SLIT("because the instance type(s)"), 
698           nest 2 (ppr inst_tys),
699           ptext SLIT("is not a simple type of form (T a b c)")]
700
701 notGeneric tycon
702   = vcat [ptext SLIT("because the instance type constructor") <+> quotes (ppr tycon) <+> 
703           ptext SLIT("was not compiled with -fgenerics")]
704
705 mixedGenericErr op
706   = ptext SLIT("Can't mix generic and non-generic equations for class method") <+> quotes (ppr op)
707 \end{code}