[project @ 2003-06-27 21:17:24 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, tcExtendLocalValEnv2,
30                           tcExtendTyVarEnv2, tcExtendTyVarEnv
31                         )
32 import TcTyDecls        ( tcMkDataCon )
33 import TcBinds          ( tcMonoBinds, tcSpecSigs )
34 import TcMonoType       ( TcSigInfo(..), tcHsType, tcHsTheta, mkTcSig )
35 import TcSimplify       ( tcSimplifyCheck, bindInstsOfLocalFuns )
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         theta       = [mkClassPred clas inst_tys]
377         local_dm_id = mkDefaultMethodId dm_name dm_ty
378         xtve        = tyvars `zip` clas_tyvars
379     in
380     newDicts origin theta                               `thenM` \ [this_dict] ->
381
382     mkMethodBind origin clas inst_tys binds_in op_item  `thenM` \ (_, meth_info) ->
383     getLIE (tcMethodBind xtve clas_tyvars theta 
384                          [this_dict] prags meth_info)   `thenM` \ (defm_bind, insts_needed) ->
385     
386     addErrCtxt (defltMethCtxt clas) $
387     
388         -- Check the context
389     tcSimplifyCheck
390         (ptext SLIT("class") <+> ppr clas)
391         clas_tyvars
392         [this_dict]
393         insts_needed                    `thenM` \ dict_binds ->
394
395         -- Simplification can do unification
396     checkSigTyVars clas_tyvars          `thenM` \ clas_tyvars' ->
397     
398     let
399         (_,dm_inst_id,_) = meth_info
400         full_bind = AbsBinds
401                     clas_tyvars'
402                     [instToId this_dict]
403                     [(clas_tyvars', local_dm_id, dm_inst_id)]
404                     emptyNameSet        -- No inlines (yet)
405                     (dict_binds `andMonoBinds` defm_bind)
406     in
407     returnM (full_bind, [local_dm_id])
408   where
409     origin = ClassDeclOrigin
410 \end{code}
411
412     
413
414 %************************************************************************
415 %*                                                                      *
416 \subsection{Typechecking a method}
417 %*                                                                      *
418 %************************************************************************
419
420 @tcMethodBind@ is used to type-check both default-method and
421 instance-decl method declarations.  We must type-check methods one at a
422 time, because their signatures may have different contexts and
423 tyvar sets.
424
425 \begin{code}
426 type MethodSpec = (Id,                  -- Global selector Id
427                    Id,                  -- Local Id (class tyvars instantiated)
428                    RenamedMonoBinds)    -- Binding for the method
429
430 tcMethodBind 
431         :: [(TyVar,TcTyVar)]    -- Bindings for type environment
432         -> [TcTyVar]            -- Instantiated type variables for the
433                                 --      enclosing class/instance decl. 
434                                 --      They'll be signature tyvars, and we
435                                 --      want to check that they don't get bound
436                                 -- Always equal the range of the type envt
437         -> TcThetaType          -- Available theta; it's just used for the error message
438         -> [Inst]               -- Available from context, used to simplify constraints 
439                                 --      from the method body
440         -> [RenamedSig]         -- Pragmas (e.g. inline pragmas)
441         -> MethodSpec           -- Details of this method
442         -> TcM TcMonoBinds
443
444 tcMethodBind xtve inst_tyvars inst_theta avail_insts prags
445              (sel_id, meth_id, meth_bind)
446   =     -- Check the bindings; first adding inst_tyvars to the envt
447         -- so that we don't quantify over them in nested places
448      mkTcSig meth_id                            `thenM` \ meth_sig ->
449
450      tcExtendTyVarEnv2 xtve (
451         addErrCtxt (methodCtxt sel_id)                  $
452         getLIE                                          $
453         tcMonoBinds meth_bind [meth_sig] NonRecursive
454      )                                                  `thenM` \ ((meth_bind,_), meth_lie) ->
455
456         -- Now do context reduction.   We simplify wrt both the local tyvars
457         -- and the ones of the class/instance decl, so that there is
458         -- no problem with
459         --      class C a where
460         --        op :: Eq a => a -> b -> a
461         --
462         -- We do this for each method independently to localise error messages
463
464      let
465         TySigInfo meth_id meth_tvs meth_theta _ local_meth_id _ _ = meth_sig
466      in
467      addErrCtxtM (sigCtxt sel_id inst_tyvars inst_theta (idType meth_id))       $
468      newDicts SignatureOrigin meth_theta        `thenM` \ meth_dicts ->
469      let
470         all_tyvars = meth_tvs ++ inst_tyvars
471         all_insts  = avail_insts ++ meth_dicts
472      in
473      tcSimplifyCheck
474          (ptext SLIT("class or instance method") <+> quotes (ppr sel_id))
475          all_tyvars all_insts meth_lie          `thenM` \ lie_binds ->
476
477      checkSigTyVars all_tyvars                  `thenM` \ all_tyvars' ->
478
479      let
480         sel_name = idName sel_id
481         inline_prags  = [ (is_inl, phase)
482                         | InlineSig is_inl name phase _ <- prags, 
483                           name == sel_name ]
484         spec_prags = [ prag 
485                      | prag@(SpecSig name _ _) <- prags, 
486                        name == sel_name]
487         
488                 -- Attach inline pragmas as appropriate
489         (final_meth_id, inlines) 
490            | ((is_inline, phase) : _) <- inline_prags
491            = (meth_id `setInlinePragma` phase,
492               if is_inline then unitNameSet (idName meth_id) else emptyNameSet)
493            | otherwise
494            = (meth_id, emptyNameSet)
495
496         meth_tvs'      = take (length meth_tvs) all_tyvars'
497         poly_meth_bind = AbsBinds meth_tvs'
498                                   (map instToId meth_dicts)
499                                   [(meth_tvs', final_meth_id, local_meth_id)]
500                                   inlines
501                                   (lie_binds `andMonoBinds` meth_bind)
502
503      in
504         -- Deal with specialisation pragmas
505         -- The sel_name is what appears in the pragma
506      tcExtendLocalValEnv2 [(sel_name, final_meth_id)] (
507         getLIE (tcSpecSigs spec_prags)                  `thenM` \ (spec_binds1, prag_lie) ->
508      
509              -- The prag_lie for a SPECIALISE pragma will mention the function itself, 
510              -- so we have to simplify them away right now lest they float outwards!
511         bindInstsOfLocalFuns prag_lie [final_meth_id]   `thenM` \ spec_binds2 ->
512         returnM (spec_binds1 `andMonoBinds` spec_binds2)
513      )                                                  `thenM` \ spec_binds ->
514
515      returnM (poly_meth_bind `andMonoBinds` spec_binds)
516
517
518 mkMethodBind :: InstOrigin
519              -> Class -> [TcType]       -- Class and instance types
520              -> RenamedMonoBinds        -- Method binding (pick the right one from in here)
521              -> ClassOpItem
522              -> TcM (Maybe Inst,                -- Method inst
523                      MethodSpec)
524 -- Find the binding for the specified method, or make
525 -- up a suitable default method if it isn't there
526
527 mkMethodBind origin clas inst_tys meth_binds (sel_id, dm_info)
528   = mkMethId origin clas sel_id inst_tys                `thenM` \ (mb_inst, meth_id) ->
529     let
530         meth_name  = idName meth_id
531     in
532         -- Figure out what method binding to use
533         -- If the user suppplied one, use it, else construct a default one
534     getSrcLocM                                  `thenM` \ loc -> 
535     (case find_bind (idName sel_id) meth_name meth_binds of
536         Just user_bind -> returnM user_bind 
537         Nothing        -> mkDefMethRhs origin clas inst_tys sel_id loc dm_info  `thenM` \ rhs ->
538                           returnM (FunMonoBind meth_name False  -- Not infix decl
539                                                [mkSimpleMatch [] rhs placeHolderType loc] loc)
540     )                                                           `thenM` \ meth_bind ->
541
542     returnM (mb_inst, (sel_id, meth_id, meth_bind))
543
544 mkMethId :: InstOrigin -> Class 
545          -> Id -> [TcType]      -- Selector, and instance types
546          -> TcM (Maybe Inst, Id)
547              
548 -- mkMethId instantiates the selector Id at the specified types
549 mkMethId origin clas sel_id inst_tys
550   = let
551         (tyvars,rho) = tcSplitForAllTys (idType sel_id)
552         rho_ty       = ASSERT( length tyvars == length inst_tys )
553                        substTyWith tyvars inst_tys rho
554         (preds,tau)  = tcSplitPhiTy rho_ty
555         first_pred   = head preds
556     in
557         -- The first predicate should be of form (C a b)
558         -- where C is the class in question
559     ASSERT( not (null preds) && 
560             case getClassPredTys_maybe first_pred of
561                 { Just (clas1,tys) -> clas == clas1 ; Nothing -> False }
562     )
563     if isSingleton preds then
564         -- If it's the only one, make a 'method'
565         getInstLoc origin                               `thenM` \ inst_loc ->
566         newMethod inst_loc sel_id inst_tys preds tau    `thenM` \ meth_inst ->
567         returnM (Just meth_inst, instToId meth_inst)
568     else
569         -- If it's not the only one we need to be careful
570         -- For example, given 'op' defined thus:
571         --      class Foo a where
572         --        op :: (?x :: String) => a -> a
573         -- (mkMethId op T) should return an Inst with type
574         --      (?x :: String) => T -> T
575         -- That is, the class-op's context is still there.  
576         -- BUT: it can't be a Method any more, because it breaks
577         --      INVARIANT 2 of methods.  (See the data decl for Inst.)
578         newUnique                       `thenM` \ uniq ->
579         getSrcLocM                      `thenM` \ loc ->
580         let 
581             real_tau = mkPhiTy (tail preds) tau
582             meth_id  = mkUserLocal (getOccName sel_id) uniq real_tau loc
583         in
584         returnM (Nothing, meth_id)
585
586      -- The user didn't supply a method binding, 
587      -- so we have to make up a default binding
588      -- The RHS of a default method depends on the default-method info
589 mkDefMethRhs origin clas inst_tys sel_id loc (DefMeth dm_name)
590   =  -- An polymorphic default method
591     traceRn (text "mkDefMeth" <+> ppr dm_name)  `thenM_`
592     returnM (HsVar dm_name)
593
594 mkDefMethRhs origin clas inst_tys sel_id loc NoDefMeth
595   =     -- No default method
596         -- Warn only if -fwarn-missing-methods
597     doptM Opt_WarnMissingMethods                `thenM` \ warn -> 
598     warnTc (isInstDecl origin
599            && warn
600            && reportIfUnused (getOccName sel_id))
601            (omittedMethodWarn sel_id)           `thenM_`
602     returnM error_rhs
603   where
604     error_rhs  = HsLam (mkSimpleMatch wild_pats simple_rhs placeHolderType loc)
605     simple_rhs = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID)) 
606                        (HsLit (HsStringPrim (mkFastString (stringToUtf8 error_msg))))
607     error_msg = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
608
609         -- When the type is of form t1 -> t2 -> t3
610         -- make a default method like (\ _ _ -> noMethBind "blah")
611         -- rather than simply        (noMethBind "blah")
612         -- Reason: if t1 or t2 are higher-ranked types we get n
613         --         silly ambiguity messages.
614         -- Example:     f :: (forall a. Eq a => a -> a) -> Int
615         --              f = error "urk"
616         -- Here, tcSub tries to force (error "urk") to have the right type,
617         -- thus:        f = \(x::forall a. Eq a => a->a) -> error "urk" (x t)
618         -- where 't' is fresh ty var.  This leads directly to "ambiguous t".
619         -- 
620         -- NB: technically this changes the meaning of the default-default
621         --     method slightly, because `seq` can see the lambdas.  Oh well.
622     (_,_,tau1)    = tcSplitSigmaTy (idType sel_id)
623     (_,_,tau2)    = tcSplitSigmaTy tau1
624         -- Need two splits because the  selector can have a type like
625         --      forall a. Foo a => forall b. Eq b => ...
626     (arg_tys, _) = tcSplitFunTys tau2
627     wild_pats    = [WildPat placeHolderType | ty <- arg_tys]
628
629 mkDefMethRhs origin clas inst_tys sel_id loc GenDefMeth 
630   =     -- A generic default method
631         -- If the method is defined generically, we can only do the job if the
632         -- instance declaration is for a single-parameter type class with
633         -- a type constructor applied to type arguments in the instance decl
634         --      (checkTc, so False provokes the error)
635      ASSERT( isInstDecl origin )        -- We never get here from a class decl
636
637      checkTc (isJust maybe_tycon)
638              (badGenericInstance sel_id (notSimple inst_tys))           `thenM_`
639      checkTc (isJust (tyConGenInfo tycon))
640              (badGenericInstance sel_id (notGeneric tycon))             `thenM_`
641
642      ioToTcRn (dumpIfSet opt_PprStyle_Debug "Generic RHS" stuff)        `thenM_`
643      returnM rhs
644   where
645     rhs = mkGenericRhs sel_id clas_tyvar tycon
646
647     stuff = vcat [ppr clas <+> ppr inst_tys,
648                   nest 4 (ppr sel_id <+> equals <+> ppr rhs)]
649
650           -- The tycon is only used in the generic case, and in that
651           -- case we require that the instance decl is for a single-parameter
652           -- type class with type variable arguments:
653           --    instance (...) => C (T a b)
654     clas_tyvar    = head (classTyVars clas)
655     Just tycon    = maybe_tycon
656     maybe_tycon   = case inst_tys of 
657                         [ty] -> case tcSplitTyConApp_maybe ty of
658                                   Just (tycon, arg_tys) | all tcIsTyVarTy arg_tys -> Just tycon
659                                   other                                           -> Nothing
660                         other -> Nothing
661
662 isInstDecl InstanceDeclOrigin = True
663 isInstDecl ClassDeclOrigin    = False
664 \end{code}
665
666
667 \begin{code}
668 -- The renamer just puts the selector ID as the binder in the method binding
669 -- but we must use the method name; so we substitute it here.  Crude but simple.
670 find_bind sel_name meth_name (FunMonoBind op_name fix matches loc)
671     | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
672 find_bind sel_name meth_name (AndMonoBinds b1 b2)
673     = find_bind sel_name meth_name b1 `seqMaybe` find_bind sel_name meth_name b2
674 find_bind sel_name meth_name other  = Nothing   -- Default case
675
676  -- Find the prags for this method, and replace the
677  -- selector name with the method name
678 find_prags sel_name meth_name [] = []
679 find_prags sel_name meth_name (SpecSig name ty loc : prags) 
680      | name == sel_name = SpecSig meth_name ty loc : find_prags sel_name meth_name prags
681 find_prags sel_name meth_name (InlineSig sense name phase loc : prags)
682    | name == sel_name = InlineSig sense meth_name phase loc : find_prags sel_name meth_name prags
683 find_prags sel_name meth_name (prag:prags) = find_prags sel_name meth_name prags
684 \end{code}
685
686
687 Contexts and errors
688 ~~~~~~~~~~~~~~~~~~~
689 \begin{code}
690 defltMethCtxt clas
691   = ptext SLIT("When checking the default methods for class") <+> quotes (ppr clas)
692
693 methodCtxt sel_id
694   = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
695
696 badMethodErr clas op
697   = hsep [ptext SLIT("Class"), quotes (ppr clas), 
698           ptext SLIT("does not have a method"), quotes (ppr op)]
699
700 omittedMethodWarn sel_id
701   = ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id)
702
703 badGenericInstance sel_id because
704   = sep [ptext SLIT("Can't derive generic code for") <+> quotes (ppr sel_id),
705          because]
706
707 notSimple inst_tys
708   = vcat [ptext SLIT("because the instance type(s)"), 
709           nest 2 (ppr inst_tys),
710           ptext SLIT("is not a simple type of form (T a b c)")]
711
712 notGeneric tycon
713   = vcat [ptext SLIT("because the instance type constructor") <+> quotes (ppr tycon) <+> 
714           ptext SLIT("was not compiled with -fgenerics")]
715
716 mixedGenericErr op
717   = ptext SLIT("Can't mix generic and non-generic equations for class method") <+> quotes (ppr op)
718 \end{code}