2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcClassDcl]{Typechecking class declarations}
7 module TcClassDcl ( tcClassDecl1, tcClassDecls2,
8 MethodSpec, tcMethodBind, mkMethodBind, badMethodErr
11 #include "HsVersions.h"
13 import HsSyn ( TyClDecl(..), Sig(..), MonoBinds(..),
14 HsExpr(..), HsLit(..), Pat(WildPat),
15 mkSimpleMatch, andMonoBinds, andMonoBindList,
16 isClassOpSig, isPragSig,
19 import BasicTypes ( RecFlag(..) )
20 import RnHsSyn ( RenamedTyClDecl, RenamedSig,
21 RenamedClassOpSig, RenamedMonoBinds,
24 import RnEnv ( lookupSysName )
25 import TcHsSyn ( TcMonoBinds )
27 import Inst ( Inst, InstOrigin(..), instToId, newDicts, newMethod )
28 import TcEnv ( TyThingDetails(..),
29 tcLookupClass, tcExtendLocalValEnv2,
30 tcExtendTyVarEnv2, tcExtendTyVarEnv
32 import TcTyDecls ( tcMkDataCon )
33 import TcBinds ( tcMonoBinds, tcSpecSigs )
34 import TcMonoType ( TcSigInfo(..), tcHsType, tcHsTheta, mkTcSig )
35 import TcSimplify ( tcSimplifyCheck, bindInstsOfLocalFuns )
36 import TcUnify ( checkSigTyVars, sigCtxt )
37 import TcMType ( tcInstTyVars )
38 import TcType ( Type, TyVarDetails(..), TcType, TcThetaType, TcTyVar,
39 mkTyVarTys, mkPredTys, mkClassPred, tcSplitSigmaTy, tcSplitFunTys,
40 tcIsTyVarTy, tcSplitTyConApp_maybe, tcSplitForAllTys, tcSplitPhiTy,
41 getClassPredTys_maybe, mkPhiTy
44 import Generics ( mkGenericRhs )
45 import PrelInfo ( nO_METHOD_BINDING_ERROR_ID )
46 import Class ( classTyVars, classBigSig, classTyCon,
47 Class, ClassOpItem, DefMeth (..) )
48 import TyCon ( tyConGenInfo )
49 import Subst ( substTyWith )
50 import MkId ( mkDictSelId, mkDefaultMethodId )
51 import Id ( Id, idType, idName, mkUserLocal, setInlinePragma )
52 import Name ( Name, NamedThing(..) )
53 import NameEnv ( NameEnv, lookupNameEnv, emptyNameEnv, unitNameEnv, plusNameEnv )
54 import NameSet ( emptyNameSet, unitNameSet )
55 import OccName ( mkClassTyConOcc, mkClassDataConOcc, mkSuperDictSelOcc, reportIfUnused )
59 import UnicodeUtil ( stringToUtf8 )
60 import ErrUtils ( dumpIfSet )
61 import Util ( count, lengthIs, isSingleton )
62 import Maybes ( seqMaybe )
63 import Maybe ( isJust )
71 Every class implicitly declares a new data type, corresponding to dictionaries
72 of that class. So, for example:
74 class (D a) => C a where
76 op2 :: forall b. Ord b => a -> b -> b
78 would implicitly declare
80 data CDict a = CDict (D a)
82 (forall b. Ord b => a -> b -> b)
84 (We could use a record decl, but that means changing more of the existing apparatus.
87 For classes with just one superclass+method, we use a newtype decl instead:
90 op :: forallb. a -> b -> b
94 newtype CDict a = CDict (forall b. a -> b -> b)
96 Now DictTy in Type is just a form of type synomym:
97 DictTy c t = TyConTy CDict `AppTy` t
99 Death to "ExpandingDicts".
102 %************************************************************************
104 \subsection{Type checking}
106 %************************************************************************
110 tcClassDecl1 :: RenamedTyClDecl -> TcM (Name, TyThingDetails)
111 tcClassDecl1 (ClassDecl {tcdCtxt = context, tcdName = class_name,
112 tcdTyVars = tyvar_names, tcdFDs = fundeps,
113 tcdSigs = class_sigs, tcdMeths = def_methods,
115 = -- LOOK THINGS UP IN THE ENVIRONMENT
116 tcLookupClass class_name `thenM` \ clas ->
118 tyvars = classTyVars clas
119 op_sigs = filter isClassOpSig class_sigs
120 op_names = [n | ClassOpSig n _ _ _ <- op_sigs]
122 tcExtendTyVarEnv tyvars $
124 checkDefaultBinds clas op_names def_methods `thenM` \ mb_dm_env ->
127 -- The renamer has already checked that the context mentions
128 -- only the type variable of the class decl.
129 -- Context is already kind-checked
130 tcHsTheta context `thenM` \ sc_theta ->
132 -- CHECK THE CLASS SIGNATURES,
133 mappM (tcClassSig clas tyvars mb_dm_env) op_sigs `thenM` \ sig_stuff ->
135 -- MAKE THE CLASS DETAILS
136 lookupSysName class_name mkClassTyConOcc `thenM` \ tycon_name ->
137 lookupSysName class_name mkClassDataConOcc `thenM` \ datacon_name ->
138 mapM (lookupSysName class_name . mkSuperDictSelOcc)
139 [1..length context] `thenM` \ sc_sel_names ->
140 -- We number off the superclass selectors, 1, 2, 3 etc so that we
141 -- can construct names for the selectors. Thus
142 -- class (C a, C b) => D a b where ...
143 -- gives superclass selectors
145 -- (We used to call them D_C, but now we can have two different
146 -- superclasses both called C!)
148 (op_tys, op_items) = unzip sig_stuff
149 sc_tys = mkPredTys sc_theta
150 dict_component_tys = sc_tys ++ op_tys
151 sc_sel_ids = [mkDictSelId sc_name clas | sc_name <- sc_sel_names]
153 tcMkDataCon datacon_name
154 [{- No strictness -}]
155 [{- No labelled fields -}]
156 tyvars [{-No context-}]
157 [{-No existential tyvars-}] [{-Or context-}]
159 (classTyCon clas) `thenM` \ dict_con ->
161 returnM (class_name, ClassDetails sc_theta sc_sel_ids op_items dict_con tycon_name)
165 checkDefaultBinds :: Class -> [Name] -> Maybe RenamedMonoBinds
166 -> TcM (Maybe (NameEnv Bool))
167 -- The returned environment says
168 -- x not in env => no default method
169 -- x -> True => generic default method
170 -- x -> False => polymorphic default method
172 -- Check default bindings
173 -- a) must be for a class op for this class
174 -- b) must be all generic or all non-generic
175 -- and return a mapping from class-op to DefMeth info
177 -- But do all this only for source binds
179 checkDefaultBinds clas ops Nothing
182 checkDefaultBinds clas ops (Just mbs)
183 = go mbs `thenM` \ dm_env ->
184 returnM (Just dm_env)
186 go EmptyMonoBinds = returnM emptyNameEnv
188 go (AndMonoBinds b1 b2)
189 = go b1 `thenM` \ dm_info1 ->
190 go b2 `thenM` \ dm_info2 ->
191 returnM (dm_info1 `plusNameEnv` dm_info2)
193 go (FunMonoBind op _ matches loc)
196 -- Check that the op is from this class
197 checkTc (op `elem` ops) (badMethodErr clas op) `thenM_`
199 -- Check that all the defns ar generic, or none are
200 checkTc (all_generic || none_generic) (mixedGenericErr op) `thenM_`
202 returnM (unitNameEnv op all_generic)
204 n_generic = count (isJust . maybeGenericMatch) matches
205 none_generic = n_generic == 0
206 all_generic = matches `lengthIs` n_generic
211 tcClassSig :: Class -- ...ditto...
212 -> [TyVar] -- The class type variable, used for error check only
213 -> Maybe (NameEnv Bool) -- Info about default methods;
214 -- Nothing => imported class defn with no method binds
216 -> TcM (Type, -- Type of the method
217 ClassOpItem) -- Selector Id, default-method Id, True if explicit default binding
219 -- This warrants an explanation: we need to separate generic
220 -- default methods and default methods later on in the compiler
221 -- so we distinguish them in checkDefaultBinds, and pass this knowledge in the
222 -- Class.DefMeth data structure.
224 tcClassSig clas clas_tyvars maybe_dm_env
225 (ClassOpSig op_name sig_dm op_ty src_loc)
226 = addSrcLoc src_loc $
228 -- Check the type signature. NB that the envt *already has*
229 -- bindings for the type variables; see comments in TcTyAndClassDcls.
230 tcHsType op_ty `thenM` \ local_ty ->
233 theta = [mkClassPred clas (mkTyVarTys clas_tyvars)]
235 -- Build the selector id and default method id
236 sel_id = mkDictSelId op_name clas
237 DefMeth dm_name = sig_dm
239 dm_info = case maybe_dm_env of
241 Just dm_env -> mk_src_dm_info dm_env
243 mk_src_dm_info dm_env = case lookupNameEnv dm_env op_name of
245 Just True -> GenDefMeth
246 Just False -> DefMeth dm_name
248 returnM (local_ty, (sel_id, dm_info))
252 %************************************************************************
254 \subsection[Default methods]{Default methods}
256 %************************************************************************
258 The default methods for a class are each passed a dictionary for the
259 class, so that they get access to the other methods at the same type.
260 So, given the class decl
264 op2 :: Ord b => a -> b -> b -> b
267 op2 x y z = if (op1 x) && (y < z) then y else z
269 we get the default methods:
271 defm.Foo.op1 :: forall a. Foo a => a -> Bool
272 defm.Foo.op1 = /\a -> \dfoo -> \x -> True
274 defm.Foo.op2 :: forall a. Foo a => forall b. Ord b => a -> b -> b -> b
275 defm.Foo.op2 = /\ a -> \ dfoo -> /\ b -> \ dord -> \x y z ->
276 if (op1 a dfoo x) && (< b dord y z) then y else z
279 When we come across an instance decl, we may need to use the default
282 instance Foo Int where {}
286 const.Foo.Int.op1 :: Int -> Bool
287 const.Foo.Int.op1 = defm.Foo.op1 Int dfun.Foo.Int
289 const.Foo.Int.op2 :: forall b. Ord b => Int -> b -> b -> b
290 const.Foo.Int.op2 = defm.Foo.op2 Int dfun.Foo.Int
292 dfun.Foo.Int :: Foo Int
293 dfun.Foo.Int = (const.Foo.Int.op1, const.Foo.Int.op2)
295 Notice that, as with method selectors above, we assume that dictionary
296 application is curried, so there's no need to mention the Ord dictionary
297 in const.Foo.Int.op2 (or the type variable).
300 instance Foo a => Foo [a] where {}
302 dfun.Foo.List :: forall a. Foo a -> Foo [a]
304 = /\ a -> \ dfoo_a ->
306 op1 = defm.Foo.op1 [a] dfoo_list
307 op2 = defm.Foo.op2 [a] dfoo_list
308 dfoo_list = (op1, op2)
313 The function @tcClassDecls2@ just arranges to apply @tcClassDecl2@ to
314 each local class decl.
317 tcClassDecls2 :: [RenamedTyClDecl] -> TcM (TcMonoBinds, [Id])
321 (returnM (EmptyMonoBinds, []))
322 [tcClassDecl2 cls_decl | cls_decl@(ClassDecl {tcdMeths = Just _}) <- decls]
323 -- The 'Just' picks out source ClassDecls
325 combine tc1 tc2 = tc1 `thenM` \ (binds1, ids1) ->
326 tc2 `thenM` \ (binds2, ids2) ->
327 returnM (binds1 `AndMonoBinds` binds2,
331 @tcClassDecl2@ generates bindings for polymorphic default methods
332 (generic default methods have by now turned into instance declarations)
335 tcClassDecl2 :: RenamedTyClDecl -- The class declaration
336 -> TcM (TcMonoBinds, [Id])
338 tcClassDecl2 (ClassDecl {tcdName = class_name, tcdSigs = sigs,
339 tcdMeths = Just default_binds, tcdLoc = src_loc})
340 = -- The 'Just' picks out source ClassDecls
341 recoverM (returnM (EmptyMonoBinds, [])) $
343 tcLookupClass class_name `thenM` \ clas ->
345 -- We make a separate binding for each default method.
346 -- At one time I used a single AbsBinds for all of them, thus
347 -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... }
348 -- But that desugars into
349 -- ds = \d -> (..., ..., ...)
350 -- dm1 = \d -> case ds d of (a,b,c) -> a
351 -- And since ds is big, it doesn't get inlined, so we don't get good
352 -- default methods. Better to make separate AbsBinds for each
354 (tyvars, _, _, op_items) = classBigSig clas
355 prags = filter isPragSig sigs
356 tc_dm = tcDefMeth clas tyvars default_binds prags
358 mapAndUnzipM tc_dm op_items `thenM` \ (defm_binds, dm_ids_s) ->
360 returnM (andMonoBindList defm_binds, concat dm_ids_s)
363 tcDefMeth clas tyvars binds_in prags (_, NoDefMeth) = returnM (EmptyMonoBinds, [])
364 tcDefMeth clas tyvars binds_in prags (_, GenDefMeth) = returnM (EmptyMonoBinds, [])
365 -- Generate code for polymorphic default methods only
366 -- (Generic default methods have turned into instance decls by now.)
367 -- This is incompatible with Hugs, which expects a polymorphic
368 -- default method for every class op, regardless of whether or not
369 -- the programmer supplied an explicit default decl for the class.
370 -- (If necessary we can fix that, but we don't have a convenient Id to hand.)
372 tcDefMeth clas tyvars binds_in prags op_item@(sel_id, DefMeth dm_name)
373 = tcInstTyVars ClsTv tyvars `thenM` \ (clas_tyvars, inst_tys, _) ->
375 dm_ty = idType sel_id -- Same as dict selector!
376 -- The default method's type should really come from the
377 -- iface file, since it could be usage-generalised, but this
378 -- requires altering the mess of knots in TcModule and I'm
379 -- too scared to do that. Instead, I have disabled generalisation
380 -- of types of default methods (and dict funs) by annotating them
381 -- TyGenNever (in MkId). Ugh! KSW 1999-09.
383 theta = [mkClassPred clas inst_tys]
384 local_dm_id = mkDefaultMethodId dm_name dm_ty
385 xtve = tyvars `zip` clas_tyvars
387 newDicts origin theta `thenM` \ [this_dict] ->
389 mkMethodBind origin clas inst_tys binds_in op_item `thenM` \ (_, meth_info) ->
390 getLIE (tcMethodBind xtve clas_tyvars theta
391 [this_dict] prags meth_info) `thenM` \ (defm_bind, insts_needed) ->
393 addErrCtxt (defltMethCtxt clas) $
397 (ptext SLIT("class") <+> ppr clas)
400 insts_needed `thenM` \ dict_binds ->
402 -- Simplification can do unification
403 checkSigTyVars clas_tyvars `thenM` \ clas_tyvars' ->
406 (_,dm_inst_id,_) = meth_info
410 [(clas_tyvars', local_dm_id, dm_inst_id)]
411 emptyNameSet -- No inlines (yet)
412 (dict_binds `andMonoBinds` defm_bind)
414 returnM (full_bind, [local_dm_id])
416 origin = ClassDeclOrigin
421 %************************************************************************
423 \subsection{Typechecking a method}
425 %************************************************************************
427 @tcMethodBind@ is used to type-check both default-method and
428 instance-decl method declarations. We must type-check methods one at a
429 time, because their signatures may have different contexts and
433 type MethodSpec = (Id, -- Global selector Id
434 Id, -- Local Id (class tyvars instantiated)
435 RenamedMonoBinds) -- Binding for the method
438 :: [(TyVar,TcTyVar)] -- Bindings for type environment
439 -> [TcTyVar] -- Instantiated type variables for the
440 -- enclosing class/instance decl.
441 -- They'll be signature tyvars, and we
442 -- want to check that they don't get bound
443 -- Always equal the range of the type envt
444 -> TcThetaType -- Available theta; it's just used for the error message
445 -> [Inst] -- Available from context, used to simplify constraints
446 -- from the method body
447 -> [RenamedSig] -- Pragmas (e.g. inline pragmas)
448 -> MethodSpec -- Details of this method
451 tcMethodBind xtve inst_tyvars inst_theta avail_insts prags
452 (sel_id, meth_id, meth_bind)
453 = -- Check the bindings; first adding inst_tyvars to the envt
454 -- so that we don't quantify over them in nested places
455 mkTcSig meth_id `thenM` \ meth_sig ->
457 tcExtendTyVarEnv2 xtve (
458 addErrCtxt (methodCtxt sel_id) $
460 tcMonoBinds meth_bind [meth_sig] NonRecursive
461 ) `thenM` \ ((meth_bind,_), meth_lie) ->
463 -- Now do context reduction. We simplify wrt both the local tyvars
464 -- and the ones of the class/instance decl, so that there is
467 -- op :: Eq a => a -> b -> a
469 -- We do this for each method independently to localise error messages
472 TySigInfo meth_id meth_tvs meth_theta _ local_meth_id _ _ = meth_sig
474 addErrCtxtM (sigCtxt sel_id inst_tyvars inst_theta (idType meth_id)) $
475 newDicts SignatureOrigin meth_theta `thenM` \ meth_dicts ->
477 all_tyvars = meth_tvs ++ inst_tyvars
478 all_insts = avail_insts ++ meth_dicts
481 (ptext SLIT("class or instance method") <+> quotes (ppr sel_id))
482 all_tyvars all_insts meth_lie `thenM` \ lie_binds ->
484 checkSigTyVars all_tyvars `thenM` \ all_tyvars' ->
487 sel_name = idName sel_id
488 inline_prags = [ (is_inl, phase)
489 | InlineSig is_inl name phase _ <- prags,
492 | prag@(SpecSig name _ _) <- prags,
495 -- Attach inline pragmas as appropriate
496 (final_meth_id, inlines)
497 | ((is_inline, phase) : _) <- inline_prags
498 = (meth_id `setInlinePragma` phase,
499 if is_inline then unitNameSet (idName meth_id) else emptyNameSet)
501 = (meth_id, emptyNameSet)
503 meth_tvs' = take (length meth_tvs) all_tyvars'
504 poly_meth_bind = AbsBinds meth_tvs'
505 (map instToId meth_dicts)
506 [(meth_tvs', final_meth_id, local_meth_id)]
508 (lie_binds `andMonoBinds` meth_bind)
511 -- Deal with specialisation pragmas
512 -- The sel_name is what appears in the pragma
513 tcExtendLocalValEnv2 [(sel_name, final_meth_id)] (
514 getLIE (tcSpecSigs spec_prags) `thenM` \ (spec_binds1, prag_lie) ->
516 -- The prag_lie for a SPECIALISE pragma will mention the function itself,
517 -- so we have to simplify them away right now lest they float outwards!
518 bindInstsOfLocalFuns prag_lie [final_meth_id] `thenM` \ spec_binds2 ->
519 returnM (spec_binds1 `andMonoBinds` spec_binds2)
520 ) `thenM` \ spec_binds ->
522 returnM (poly_meth_bind `andMonoBinds` spec_binds)
525 mkMethodBind :: InstOrigin
526 -> Class -> [TcType] -- Class and instance types
527 -> RenamedMonoBinds -- Method binding (pick the right one from in here)
529 -> TcM (Maybe Inst, -- Method inst
531 -- Find the binding for the specified method, or make
532 -- up a suitable default method if it isn't there
534 mkMethodBind origin clas inst_tys meth_binds (sel_id, dm_info)
535 = mkMethId origin clas sel_id inst_tys `thenM` \ (mb_inst, meth_id) ->
537 meth_name = idName meth_id
539 -- Figure out what method binding to use
540 -- If the user suppplied one, use it, else construct a default one
541 getSrcLocM `thenM` \ loc ->
542 (case find_bind (idName sel_id) meth_name meth_binds of
543 Just user_bind -> returnM user_bind
544 Nothing -> mkDefMethRhs origin clas inst_tys sel_id loc dm_info `thenM` \ rhs ->
545 returnM (FunMonoBind meth_name False -- Not infix decl
546 [mkSimpleMatch [] rhs placeHolderType loc] loc)
547 ) `thenM` \ meth_bind ->
549 returnM (mb_inst, (sel_id, meth_id, meth_bind))
551 mkMethId :: InstOrigin -> Class
552 -> Id -> [TcType] -- Selector, and instance types
553 -> TcM (Maybe Inst, Id)
555 -- mkMethId instantiates the selector Id at the specified types
556 mkMethId origin clas sel_id inst_tys
558 (tyvars,rho) = tcSplitForAllTys (idType sel_id)
559 rho_ty = ASSERT( length tyvars == length inst_tys )
560 substTyWith tyvars inst_tys rho
561 (preds,tau) = tcSplitPhiTy rho_ty
562 first_pred = head preds
564 -- The first predicate should be of form (C a b)
565 -- where C is the class in question
566 ASSERT( not (null preds) &&
567 case getClassPredTys_maybe first_pred of
568 { Just (clas1,tys) -> clas == clas1 ; Nothing -> False }
570 if isSingleton preds then
571 -- If it's the only one, make a 'method'
572 getInstLoc origin `thenM` \ inst_loc ->
573 newMethod inst_loc sel_id inst_tys preds tau `thenM` \ meth_inst ->
574 returnM (Just meth_inst, instToId meth_inst)
576 -- If it's not the only one we need to be careful
577 -- For example, given 'op' defined thus:
579 -- op :: (?x :: String) => a -> a
580 -- (mkMethId op T) should return an Inst with type
581 -- (?x :: String) => T -> T
582 -- That is, the class-op's context is still there.
583 -- BUT: it can't be a Method any more, because it breaks
584 -- INVARIANT 2 of methods. (See the data decl for Inst.)
585 newUnique `thenM` \ uniq ->
586 getSrcLocM `thenM` \ loc ->
588 real_tau = mkPhiTy (tail preds) tau
589 meth_id = mkUserLocal (getOccName sel_id) uniq real_tau loc
591 returnM (Nothing, meth_id)
593 -- The user didn't supply a method binding,
594 -- so we have to make up a default binding
595 -- The RHS of a default method depends on the default-method info
596 mkDefMethRhs origin clas inst_tys sel_id loc (DefMeth dm_name)
597 = -- An polymorphic default method
598 traceRn (text "mkDefMeth" <+> ppr dm_name) `thenM_`
599 returnM (HsVar dm_name)
601 mkDefMethRhs origin clas inst_tys sel_id loc NoDefMeth
602 = -- No default method
603 -- Warn only if -fwarn-missing-methods
604 doptM Opt_WarnMissingMethods `thenM` \ warn ->
605 warnTc (isInstDecl origin
607 && reportIfUnused (getOccName sel_id))
608 (omittedMethodWarn sel_id) `thenM_`
611 error_rhs = HsLam (mkSimpleMatch wild_pats simple_rhs placeHolderType loc)
612 simple_rhs = HsApp (HsVar (getName nO_METHOD_BINDING_ERROR_ID))
613 (HsLit (HsStringPrim (mkFastString (stringToUtf8 error_msg))))
614 error_msg = showSDoc (hcat [ppr loc, text "|", ppr sel_id ])
616 -- When the type is of form t1 -> t2 -> t3
617 -- make a default method like (\ _ _ -> noMethBind "blah")
618 -- rather than simply (noMethBind "blah")
619 -- Reason: if t1 or t2 are higher-ranked types we get n
620 -- silly ambiguity messages.
621 -- Example: f :: (forall a. Eq a => a -> a) -> Int
623 -- Here, tcSub tries to force (error "urk") to have the right type,
624 -- thus: f = \(x::forall a. Eq a => a->a) -> error "urk" (x t)
625 -- where 't' is fresh ty var. This leads directly to "ambiguous t".
627 -- NB: technically this changes the meaning of the default-default
628 -- method slightly, because `seq` can see the lambdas. Oh well.
629 (_,_,tau1) = tcSplitSigmaTy (idType sel_id)
630 (_,_,tau2) = tcSplitSigmaTy tau1
631 -- Need two splits because the selector can have a type like
632 -- forall a. Foo a => forall b. Eq b => ...
633 (arg_tys, _) = tcSplitFunTys tau2
634 wild_pats = [WildPat placeHolderType | ty <- arg_tys]
636 mkDefMethRhs origin clas inst_tys sel_id loc GenDefMeth
637 = -- A generic default method
638 -- If the method is defined generically, we can only do the job if the
639 -- instance declaration is for a single-parameter type class with
640 -- a type constructor applied to type arguments in the instance decl
641 -- (checkTc, so False provokes the error)
642 ASSERT( isInstDecl origin ) -- We never get here from a class decl
644 checkTc (isJust maybe_tycon)
645 (badGenericInstance sel_id (notSimple inst_tys)) `thenM_`
646 checkTc (isJust (tyConGenInfo tycon))
647 (badGenericInstance sel_id (notGeneric tycon)) `thenM_`
649 ioToTcRn (dumpIfSet opt_PprStyle_Debug "Generic RHS" stuff) `thenM_`
652 rhs = mkGenericRhs sel_id clas_tyvar tycon
654 stuff = vcat [ppr clas <+> ppr inst_tys,
655 nest 4 (ppr sel_id <+> equals <+> ppr rhs)]
657 -- The tycon is only used in the generic case, and in that
658 -- case we require that the instance decl is for a single-parameter
659 -- type class with type variable arguments:
660 -- instance (...) => C (T a b)
661 clas_tyvar = head (classTyVars clas)
662 Just tycon = maybe_tycon
663 maybe_tycon = case inst_tys of
664 [ty] -> case tcSplitTyConApp_maybe ty of
665 Just (tycon, arg_tys) | all tcIsTyVarTy arg_tys -> Just tycon
669 isInstDecl InstanceDeclOrigin = True
670 isInstDecl ClassDeclOrigin = False
675 -- The renamer just puts the selector ID as the binder in the method binding
676 -- but we must use the method name; so we substitute it here. Crude but simple.
677 find_bind sel_name meth_name (FunMonoBind op_name fix matches loc)
678 | op_name == sel_name = Just (FunMonoBind meth_name fix matches loc)
679 find_bind sel_name meth_name (AndMonoBinds b1 b2)
680 = find_bind sel_name meth_name b1 `seqMaybe` find_bind sel_name meth_name b2
681 find_bind sel_name meth_name other = Nothing -- Default case
683 -- Find the prags for this method, and replace the
684 -- selector name with the method name
685 find_prags sel_name meth_name [] = []
686 find_prags sel_name meth_name (SpecSig name ty loc : prags)
687 | name == sel_name = SpecSig meth_name ty loc : find_prags sel_name meth_name prags
688 find_prags sel_name meth_name (InlineSig sense name phase loc : prags)
689 | name == sel_name = InlineSig sense meth_name phase loc : find_prags sel_name meth_name prags
690 find_prags sel_name meth_name (prag:prags) = find_prags sel_name meth_name prags
698 = ptext SLIT("When checking the default methods for class") <+> quotes (ppr clas)
701 = ptext SLIT("In the definition for method") <+> quotes (ppr sel_id)
704 = hsep [ptext SLIT("Class"), quotes (ppr clas),
705 ptext SLIT("does not have a method"), quotes (ppr op)]
707 omittedMethodWarn sel_id
708 = ptext SLIT("No explicit method nor default method for") <+> quotes (ppr sel_id)
710 badGenericInstance sel_id because
711 = sep [ptext SLIT("Can't derive generic code for") <+> quotes (ppr sel_id),
715 = vcat [ptext SLIT("because the instance type(s)"),
716 nest 2 (ppr inst_tys),
717 ptext SLIT("is not a simple type of form (T a b c)")]
720 = vcat [ptext SLIT("because the instance type constructor") <+> quotes (ppr tycon) <+>
721 ptext SLIT("was not compiled with -fgenerics")]
724 = ptext SLIT("Can't mix generic and non-generic equations for class method") <+> quotes (ppr op)