[project @ 2003-10-09 11:58:39 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 ( tcClassSigs, tcClassDecl2, 
8                     getGenericInstances, 
9                     MethodSpec, tcMethodBind, mkMethodBind, 
10                     tcAddDeclCtxt, badMethodErr
11                   ) where
12
13 #include "HsVersions.h"
14
15 import HsSyn            ( TyClDecl(..), Sig(..), MonoBinds(..), HsType(..),
16                           HsExpr(..), HsLit(..), Pat(WildPat), HsTyVarBndr(..),
17                           mkSimpleMatch, andMonoBinds, andMonoBindList, 
18                           isPragSig, placeHolderType, mkHsForAllTy
19                         )
20 import BasicTypes       ( RecFlag(..), NewOrData(..) )
21 import RnHsSyn          ( RenamedTyClDecl, RenamedSig,
22                           RenamedClassOpSig, RenamedMonoBinds,
23                           maybeGenericMatch, extractHsTyVars
24                         )
25 import RnExpr           ( rnExpr )
26 import RnEnv            ( lookupTopBndrRn, lookupImportedName )
27 import TcHsSyn          ( TcMonoBinds )
28
29 import Inst             ( Inst, InstOrigin(..), instToId, newDicts, newMethod )
30 import TcEnv            ( tcLookupClass, tcExtendLocalValEnv2, tcExtendTyVarEnv2,
31                           InstInfo(..), pprInstInfo, simpleInstInfoTyCon, simpleInstInfoTy,
32                           InstBindings(..), newDFunName
33                         )
34 import TcBinds          ( tcMonoBinds, tcSpecSigs )
35 import TcHsType         ( TcSigInfo(..), mkTcSig, tcHsKindedType, tcHsSigType )
36 import TcSimplify       ( tcSimplifyCheck, bindInstsOfLocalFuns )
37 import TcUnify          ( checkSigTyVars, sigCtxt )
38 import TcMType          ( tcInstTyVars, UserTypeCtxt( GenPatCtxt ) )
39 import TcType           ( Type, TyVarDetails(..), TcType, TcThetaType, TcTyVar, 
40                           mkClassPred, tcSplitSigmaTy, tcSplitFunTys,
41                           tcIsTyVarTy, tcSplitTyConApp_maybe, tcSplitForAllTys, tcSplitPhiTy,
42                           getClassPredTys_maybe, mkPhiTy, mkTyVarTy
43                         )
44 import TcRnMonad
45 import Generics         ( mkGenericRhs, validGenericInstanceType )
46 import PrelInfo         ( nO_METHOD_BINDING_ERROR_ID )
47 import Class            ( classTyVars, classBigSig, 
48                           Class, ClassOpItem, DefMeth (..) )
49 import TyCon            ( TyCon, tyConName, tyConHasGenerics )
50 import Subst            ( substTyWith )
51 import MkId             ( mkDefaultMethodId, mkDictFunId )
52 import Id               ( Id, idType, idName, mkUserLocal, setInlinePragma )
53 import Name             ( Name, NamedThing(..) )
54 import NameEnv          ( NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, plusNameEnv )
55 import NameSet          ( emptyNameSet, unitNameSet, nameSetToList )
56 import OccName          ( reportIfUnused, mkDefaultMethodOcc )
57 import RdrName          ( RdrName, mkDerivedRdrName )
58 import Outputable
59 import Var              ( TyVar )
60 import PrelNames        ( genericTyConNames )
61 import CmdLineOpts
62 import UnicodeUtil      ( stringToUtf8 )
63 import ErrUtils         ( dumpIfSet, dumpIfSet_dyn )
64 import Util             ( count, lengthIs, isSingleton, lengthExceeds )
65 import Unique           ( Uniquable(..) )
66 import ListSetOps       ( equivClassesByUniq, minusList )
67 import SrcLoc           ( SrcLoc )
68 import Maybes           ( seqMaybe, isJust, mapCatMaybes )
69 import List             ( partition )
70 import FastString
71 \end{code}
72
73
74
75 Dictionary handling
76 ~~~~~~~~~~~~~~~~~~~
77 Every class implicitly declares a new data type, corresponding to dictionaries
78 of that class. So, for example:
79
80         class (D a) => C a where
81           op1 :: a -> a
82           op2 :: forall b. Ord b => a -> b -> b
83
84 would implicitly declare
85
86         data CDict a = CDict (D a)      
87                              (a -> a)
88                              (forall b. Ord b => a -> b -> b)
89
90 (We could use a record decl, but that means changing more of the existing apparatus.
91 One step at at time!)
92
93 For classes with just one superclass+method, we use a newtype decl instead:
94
95         class C a where
96           op :: forallb. a -> b -> b
97
98 generates
99
100         newtype CDict a = CDict (forall b. a -> b -> b)
101
102 Now DictTy in Type is just a form of type synomym: 
103         DictTy c t = TyConTy CDict `AppTy` t
104
105 Death to "ExpandingDicts".
106
107
108 %************************************************************************
109 %*                                                                      *
110                 Type-checking the class op signatures
111 %*                                                                      *
112 %************************************************************************
113
114 \begin{code}
115 tcClassSigs :: Name                     -- Name of the class
116             -> [RenamedClassOpSig]
117             -> RenamedMonoBinds
118             -> TcM [TcMethInfo]
119
120 type TcMethInfo = (Name, DefMeth, Type) -- A temporary intermediate, to communicate 
121                                         -- between tcClassSigs and buildClass
122 tcClassSigs clas sigs def_methods
123   = do { dm_env <- checkDefaultBinds clas op_names def_methods
124        ; mappM (tcClassSig dm_env) op_sigs }
125   where
126     op_sigs  = [sig | sig@(Sig n _ _) <- sigs]
127     op_names = [n   | sig@(Sig n _ _) <- op_sigs]
128
129     
130 checkDefaultBinds :: Name -> [Name] -> RenamedMonoBinds
131                   -> TcM (NameEnv Bool)
132   -- Check default bindings
133   --    a) must be for a class op for this class
134   --    b) must be all generic or all non-generic
135   -- and return a mapping from class-op to Bool
136   --    where True <=> it's a generic default method
137
138 checkDefaultBinds clas ops EmptyMonoBinds 
139   = returnM emptyNameEnv
140
141 checkDefaultBinds clas ops (AndMonoBinds b1 b2)
142   = do  { dm_info1 <- checkDefaultBinds clas ops b1
143         ; dm_info2 <- checkDefaultBinds clas ops b2
144         ; returnM (dm_info1 `plusNameEnv` dm_info2) }
145
146 checkDefaultBinds clas ops (FunMonoBind op _ matches loc)
147   = addSrcLoc loc  $ do 
148     {   -- Check that the op is from this class
149         checkTc (op `elem` ops) (badMethodErr clas op)
150
151         -- Check that all the defns ar generic, or none are
152     ;   checkTc (all_generic || none_generic) (mixedGenericErr op)
153
154     ;   returnM (unitNameEnv op all_generic)
155     }
156   where
157     n_generic    = count (isJust . maybeGenericMatch) matches
158     none_generic = n_generic == 0
159     all_generic  = matches `lengthIs` n_generic
160
161
162 tcClassSig :: NameEnv Bool              -- Info about default methods; 
163            -> RenamedClassOpSig
164            -> TcM TcMethInfo
165
166 tcClassSig dm_env (Sig op_name op_hs_ty src_loc)
167   = addSrcLoc src_loc $ do
168     { op_ty <- tcHsKindedType op_hs_ty  -- Class tyvars already in scope
169     ; let dm = case lookupNameEnv dm_env op_name of
170                 Nothing    -> NoDefMeth
171                 Just False -> DefMeth
172                 Just True  -> GenDefMeth
173     ; returnM (op_name, dm, op_ty) }
174 \end{code}
175
176
177 %************************************************************************
178 %*                                                                      *
179 \subsection[Default methods]{Default methods}
180 %*                                                                      *
181 %************************************************************************
182
183 The default methods for a class are each passed a dictionary for the
184 class, so that they get access to the other methods at the same type.
185 So, given the class decl
186 \begin{verbatim}
187 class Foo a where
188         op1 :: a -> Bool
189         op2 :: Ord b => a -> b -> b -> b
190
191         op1 x = True
192         op2 x y z = if (op1 x) && (y < z) then y else z
193 \end{verbatim}
194 we get the default methods:
195 \begin{verbatim}
196 defm.Foo.op1 :: forall a. Foo a => a -> Bool
197 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
198
199 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
200 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
201                   if (op1 a dfoo x) && (< b dord y z) then y else z
202 \end{verbatim}
203
204 When we come across an instance decl, we may need to use the default
205 methods:
206 \begin{verbatim}
207 instance Foo Int where {}
208 \end{verbatim}
209 gives
210 \begin{verbatim}
211 const.Foo.Int.op1 :: Int -> Bool
212 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
213
214 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
215 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
216
217 dfun.Foo.Int :: Foo Int
218 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
219 \end{verbatim}
220 Notice that, as with method selectors above, we assume that dictionary
221 application is curried, so there's no need to mention the Ord dictionary
222 in const.Foo.Int.op2 (or the type variable).
223
224 \begin{verbatim}
225 instance Foo a => Foo [a] where {}
226
227 dfun.Foo.List :: forall a. Foo a -> Foo [a]
228 dfun.Foo.List
229   = /\ a -> \ dfoo_a ->
230     let rec
231         op1 = defm.Foo.op1 [a] dfoo_list
232         op2 = defm.Foo.op2 [a] dfoo_list
233         dfoo_list = (op1, op2)
234     in
235         dfoo_list
236 \end{verbatim}
237
238 @tcClassDecls2@ generates bindings for polymorphic default methods
239 (generic default methods have by now turned into instance declarations)
240
241 \begin{code}
242 tcClassDecl2 :: RenamedTyClDecl         -- The class declaration
243              -> TcM (TcMonoBinds, [Id])
244
245 tcClassDecl2 (ClassDecl {tcdName = class_name, tcdSigs = sigs, 
246                          tcdMeths = default_binds, tcdLoc = src_loc})
247   = recoverM (returnM (EmptyMonoBinds, []))     $ 
248     addSrcLoc src_loc                                   $
249     tcLookupClass class_name                            `thenM` \ clas ->
250
251         -- We make a separate binding for each default method.
252         -- At one time I used a single AbsBinds for all of them, thus
253         -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
254         -- But that desugars into
255         --      ds = \d -> (..., ..., ...)
256         --      dm1 = \d -> case ds d of (a,b,c) -> a
257         -- And since ds is big, it doesn't get inlined, so we don't get good
258         -- default methods.  Better to make separate AbsBinds for each
259     let
260         (tyvars, _, _, op_items) = classBigSig clas
261         prags                    = filter isPragSig sigs
262         tc_dm                    = tcDefMeth clas tyvars default_binds prags
263
264         dm_sel_ids               = [sel_id | (sel_id, DefMeth) <- op_items]
265         -- Generate code for polymorphic default methods only
266         -- (Generic default methods have turned into instance decls by now.)
267         -- This is incompatible with Hugs, which expects a polymorphic 
268         -- default method for every class op, regardless of whether or not 
269         -- the programmer supplied an explicit default decl for the class.  
270         -- (If necessary we can fix that, but we don't have a convenient Id to hand.)
271     in
272     mapAndUnzipM tc_dm dm_sel_ids       `thenM` \ (defm_binds, dm_ids_s) ->
273     returnM (andMonoBindList defm_binds, concat dm_ids_s)
274     
275 tcDefMeth clas tyvars binds_in prags sel_id
276   = lookupTopBndrRn (mkDefMethRdrName sel_id)   `thenM` \ dm_name -> 
277     tcInstTyVars ClsTv tyvars                   `thenM` \ (clas_tyvars, inst_tys, _) ->
278     let
279         dm_ty       = idType sel_id     -- Same as dict selector!
280         theta       = [mkClassPred clas inst_tys]
281         local_dm_id = mkDefaultMethodId dm_name dm_ty
282         xtve        = tyvars `zip` clas_tyvars
283         origin      = ClassDeclOrigin
284     in
285     mkMethodBind origin clas inst_tys 
286                  binds_in (sel_id, DefMeth)             `thenM` \ (_, meth_info) ->
287     newDicts origin theta                               `thenM` \ [this_dict] ->
288     getLIE (tcMethodBind xtve clas_tyvars theta 
289                          [this_dict] prags meth_info)   `thenM` \ (defm_bind, insts_needed) ->
290     
291     addErrCtxt (defltMethCtxt clas) $
292     
293         -- Check the context
294     tcSimplifyCheck
295         (ptext SLIT("class") <+> ppr clas)
296         clas_tyvars
297         [this_dict]
298         insts_needed                    `thenM` \ dict_binds ->
299
300         -- Simplification can do unification
301     checkSigTyVars clas_tyvars          `thenM` \ clas_tyvars' ->
302     
303     let
304         (_,dm_inst_id,_) = meth_info
305         full_bind = AbsBinds
306                     clas_tyvars'
307                     [instToId this_dict]
308                     [(clas_tyvars', local_dm_id, dm_inst_id)]
309                     emptyNameSet        -- No inlines (yet)
310                     (dict_binds `andMonoBinds` defm_bind)
311     in
312     returnM (full_bind, [local_dm_id])
313
314 mkDefMethRdrName :: Id -> RdrName
315 mkDefMethRdrName sel_id = mkDerivedRdrName (idName sel_id) mkDefaultMethodOcc
316 \end{code}
317
318
319 %************************************************************************
320 %*                                                                      *
321 \subsection{Typechecking a method}
322 %*                                                                      *
323 %************************************************************************
324
325 @tcMethodBind@ is used to type-check both default-method and
326 instance-decl method declarations.  We must type-check methods one at a
327 time, because their signatures may have different contexts and
328 tyvar sets.
329
330 \begin{code}
331 type MethodSpec = (Id,                  -- Global selector Id
332                    Id,                  -- Local Id (class tyvars instantiated)
333                    RenamedMonoBinds)    -- Binding for the method
334
335 tcMethodBind 
336         :: [(TyVar,TcTyVar)]    -- Bindings for type environment
337         -> [TcTyVar]            -- Instantiated type variables for the
338                                 --      enclosing class/instance decl. 
339                                 --      They'll be signature tyvars, and we
340                                 --      want to check that they don't get bound
341                                 -- Always equal the range of the type envt
342         -> TcThetaType          -- Available theta; it's just used for the error message
343         -> [Inst]               -- Available from context, used to simplify constraints 
344                                 --      from the method body
345         -> [RenamedSig]         -- Pragmas (e.g. inline pragmas)
346         -> MethodSpec           -- Details of this method
347         -> TcM TcMonoBinds
348
349 tcMethodBind xtve inst_tyvars inst_theta avail_insts prags
350              (sel_id, meth_id, meth_bind)
351   =     -- Check the bindings; first adding inst_tyvars to the envt
352         -- so that we don't quantify over them in nested places
353      mkTcSig meth_id                            `thenM` \ meth_sig ->
354
355      tcExtendTyVarEnv2 xtve (
356         addErrCtxt (methodCtxt sel_id)                  $
357         getLIE                                          $
358         tcMonoBinds meth_bind [meth_sig] NonRecursive
359      )                                                  `thenM` \ ((meth_bind,_), meth_lie) ->
360
361         -- Now do context reduction.   We simplify wrt both the local tyvars
362         -- and the ones of the class/instance decl, so that there is
363         -- no problem with
364         --      class C a where
365         --        op :: Eq a => a -> b -> a
366         --
367         -- We do this for each method independently to localise error messages
368
369      let
370         TySigInfo meth_id meth_tvs meth_theta _ local_meth_id _ _ = meth_sig
371      in
372      addErrCtxtM (sigCtxt sel_id inst_tyvars inst_theta (idType meth_id))       $
373      newDicts SignatureOrigin meth_theta        `thenM` \ meth_dicts ->
374      let
375         all_tyvars = meth_tvs ++ inst_tyvars
376         all_insts  = avail_insts ++ meth_dicts
377      in
378      tcSimplifyCheck
379          (ptext SLIT("class or instance method") <+> quotes (ppr sel_id))
380          all_tyvars all_insts meth_lie          `thenM` \ lie_binds ->
381
382      checkSigTyVars all_tyvars                  `thenM` \ all_tyvars' ->
383
384      let
385         sel_name = idName sel_id
386         inline_prags  = [ (is_inl, phase)
387                         | InlineSig is_inl name phase _ <- prags, 
388                           name == sel_name ]
389         spec_prags = [ prag 
390                      | prag@(SpecSig name _ _) <- prags, 
391                        name == sel_name]
392         
393                 -- Attach inline pragmas as appropriate
394         (final_meth_id, inlines) 
395            | ((is_inline, phase) : _) <- inline_prags
396            = (meth_id `setInlinePragma` phase,
397               if is_inline then unitNameSet (idName meth_id) else emptyNameSet)
398            | otherwise
399            = (meth_id, emptyNameSet)
400
401         meth_tvs'      = take (length meth_tvs) all_tyvars'
402         poly_meth_bind = AbsBinds meth_tvs'
403                                   (map instToId meth_dicts)
404                                   [(meth_tvs', final_meth_id, local_meth_id)]
405                                   inlines
406                                   (lie_binds `andMonoBinds` meth_bind)
407
408      in
409         -- Deal with specialisation pragmas
410         -- The sel_name is what appears in the pragma
411      tcExtendLocalValEnv2 [(sel_name, final_meth_id)] (
412         getLIE (tcSpecSigs spec_prags)                  `thenM` \ (spec_binds1, prag_lie) ->
413      
414              -- The prag_lie for a SPECIALISE pragma will mention the function itself, 
415              -- so we have to simplify them away right now lest they float outwards!
416         bindInstsOfLocalFuns prag_lie [final_meth_id]   `thenM` \ spec_binds2 ->
417         returnM (spec_binds1 `andMonoBinds` spec_binds2)
418      )                                                  `thenM` \ spec_binds ->
419
420      returnM (poly_meth_bind `andMonoBinds` spec_binds)
421
422
423 mkMethodBind :: InstOrigin
424              -> Class -> [TcType]       -- Class and instance types
425              -> RenamedMonoBinds        -- Method binding (pick the right one from in here)
426              -> ClassOpItem
427              -> TcM (Maybe Inst,                -- Method inst
428                      MethodSpec)
429 -- Find the binding for the specified method, or make
430 -- up a suitable default method if it isn't there
431
432 mkMethodBind origin clas inst_tys meth_binds (sel_id, dm_info)
433   = mkMethId origin clas sel_id inst_tys                `thenM` \ (mb_inst, meth_id) ->
434     let
435         meth_name  = idName meth_id
436     in
437         -- Figure out what method binding to use
438         -- If the user suppplied one, use it, else construct a default one
439     getSrcLocM                                  `thenM` \ loc -> 
440     (case find_bind (idName sel_id) meth_name meth_binds of
441         Just user_bind -> returnM user_bind 
442         Nothing        -> mkDefMethRhs origin clas inst_tys sel_id loc dm_info  `thenM` \ rhs ->
443                           returnM (FunMonoBind meth_name False  -- Not infix decl
444                                                [mkSimpleMatch [] rhs placeHolderType loc] loc)
445     )                                                           `thenM` \ meth_bind ->
446
447     returnM (mb_inst, (sel_id, meth_id, meth_bind))
448
449 mkMethId :: InstOrigin -> Class 
450          -> Id -> [TcType]      -- Selector, and instance types
451          -> TcM (Maybe Inst, Id)
452              
453 -- mkMethId instantiates the selector Id at the specified types
454 mkMethId origin clas sel_id inst_tys
455   = let
456         (tyvars,rho) = tcSplitForAllTys (idType sel_id)
457         rho_ty       = ASSERT( length tyvars == length inst_tys )
458                        substTyWith tyvars inst_tys rho
459         (preds,tau)  = tcSplitPhiTy rho_ty
460         first_pred   = head preds
461     in
462         -- The first predicate should be of form (C a b)
463         -- where C is the class in question
464     ASSERT( not (null preds) && 
465             case getClassPredTys_maybe first_pred of
466                 { Just (clas1,tys) -> clas == clas1 ; Nothing -> False }
467     )
468     if isSingleton preds then
469         -- If it's the only one, make a 'method'
470         getInstLoc origin                               `thenM` \ inst_loc ->
471         newMethod inst_loc sel_id inst_tys preds tau    `thenM` \ meth_inst ->
472         returnM (Just meth_inst, instToId meth_inst)
473     else
474         -- If it's not the only one we need to be careful
475         -- For example, given 'op' defined thus:
476         --      class Foo a where
477         --        op :: (?x :: String) => a -> a
478         -- (mkMethId op T) should return an Inst with type
479         --      (?x :: String) => T -> T
480         -- That is, the class-op's context is still there.  
481         -- BUT: it can't be a Method any more, because it breaks
482         --      INVARIANT 2 of methods.  (See the data decl for Inst.)
483         newUnique                       `thenM` \ uniq ->
484         getSrcLocM                      `thenM` \ loc ->
485         let 
486             real_tau = mkPhiTy (tail preds) tau
487             meth_id  = mkUserLocal (getOccName sel_id) uniq real_tau loc
488         in
489         returnM (Nothing, meth_id)
490
491      -- The user didn't supply a method binding, 
492      -- so we have to make up a default binding
493      -- The RHS of a default method depends on the default-method info
494 mkDefMethRhs origin clas inst_tys sel_id loc DefMeth
495   =  -- An polymorphic default method
496     lookupImportedName (mkDefMethRdrName sel_id)        `thenM` \ dm_name ->
497         -- Might not be imported, but will be an OrigName
498     traceRn (text "mkDefMeth" <+> ppr dm_name)          `thenM_`
499     returnM (HsVar dm_name)
500
501 mkDefMethRhs origin clas inst_tys sel_id loc NoDefMeth
502   =     -- No default method
503         -- Warn only if -fwarn-missing-methods
504     doptM Opt_WarnMissingMethods                `thenM` \ warn -> 
505     warnTc (isInstDecl origin
506            && warn
507            && reportIfUnused (getOccName sel_id))
508            (omittedMethodWarn sel_id)           `thenM_`
509     returnM error_rhs
510   where
511     error_rhs  = HsLam (mkSimpleMatch wild_pats simple_rhs placeHolderType loc)
512     simple_rhs = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID)) 
513                        (HsLit (HsStringPrim (mkFastString (stringToUtf8 error_msg))))
514     error_msg = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
515
516         -- When the type is of form t1 -> t2 -> t3
517         -- make a default method like (\ _ _ -> noMethBind "blah")
518         -- rather than simply        (noMethBind "blah")
519         -- Reason: if t1 or t2 are higher-ranked types we get n
520         --         silly ambiguity messages.
521         -- Example:     f :: (forall a. Eq a => a -> a) -> Int
522         --              f = error "urk"
523         -- Here, tcSub tries to force (error "urk") to have the right type,
524         -- thus:        f = \(x::forall a. Eq a => a->a) -> error "urk" (x t)
525         -- where 't' is fresh ty var.  This leads directly to "ambiguous t".
526         -- 
527         -- NB: technically this changes the meaning of the default-default
528         --     method slightly, because `seq` can see the lambdas.  Oh well.
529     (_,_,tau1)    = tcSplitSigmaTy (idType sel_id)
530     (_,_,tau2)    = tcSplitSigmaTy tau1
531         -- Need two splits because the  selector can have a type like
532         --      forall a. Foo a => forall b. Eq b => ...
533     (arg_tys, _) = tcSplitFunTys tau2
534     wild_pats    = [WildPat placeHolderType | ty <- arg_tys]
535
536 mkDefMethRhs origin clas inst_tys sel_id loc GenDefMeth 
537   =     -- A generic default method
538         -- If the method is defined generically, we can only do the job if the
539         -- instance declaration is for a single-parameter type class with
540         -- a type constructor applied to type arguments in the instance decl
541         --      (checkTc, so False provokes the error)
542      ASSERT( isInstDecl origin )        -- We never get here from a class decl
543
544      checkTc (isJust maybe_tycon)
545              (badGenericInstance sel_id (notSimple inst_tys))           `thenM_`
546      checkTc (tyConHasGenerics tycon)
547              (badGenericInstance sel_id (notGeneric tycon))             `thenM_`
548
549      ioToTcRn (dumpIfSet opt_PprStyle_Debug "Generic RHS" stuff)        `thenM_`
550
551         -- Rename it before returning it
552      rnExpr rhs                 `thenM` \ (rn_rhs, _) ->
553      returnM rn_rhs
554   where
555     rhs = mkGenericRhs sel_id clas_tyvar tycon
556
557     stuff = vcat [ppr clas <+> ppr inst_tys,
558                   nest 4 (ppr sel_id <+> equals <+> ppr rhs)]
559
560           -- The tycon is only used in the generic case, and in that
561           -- case we require that the instance decl is for a single-parameter
562           -- type class with type variable arguments:
563           --    instance (...) => C (T a b)
564     clas_tyvar    = head (classTyVars clas)
565     Just tycon    = maybe_tycon
566     maybe_tycon   = case inst_tys of 
567                         [ty] -> case tcSplitTyConApp_maybe ty of
568                                   Just (tycon, arg_tys) | all tcIsTyVarTy arg_tys -> Just tycon
569                                   other                                           -> Nothing
570                         other -> Nothing
571
572 isInstDecl InstanceDeclOrigin = True
573 isInstDecl ClassDeclOrigin    = False
574 \end{code}
575
576
577 \begin{code}
578 -- The renamer just puts the selector ID as the binder in the method binding
579 -- but we must use the method name; so we substitute it here.  Crude but simple.
580 find_bind sel_name meth_name (FunMonoBind op_name fix matches loc)
581     | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
582 find_bind sel_name meth_name (AndMonoBinds b1 b2)
583     = find_bind sel_name meth_name b1 `seqMaybe` find_bind sel_name meth_name b2
584 find_bind sel_name meth_name other  = Nothing   -- Default case
585 \end{code}
586
587
588 %************************************************************************
589 %*                                                                      *
590 \subsection{Extracting generic instance declaration from class declarations}
591 %*                                                                      *
592 %************************************************************************
593
594 @getGenericInstances@ extracts the generic instance declarations from a class
595 declaration.  For exmaple
596
597         class C a where
598           op :: a -> a
599         
600           op{ x+y } (Inl v)   = ...
601           op{ x+y } (Inr v)   = ...
602           op{ x*y } (v :*: w) = ...
603           op{ 1   } Unit      = ...
604
605 gives rise to the instance declarations
606
607         instance C (x+y) where
608           op (Inl v)   = ...
609           op (Inr v)   = ...
610         
611         instance C (x*y) where
612           op (v :*: w) = ...
613
614         instance C 1 where
615           op Unit      = ...
616
617
618 \begin{code}
619 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo] 
620 getGenericInstances class_decls
621   = do  { gen_inst_infos <- mappM get_generics class_decls
622         ; let { gen_inst_info = concat gen_inst_infos }
623
624         -- Return right away if there is no generic stuff
625         ; if null gen_inst_info then returnM []
626           else do 
627
628         -- Otherwise print it out
629         { dflags <- getDOpts
630         ; ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances" 
631                    (vcat (map pprInstInfo gen_inst_info)))      
632         ; returnM gen_inst_info }}
633
634 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = def_methods, tcdLoc = loc})
635   | null generic_binds
636   = returnM [] -- The comon case: no generic default methods
637
638   | otherwise   -- A source class decl with generic default methods
639   = recoverM (returnM [])                               $
640     tcAddDeclCtxt decl                                  $
641     tcLookupClass class_name                            `thenM` \ clas ->
642
643         -- Group by type, and
644         -- make an InstInfo out of each group
645     let
646         groups = groupWith andMonoBindList generic_binds
647     in
648     mappM (mkGenericInstance clas loc) groups           `thenM` \ inst_infos ->
649
650         -- Check that there is only one InstInfo for each type constructor
651         -- The main way this can fail is if you write
652         --      f {| a+b |} ... = ...
653         --      f {| x+y |} ... = ...
654         -- Then at this point we'll have an InstInfo for each
655     let
656         tc_inst_infos :: [(TyCon, InstInfo)]
657         tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
658
659         bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
660                               group `lengthExceeds` 1]
661         get_uniq (tc,_) = getUnique tc
662     in
663     mappM (addErrTc . dupGenericInsts) bad_groups       `thenM_`
664
665         -- Check that there is an InstInfo for each generic type constructor
666     let
667         missing = genericTyConNames `minusList` [tyConName tc | (tc,_) <- tc_inst_infos]
668     in
669     checkTc (null missing) (missingGenericInstances missing)    `thenM_`
670
671     returnM inst_infos
672
673   where
674     generic_binds :: [(HsType Name, RenamedMonoBinds)]
675     generic_binds = getGenericBinds def_methods
676
677
678 ---------------------------------
679 getGenericBinds :: RenamedMonoBinds -> [(HsType Name, RenamedMonoBinds)]
680   -- Takes a group of method bindings, finds the generic ones, and returns
681   -- them in finite map indexed by the type parameter in the definition.
682
683 getGenericBinds EmptyMonoBinds       = []
684 getGenericBinds (AndMonoBinds m1 m2) = getGenericBinds m1 ++ getGenericBinds m2
685
686 getGenericBinds (FunMonoBind id infixop matches loc)
687   = groupWith wrap (mapCatMaybes maybeGenericMatch matches)
688   where
689     wrap ms = FunMonoBind id infixop ms loc
690
691 groupWith :: ([a] -> b) -> [(HsType Name, a)] -> [(HsType Name, b)]
692 groupWith op []          = []
693 groupWith op ((t,v):prs) = (t, op (v:vs)) : groupWith op rest
694     where
695       vs            = map snd this
696       (this,rest)   = partition same_t prs
697       same_t (t',v) = t `eqPatType` t'
698
699 eqPatType :: HsType Name -> HsType Name -> Bool
700 -- A very simple equality function, only for 
701 -- type patterns in generic function definitions.
702 eqPatType (HsTyVar v1)    (HsTyVar v2)    = v1==v2
703 eqPatType (HsAppTy s1 t1) (HsAppTy s2 t2) = s1 `eqPatType` s2 && t2 `eqPatType` t2
704 eqPatType _ _ = False
705
706 ---------------------------------
707 mkGenericInstance :: Class -> SrcLoc
708                   -> (HsType Name, RenamedMonoBinds)
709                   -> TcM InstInfo
710
711 mkGenericInstance clas loc (hs_ty, binds)
712   -- Make a generic instance declaration
713   -- For example:       instance (C a, C b) => C (a+b) where { binds }
714
715   =     -- Extract the universally quantified type variables
716         -- and wrap them as forall'd tyvars, so that kind inference
717         -- works in the standard way
718     let
719         sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
720         hs_forall_ty = mkHsForAllTy (Just sig_tvs) [] hs_ty
721     in
722         -- Type-check the instance type, and check its form
723     tcHsSigType GenPatCtxt hs_forall_ty         `thenM` \ forall_inst_ty ->
724     let
725         (tyvars, inst_ty) = tcSplitForAllTys forall_inst_ty
726     in
727     checkTc (validGenericInstanceType inst_ty)
728             (badGenericInstanceType binds)      `thenM_`
729
730         -- Make the dictionary function.
731     newDFunName clas [inst_ty] loc              `thenM` \ dfun_name ->
732     let
733         inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
734         dfun_id    = mkDictFunId dfun_name tyvars inst_theta clas [inst_ty]
735     in
736
737     returnM (InstInfo { iDFunId = dfun_id, iBinds = VanillaInst binds [] })
738 \end{code}
739
740
741 %************************************************************************
742 %*                                                                      *
743                 Error messages
744 %*                                                                      *
745 %************************************************************************
746
747 \begin{code}
748 tcAddDeclCtxt decl thing_inside
749   = addSrcLoc (tcdLoc decl)     $
750     addErrCtxt ctxt     $
751     thing_inside
752   where
753      thing = case decl of
754                 ClassDecl {}              -> "class"
755                 TySynonym {}              -> "type synonym"
756                 TyData {tcdND = NewType}  -> "newtype"
757                 TyData {tcdND = DataType} -> "data type"
758
759      ctxt = hsep [ptext SLIT("In the"), text thing, 
760                   ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
761
762 defltMethCtxt clas
763   = ptext SLIT("When checking the default methods for class") <+> quotes (ppr clas)
764
765 methodCtxt sel_id
766   = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
767
768 badMethodErr clas op
769   = hsep [ptext SLIT("Class"), quotes (ppr clas), 
770           ptext SLIT("does not have a method"), quotes (ppr op)]
771
772 omittedMethodWarn sel_id
773   = ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id)
774
775 badGenericInstance sel_id because
776   = sep [ptext SLIT("Can't derive generic code for") <+> quotes (ppr sel_id),
777          because]
778
779 notSimple inst_tys
780   = vcat [ptext SLIT("because the instance type(s)"), 
781           nest 2 (ppr inst_tys),
782           ptext SLIT("is not a simple type of form (T a b c)")]
783
784 notGeneric tycon
785   = vcat [ptext SLIT("because the instance type constructor") <+> quotes (ppr tycon) <+> 
786           ptext SLIT("was not compiled with -fgenerics")]
787
788 badGenericInstanceType binds
789   = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
790           nest 4 (ppr binds)]
791
792 missingGenericInstances missing
793   = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
794           
795 dupGenericInsts tc_inst_infos
796   = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
797           nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
798           ptext SLIT("All the type patterns for a generic type constructor must be identical")
799     ]
800   where 
801     ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
802
803 mixedGenericErr op
804   = ptext SLIT("Can't mix generic and non-generic equations for class method") <+> quotes (ppr op)
805 \end{code}