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