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