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