[project @ 2003-03-27 08:21:27 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           -- 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                                          $
460         tcMonoBinds meth_bind [meth_sig] NonRecursive
461      )                                                  `thenM` \ ((meth_bind,_), meth_lie) ->
462
463         -- Now do context reduction.   We simplify wrt both the local tyvars
464         -- and the ones of the class/instance decl, so that there is
465         -- no problem with
466         --      class C a where
467         --        op :: Eq a => a -> b -> a
468         --
469         -- We do this for each method independently to localise error messages
470
471      let
472         TySigInfo meth_id meth_tvs meth_theta _ local_meth_id _ _ = meth_sig
473      in
474      addErrCtxtM (sigCtxt sel_id inst_tyvars inst_theta (idType meth_id))       $
475      newDicts SignatureOrigin meth_theta        `thenM` \ meth_dicts ->
476      let
477         all_tyvars = meth_tvs ++ inst_tyvars
478         all_insts  = avail_insts ++ meth_dicts
479      in
480      tcSimplifyCheck
481          (ptext SLIT("class or instance method") <+> quotes (ppr sel_id))
482          all_tyvars all_insts meth_lie          `thenM` \ lie_binds ->
483
484      checkSigTyVars all_tyvars                  `thenM` \ all_tyvars' ->
485
486      let
487         sel_name = idName sel_id
488         inline_prags  = [ (is_inl, phase)
489                         | InlineSig is_inl name phase _ <- prags, 
490                           name == sel_name ]
491         spec_prags = [ prag 
492                      | prag@(SpecSig name _ _) <- prags, 
493                        name == sel_name]
494         
495                 -- Attach inline pragmas as appropriate
496         (final_meth_id, inlines) 
497            | ((is_inline, phase) : _) <- inline_prags
498            = (meth_id `setInlinePragma` phase,
499               if is_inline then unitNameSet (idName meth_id) else emptyNameSet)
500            | otherwise
501            = (meth_id, emptyNameSet)
502
503         meth_tvs'      = take (length meth_tvs) all_tyvars'
504         poly_meth_bind = AbsBinds meth_tvs'
505                                   (map instToId meth_dicts)
506                                   [(meth_tvs', final_meth_id, local_meth_id)]
507                                   inlines
508                                   (lie_binds `andMonoBinds` meth_bind)
509
510      in
511         -- Deal with specialisation pragmas
512         -- The sel_name is what appears in the pragma
513      tcExtendLocalValEnv2 [(sel_name, final_meth_id)] (
514         getLIE (tcSpecSigs spec_prags)                  `thenM` \ (spec_binds1, prag_lie) ->
515      
516              -- The prag_lie for a SPECIALISE pragma will mention the function itself, 
517              -- so we have to simplify them away right now lest they float outwards!
518         bindInstsOfLocalFuns prag_lie [final_meth_id]   `thenM` \ spec_binds2 ->
519         returnM (spec_binds1 `andMonoBinds` spec_binds2)
520      )                                                  `thenM` \ spec_binds ->
521
522      returnM (poly_meth_bind `andMonoBinds` spec_binds)
523
524
525 mkMethodBind :: InstOrigin
526              -> Class -> [TcType]       -- Class and instance types
527              -> RenamedMonoBinds        -- Method binding (pick the right one from in here)
528              -> ClassOpItem
529              -> TcM (Maybe Inst,                -- Method inst
530                      MethodSpec)
531 -- Find the binding for the specified method, or make
532 -- up a suitable default method if it isn't there
533
534 mkMethodBind origin clas inst_tys meth_binds (sel_id, dm_info)
535   = mkMethId origin clas sel_id inst_tys                `thenM` \ (mb_inst, meth_id) ->
536     let
537         meth_name  = idName meth_id
538     in
539         -- Figure out what method binding to use
540         -- If the user suppplied one, use it, else construct a default one
541     getSrcLocM                                  `thenM` \ loc -> 
542     (case find_bind (idName sel_id) meth_name meth_binds of
543         Just user_bind -> returnM user_bind 
544         Nothing        -> mkDefMethRhs origin clas inst_tys sel_id loc dm_info  `thenM` \ rhs ->
545                           returnM (FunMonoBind meth_name False  -- Not infix decl
546                                                [mkSimpleMatch [] rhs placeHolderType loc] loc)
547     )                                                           `thenM` \ meth_bind ->
548
549     returnM (mb_inst, (sel_id, meth_id, meth_bind))
550
551 mkMethId :: InstOrigin -> Class 
552          -> Id -> [TcType]      -- Selector, and instance types
553          -> TcM (Maybe Inst, Id)
554              
555 -- mkMethId instantiates the selector Id at the specified types
556 mkMethId origin clas sel_id inst_tys
557   = let
558         (tyvars,rho) = tcSplitForAllTys (idType sel_id)
559         rho_ty       = ASSERT( length tyvars == length inst_tys )
560                        substTyWith tyvars inst_tys rho
561         (preds,tau)  = tcSplitPhiTy rho_ty
562         first_pred   = head preds
563     in
564         -- The first predicate should be of form (C a b)
565         -- where C is the class in question
566     ASSERT( not (null preds) && 
567             case getClassPredTys_maybe first_pred of
568                 { Just (clas1,tys) -> clas == clas1 ; Nothing -> False }
569     )
570     if isSingleton preds then
571         -- If it's the only one, make a 'method'
572         getInstLoc origin                               `thenM` \ inst_loc ->
573         newMethod inst_loc sel_id inst_tys preds tau    `thenM` \ meth_inst ->
574         returnM (Just meth_inst, instToId meth_inst)
575     else
576         -- If it's not the only one we need to be careful
577         -- For example, given 'op' defined thus:
578         --      class Foo a where
579         --        op :: (?x :: String) => a -> a
580         -- (mkMethId op T) should return an Inst with type
581         --      (?x :: String) => T -> T
582         -- That is, the class-op's context is still there.  
583         -- BUT: it can't be a Method any more, because it breaks
584         --      INVARIANT 2 of methods.  (See the data decl for Inst.)
585         newUnique                       `thenM` \ uniq ->
586         getSrcLocM                      `thenM` \ loc ->
587         let 
588             real_tau = mkPhiTy (tail preds) tau
589             meth_id  = mkUserLocal (getOccName sel_id) uniq real_tau loc
590         in
591         returnM (Nothing, meth_id)
592
593      -- The user didn't supply a method binding, 
594      -- so we have to make up a default binding
595      -- The RHS of a default method depends on the default-method info
596 mkDefMethRhs origin clas inst_tys sel_id loc (DefMeth dm_name)
597   =  -- An polymorphic default method
598     traceRn (text "mkDefMeth" <+> ppr dm_name)  `thenM_`
599     returnM (HsVar dm_name)
600
601 mkDefMethRhs origin clas inst_tys sel_id loc NoDefMeth
602   =     -- No default method
603         -- Warn only if -fwarn-missing-methods
604     doptM Opt_WarnMissingMethods                `thenM` \ warn -> 
605     warnTc (isInstDecl origin
606            && warn
607            && reportIfUnused (getOccName sel_id))
608            (omittedMethodWarn sel_id)           `thenM_`
609     returnM error_rhs
610   where
611     error_rhs  = HsLam (mkSimpleMatch wild_pats simple_rhs placeHolderType loc)
612     simple_rhs = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID)) 
613                        (HsLit (HsStringPrim (mkFastString (stringToUtf8 error_msg))))
614     error_msg = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
615
616         -- When the type is of form t1 -> t2 -> t3
617         -- make a default method like (\ _ _ -> noMethBind "blah")
618         -- rather than simply        (noMethBind "blah")
619         -- Reason: if t1 or t2 are higher-ranked types we get n
620         --         silly ambiguity messages.
621         -- Example:     f :: (forall a. Eq a => a -> a) -> Int
622         --              f = error "urk"
623         -- Here, tcSub tries to force (error "urk") to have the right type,
624         -- thus:        f = \(x::forall a. Eq a => a->a) -> error "urk" (x t)
625         -- where 't' is fresh ty var.  This leads directly to "ambiguous t".
626         -- 
627         -- NB: technically this changes the meaning of the default-default
628         --     method slightly, because `seq` can see the lambdas.  Oh well.
629     (_,_,tau1)    = tcSplitSigmaTy (idType sel_id)
630     (_,_,tau2)    = tcSplitSigmaTy tau1
631         -- Need two splits because the  selector can have a type like
632         --      forall a. Foo a => forall b. Eq b => ...
633     (arg_tys, _) = tcSplitFunTys tau2
634     wild_pats    = [WildPat placeHolderType | ty <- arg_tys]
635
636 mkDefMethRhs origin clas inst_tys sel_id loc GenDefMeth 
637   =     -- A generic default method
638         -- If the method is defined generically, we can only do the job if the
639         -- instance declaration is for a single-parameter type class with
640         -- a type constructor applied to type arguments in the instance decl
641         --      (checkTc, so False provokes the error)
642      ASSERT( isInstDecl origin )        -- We never get here from a class decl
643
644      checkTc (isJust maybe_tycon)
645              (badGenericInstance sel_id (notSimple inst_tys))           `thenM_`
646      checkTc (isJust (tyConGenInfo tycon))
647              (badGenericInstance sel_id (notGeneric tycon))             `thenM_`
648
649      ioToTcRn (dumpIfSet opt_PprStyle_Debug "Generic RHS" stuff)        `thenM_`
650      returnM rhs
651   where
652     rhs = mkGenericRhs sel_id clas_tyvar tycon
653
654     stuff = vcat [ppr clas <+> ppr inst_tys,
655                   nest 4 (ppr sel_id <+> equals <+> ppr rhs)]
656
657           -- The tycon is only used in the generic case, and in that
658           -- case we require that the instance decl is for a single-parameter
659           -- type class with type variable arguments:
660           --    instance (...) => C (T a b)
661     clas_tyvar    = head (classTyVars clas)
662     Just tycon    = maybe_tycon
663     maybe_tycon   = case inst_tys of 
664                         [ty] -> case tcSplitTyConApp_maybe ty of
665                                   Just (tycon, arg_tys) | all tcIsTyVarTy arg_tys -> Just tycon
666                                   other                                           -> Nothing
667                         other -> Nothing
668
669 isInstDecl InstanceDeclOrigin = True
670 isInstDecl ClassDeclOrigin    = False
671 \end{code}
672
673
674 \begin{code}
675 -- The renamer just puts the selector ID as the binder in the method binding
676 -- but we must use the method name; so we substitute it here.  Crude but simple.
677 find_bind sel_name meth_name (FunMonoBind op_name fix matches loc)
678     | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
679 find_bind sel_name meth_name (AndMonoBinds b1 b2)
680     = find_bind sel_name meth_name b1 `seqMaybe` find_bind sel_name meth_name b2
681 find_bind sel_name meth_name other  = Nothing   -- Default case
682
683  -- Find the prags for this method, and replace the
684  -- selector name with the method name
685 find_prags sel_name meth_name [] = []
686 find_prags sel_name meth_name (SpecSig name ty loc : prags) 
687      | name == sel_name = SpecSig meth_name ty loc : find_prags sel_name meth_name prags
688 find_prags sel_name meth_name (InlineSig sense name phase loc : prags)
689    | name == sel_name = InlineSig sense meth_name phase loc : find_prags sel_name meth_name prags
690 find_prags sel_name meth_name (prag:prags) = find_prags sel_name meth_name prags
691 \end{code}
692
693
694 Contexts and errors
695 ~~~~~~~~~~~~~~~~~~~
696 \begin{code}
697 defltMethCtxt clas
698   = ptext SLIT("When checking the default methods for class") <+> quotes (ppr clas)
699
700 methodCtxt sel_id
701   = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
702
703 badMethodErr clas op
704   = hsep [ptext SLIT("Class"), quotes (ppr clas), 
705           ptext SLIT("does not have a method"), quotes (ppr op)]
706
707 omittedMethodWarn sel_id
708   = ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id)
709
710 badGenericInstance sel_id because
711   = sep [ptext SLIT("Can't derive generic code for") <+> quotes (ppr sel_id),
712          because]
713
714 notSimple inst_tys
715   = vcat [ptext SLIT("because the instance type(s)"), 
716           nest 2 (ppr inst_tys),
717           ptext SLIT("is not a simple type of form (T a b c)")]
718
719 notGeneric tycon
720   = vcat [ptext SLIT("because the instance type constructor") <+> quotes (ppr tycon) <+> 
721           ptext SLIT("was not compiled with -fgenerics")]
722
723 mixedGenericErr op
724   = ptext SLIT("Can't mix generic and non-generic equations for class method") <+> quotes (ppr op)
725 \end{code}