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