2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcInstDecls]{Typechecking instance declarations}
7 module TcInstDcls ( tcInstDecls1, tcIfaceInstDecls,
8 tcInstDecls2, tcAddDeclCtxt ) where
10 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlag(..) )
15 import HsSyn ( InstDecl(..), TyClDecl(..), HsType(..),
16 MonoBinds(..), HsExpr(..), HsLit(..), Sig(..), HsTyVarBndr(..),
17 andMonoBindList, collectMonoBinders,
18 isClassDecl, isSourceInstDecl, toHsType
20 import RnHsSyn ( RenamedHsBinds, RenamedInstDecl,
21 RenamedMonoBinds, RenamedTyClDecl, RenamedHsType,
22 extractHsTyVars, maybeGenericMatch
24 import TcHsSyn ( TcMonoBinds, mkHsConApp )
25 import TcBinds ( tcSpecSigs )
26 import TcClassDcl ( tcMethodBind, mkMethodBind, badMethodErr )
28 import TcMType ( tcInstType, checkValidTheta, checkValidInstHead, instTypeErr,
29 checkAmbiguity, UserTypeCtxt(..), SourceTyCtxt(..) )
30 import TcType ( mkClassPred, mkTyVarTy, tcSplitForAllTys, tyVarsOfType,
31 tcSplitSigmaTy, getClassPredTys, tcSplitPredTy_maybe,
34 import Inst ( InstOrigin(..), newDicts, instToId, showLIE )
35 import TcDeriv ( tcDeriving )
36 import TcEnv ( tcExtendGlobalValEnv, tcExtendLocalValEnv2,
37 tcLookupClass, tcExtendTyVarEnv2,
38 tcExtendInstEnv, tcExtendLocalInstEnv, tcLookupGlobalId,
39 InstInfo(..), pprInstInfo, simpleInstInfoTyCon,
40 simpleInstInfoTy, newDFunName
42 import PprType ( pprClassPred )
43 import TcMonoType ( tcSigPolyId, tcHsTyVars, kcHsSigType, tcHsType, tcHsSigType )
44 import TcUnify ( checkSigTyVars )
45 import TcSimplify ( tcSimplifyCheck, tcSimplifyTop )
46 import HscTypes ( DFunId )
47 import Subst ( mkTyVarSubst, substTheta )
48 import DataCon ( classDataCon )
49 import Class ( Class, classBigSig )
50 import Var ( idName, idType )
52 import Id ( setIdLocalExported )
53 import MkId ( mkDictFunId, unsafeCoerceId, rUNTIME_ERROR_ID )
54 import FunDeps ( checkInstFDs )
55 import Generics ( validGenericInstanceType )
56 import Name ( getSrcLoc )
57 import NameSet ( unitNameSet, emptyNameSet, nameSetToList )
58 import TyCon ( TyCon )
59 import TysWiredIn ( genericTyCons )
60 import SrcLoc ( SrcLoc )
61 import Unique ( Uniquable(..) )
62 import Util ( lengthExceeds, isSingleton )
63 import BasicTypes ( NewOrData(..) )
64 import UnicodeUtil ( stringToUtf8 )
65 import ErrUtils ( dumpIfSet_dyn )
66 import ListSetOps ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc,
67 assocElts, extendAssoc_C, equivClassesByUniq, minusList
69 import Maybe ( catMaybes )
70 import List ( partition )
75 Typechecking instance declarations is done in two passes. The first
76 pass, made by @tcInstDecls1@, collects information to be used in the
79 This pre-processed info includes the as-yet-unprocessed bindings
80 inside the instance declaration. These are type-checked in the second
81 pass, when the class-instance envs and GVE contain all the info from
82 all the instance and value decls. Indeed that's the reason we need
83 two passes over the instance decls.
86 Here is the overall algorithm.
87 Assume that we have an instance declaration
89 instance c => k (t tvs) where b
93 $LIE_c$ is the LIE for the context of class $c$
95 $betas_bar$ is the free variables in the class method type, excluding the
98 $LIE_cop$ is the LIE constraining a particular class method
100 $tau_cop$ is the tau type of a class method
102 $LIE_i$ is the LIE for the context of instance $i$
104 $X$ is the instance constructor tycon
106 $gammas_bar$ is the set of type variables of the instance
108 $LIE_iop$ is the LIE for a particular class method instance
110 $tau_iop$ is the tau type for this instance of a class method
112 $alpha$ is the class variable
114 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
116 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
119 ToDo: Update the list above with names actually in the code.
123 First, make the LIEs for the class and instance contexts, which means
124 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
125 and make LIElistI and LIEI.
127 Then process each method in turn.
129 order the instance methods according to the ordering of the class methods
131 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
133 Create final dictionary function from bindings generated already
135 df = lambda inst_tyvars
142 in <op1,op2,...,opn,sd1,...,sdm>
144 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
145 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
149 %************************************************************************
151 \subsection{Extracting instance decls}
153 %************************************************************************
155 Gather up the instance declarations from their various sources
158 tcInstDecls1 -- Deal with both source-code and imported instance decls
159 :: [RenamedTyClDecl] -- For deriving stuff
160 -> [RenamedInstDecl] -- Source code instance decls
161 -> TcM (TcGblEnv, -- The full inst env
162 [InstInfo], -- Source-code instance decls to process;
163 -- contains all dfuns for this module
164 RenamedHsBinds, -- Supporting bindings for derived instances
165 FreeVars) -- And the free vars of the derived code
167 tcInstDecls1 tycl_decls inst_decls
169 -- Stop if addInstInfos etc discovers any errors
170 -- (they recover, so that we get more than one error each round)
172 (src_inst_decls, iface_inst_decls) = partition isSourceInstDecl inst_decls
175 -- (0) Deal with the imported instance decls
176 tcIfaceInstDecls iface_inst_decls `thenM` \ imp_dfuns ->
177 tcExtendInstEnv imp_dfuns $
179 -- (1) Do the ordinary instance declarations
180 mappM tcLocalInstDecl1 src_inst_decls `thenM` \ local_inst_infos ->
183 local_inst_info = catMaybes local_inst_infos
184 clas_decls = filter isClassDecl tycl_decls
186 -- (2) Instances from generic class declarations
187 getGenericInstances clas_decls `thenM` \ generic_inst_info ->
189 -- Next, construct the instance environment so far, consisting of
190 -- a) imported instance decls (from this module)
191 -- b) local instance decls
192 -- c) generic instances
193 tcExtendLocalInstEnv local_inst_info $
194 tcExtendLocalInstEnv generic_inst_info $
196 -- (3) Compute instances from "deriving" clauses;
197 -- note that we only do derivings for things in this module;
198 -- we ignore deriving decls from interfaces!
199 -- This stuff computes a context for the derived instance decl, so it
200 -- needs to know about all the instances possible; hence inst_env4
201 tcDeriving tycl_decls `thenM` \ (deriv_inst_info, deriv_binds, fvs) ->
202 tcExtendLocalInstEnv deriv_inst_info $
204 getGblEnv `thenM` \ gbl_env ->
206 generic_inst_info ++ deriv_inst_info ++ local_inst_info,
211 tcLocalInstDecl1 :: RenamedInstDecl
212 -> TcM (Maybe InstInfo) -- Nothing if there was an error
213 -- A source-file instance declaration
214 -- Type-check all the stuff before the "where"
216 -- We check for respectable instance type, and context
217 -- but only do this for non-imported instance decls.
218 -- Imported ones should have been checked already, and may indeed
219 -- contain something illegal in normal Haskell, notably
220 -- instance CCallable [Char]
221 tcLocalInstDecl1 decl@(InstDecl poly_ty binds uprags Nothing src_loc)
222 = -- Prime error recovery, set source location
223 recoverM (returnM Nothing) $
225 addErrCtxt (instDeclCtxt poly_ty) $
227 -- Typecheck the instance type itself. We can't use
228 -- tcHsSigType, because it's not a valid user type.
229 kcHsSigType poly_ty `thenM_`
230 tcHsType poly_ty `thenM` \ poly_ty' ->
232 (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
234 checkValidTheta InstThetaCtxt theta `thenM_`
235 checkAmbiguity tyvars theta (tyVarsOfType tau) `thenM_`
236 checkValidInstHead tau `thenM` \ (clas,inst_tys) ->
237 checkTc (checkInstFDs theta clas inst_tys)
238 (instTypeErr (pprClassPred clas inst_tys) msg) `thenM_`
239 newDFunName clas inst_tys src_loc `thenM` \ dfun_name ->
240 returnM (Just (InstInfo { iDFunId = mkDictFunId dfun_name clas tyvars inst_tys theta,
241 iBinds = binds, iPrags = uprags }))
243 msg = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
246 Imported instance declarations
249 tcIfaceInstDecls :: [RenamedInstDecl] -> TcM [DFunId]
250 -- Deal with the instance decls,
251 tcIfaceInstDecls decls = mappM tcIfaceInstDecl decls
253 tcIfaceInstDecl :: RenamedInstDecl -> TcM DFunId
254 -- An interface-file instance declaration
255 -- Should be in scope by now, because we should
256 -- have sucked in its interface-file definition
257 -- So it will be replete with its unfolding etc
258 tcIfaceInstDecl decl@(InstDecl poly_ty binds uprags (Just dfun_name) src_loc)
259 = tcLookupGlobalId dfun_name
263 %************************************************************************
265 \subsection{Extracting generic instance declaration from class declarations}
267 %************************************************************************
269 @getGenericInstances@ extracts the generic instance declarations from a class
270 declaration. For exmaple
275 op{ x+y } (Inl v) = ...
276 op{ x+y } (Inr v) = ...
277 op{ x*y } (v :*: w) = ...
280 gives rise to the instance declarations
282 instance C (x+y) where
286 instance C (x*y) where
294 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo]
295 getGenericInstances class_decls
296 = mappM get_generics class_decls `thenM` \ gen_inst_infos ->
298 gen_inst_info = concat gen_inst_infos
300 if null gen_inst_info then
303 getDOpts `thenM` \ dflags ->
304 ioToTcRn (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances"
305 (vcat (map pprInstInfo gen_inst_info)))
307 returnM gen_inst_info
309 get_generics decl@(ClassDecl {tcdMeths = Nothing})
310 = returnM [] -- Imported class decls
312 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = Just def_methods, tcdLoc = loc})
314 = returnM [] -- The comon case: no generic default methods
316 | otherwise -- A source class decl with generic default methods
317 = recoverM (returnM []) $
319 tcLookupClass class_name `thenM` \ clas ->
321 -- Make an InstInfo out of each group
322 mappM (mkGenericInstance clas loc) groups `thenM` \ inst_infos ->
324 -- Check that there is only one InstInfo for each type constructor
325 -- The main way this can fail is if you write
326 -- f {| a+b |} ... = ...
327 -- f {| x+y |} ... = ...
328 -- Then at this point we'll have an InstInfo for each
330 tc_inst_infos :: [(TyCon, InstInfo)]
331 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
333 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
334 group `lengthExceeds` 1]
335 get_uniq (tc,_) = getUnique tc
337 mappM (addErrTc . dupGenericInsts) bad_groups `thenM_`
339 -- Check that there is an InstInfo for each generic type constructor
341 missing = genericTyCons `minusList` [tc | (tc,_) <- tc_inst_infos]
343 checkTc (null missing) (missingGenericInstances missing) `thenM_`
348 -- Group the declarations by type pattern
349 groups :: [(RenamedHsType, RenamedMonoBinds)]
350 groups = assocElts (getGenericBinds def_methods)
353 ---------------------------------
354 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
355 -- Takes a group of method bindings, finds the generic ones, and returns
356 -- them in finite map indexed by the type parameter in the definition.
358 getGenericBinds EmptyMonoBinds = emptyAssoc
359 getGenericBinds (AndMonoBinds m1 m2)
360 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
362 getGenericBinds (FunMonoBind id infixop matches loc)
363 = mapAssoc wrap (foldl add emptyAssoc matches)
364 -- Using foldl not foldr is vital, else
365 -- we reverse the order of the bindings!
367 add env match = case maybeGenericMatch match of
369 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
371 wrap ms = FunMonoBind id infixop ms loc
373 ---------------------------------
374 mkGenericInstance :: Class -> SrcLoc
375 -> (RenamedHsType, RenamedMonoBinds)
378 mkGenericInstance clas loc (hs_ty, binds)
379 -- Make a generic instance declaration
380 -- For example: instance (C a, C b) => C (a+b) where { binds }
382 = -- Extract the universally quantified type variables
384 sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
386 tcHsTyVars sig_tvs (kcHsSigType hs_ty) $ \ tyvars ->
388 -- Type-check the instance type, and check its form
389 tcHsSigType GenPatCtxt hs_ty `thenM` \ inst_ty ->
390 checkTc (validGenericInstanceType inst_ty)
391 (badGenericInstanceType binds) `thenM_`
393 -- Make the dictionary function.
394 newDFunName clas [inst_ty] loc `thenM` \ dfun_name ->
396 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
397 dfun_id = mkDictFunId dfun_name clas tyvars [inst_ty] inst_theta
400 returnM (InstInfo { iDFunId = dfun_id, iBinds = binds, iPrags = [] })
404 %************************************************************************
406 \subsection{Type-checking instance declarations, pass 2}
408 %************************************************************************
411 tcInstDecls2 :: [InstInfo] -> TcM TcMonoBinds
412 tcInstDecls2 inst_decls
413 = mappM tcInstDecl2 inst_decls `thenM` \ binds_s ->
414 returnM (andMonoBindList binds_s)
417 ======= New documentation starts here (Sept 92) ==============
419 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
420 the dictionary function for this instance declaration. For example
422 instance Foo a => Foo [a] where
426 might generate something like
428 dfun.Foo.List dFoo_a = let op1 x = ...
434 HOWEVER, if the instance decl has no context, then it returns a
435 bigger @HsBinds@ with declarations for each method. For example
437 instance Foo [a] where
443 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
444 const.Foo.op1.List a x = ...
445 const.Foo.op2.List a y = ...
447 This group may be mutually recursive, because (for example) there may
448 be no method supplied for op2 in which case we'll get
450 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
452 that is, the default method applied to the dictionary at this type.
454 What we actually produce in either case is:
456 AbsBinds [a] [dfun_theta_dicts]
457 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
458 { d = (sd1,sd2, ..., op1, op2, ...)
463 The "maybe" says that we only ask AbsBinds to make global constant methods
464 if the dfun_theta is empty.
467 For an instance declaration, say,
469 instance (C1 a, C2 b) => C (T a b) where
472 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
473 function whose type is
475 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
477 Notice that we pass it the superclass dictionaries at the instance type; this
478 is the ``Mark Jones optimisation''. The stuff before the "=>" here
479 is the @dfun_theta@ below.
481 First comes the easy case of a non-local instance decl.
485 tcInstDecl2 :: InstInfo -> TcM TcMonoBinds
487 tcInstDecl2 (NewTypeDerived { iDFunId = dfun_id })
488 = tcInstType InstTv (idType dfun_id) `thenM` \ (inst_tyvars', dfun_theta', inst_head') ->
489 newDicts InstanceDeclOrigin dfun_theta' `thenM` \ rep_dicts ->
491 rep_dict_id = ASSERT( isSingleton rep_dicts )
492 instToId (head rep_dicts) -- Derived newtypes have just one dict arg
494 body = TyLam inst_tyvars' $
495 DictLam [rep_dict_id] $
496 (HsVar unsafeCoerceId `TyApp` [idType rep_dict_id, inst_head'])
499 -- You might wonder why we have the 'coerce'. It's because the
500 -- type equality mechanism isn't clever enough; see comments with Type.eqType.
501 -- So Lint complains if we don't have this.
503 returnM (VarMonoBind dfun_id body)
505 tcInstDecl2 (InstInfo { iDFunId = dfun_id, iBinds = monobinds, iPrags = uprags })
506 = -- Prime error recovery
507 recoverM (returnM EmptyMonoBinds) $
508 addSrcLoc (getSrcLoc dfun_id) $
509 addErrCtxt (instDeclCtxt (toHsType (idType dfun_id))) $
511 inst_ty = idType dfun_id
512 (inst_tyvars, _) = tcSplitForAllTys inst_ty
513 -- The tyvars of the instance decl scope over the 'where' part
514 -- Those tyvars are inside the dfun_id's type, which is a bit
515 -- bizarre, but OK so long as you realise it!
518 -- Instantiate the instance decl with tc-style type variables
519 tcInstType InstTv inst_ty `thenM` \ (inst_tyvars', dfun_theta', inst_head') ->
521 Just pred = tcSplitPredTy_maybe inst_head'
522 (clas, inst_tys') = getClassPredTys pred
523 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
525 -- Instantiate the super-class context with inst_tys
526 sc_theta' = substTheta (mkTyVarSubst class_tyvars inst_tys') sc_theta
527 origin = InstanceDeclOrigin
529 -- Create dictionary Ids from the specified instance contexts.
530 newDicts origin sc_theta' `thenM` \ sc_dicts ->
531 newDicts origin dfun_theta' `thenM` \ dfun_arg_dicts ->
532 newDicts origin [pred] `thenM` \ [this_dict] ->
533 -- Default-method Ids may be mentioned in synthesised RHSs,
534 -- but they'll already be in the environment.
536 -- Check that all the method bindings come from this class
537 mkMethodBinds clas inst_tys' op_items monobinds `thenM` \ (meth_insts, meth_infos) ->
539 let -- These insts are in scope; quite a few, eh?
540 avail_insts = [this_dict] ++ dfun_arg_dicts ++
541 sc_dicts ++ meth_insts
543 xtve = inst_tyvars `zip` inst_tyvars'
544 tc_meth = tcMethodBind xtve inst_tyvars' dfun_theta' avail_insts uprags
546 mappM tc_meth meth_infos `thenM` \ meth_binds_s ->
548 -- Figure out bindings for the superclass context
549 tcSuperClasses inst_tyvars' dfun_arg_dicts sc_dicts
550 `thenM` \ (zonked_inst_tyvars, sc_binds_inner, sc_binds_outer) ->
552 -- Deal with SPECIALISE instance pragmas by making them
553 -- look like SPECIALISE pragmas for the dfun
555 spec_prags = [ SpecSig (idName dfun_id) ty loc
556 | SpecInstSig ty loc <- uprags]
559 tcExtendGlobalValEnv [dfun_id] (
560 tcExtendTyVarEnv2 xtve $
561 tcExtendLocalValEnv2 [(idName sel_id, tcSigPolyId sig)
562 | (sel_id, sig, _) <- meth_infos] $
563 -- Map sel_id to the local method name we are using
564 tcSpecSigs spec_prags
565 ) `thenM` \ prag_binds ->
567 -- Create the result bindings
569 local_dfun_id = setIdLocalExported dfun_id
570 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
572 dict_constr = classDataCon clas
573 scs_and_meths = map instToId (sc_dicts ++ meth_insts)
574 this_dict_id = instToId this_dict
575 inlines | null dfun_arg_dicts = emptyNameSet
576 | otherwise = unitNameSet (idName dfun_id)
577 -- Always inline the dfun; this is an experimental decision
578 -- because it makes a big performance difference sometimes.
579 -- Often it means we can do the method selection, and then
580 -- inline the method as well. Marcin's idea; see comments below.
582 -- BUT: don't inline it if it's a constant dictionary;
583 -- we'll get all the benefit without inlining, and we get
584 -- a **lot** of code duplication if we inline it
588 = -- Blatant special case for CCallable, CReturnable
589 -- If the dictionary is empty then we should never
590 -- select anything from it, so we make its RHS just
591 -- emit an error message. This in turn means that we don't
592 -- mention the constructor, which doesn't exist for CCallable, CReturnable
593 -- Hardly beautiful, but only three extra lines.
594 HsApp (TyApp (HsVar rUNTIME_ERROR_ID) [idType this_dict_id])
595 (HsLit (HsStringPrim (mkFastString (stringToUtf8 msg))))
597 | otherwise -- The common case
598 = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
599 -- We don't produce a binding for the dict_constr; instead we
600 -- rely on the simplifier to unfold this saturated application
601 -- We do this rather than generate an HsCon directly, because
602 -- it means that the special cases (e.g. dictionary with only one
603 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
604 -- than needing to be repeated here.
607 msg = "Compiler error: bad dictionary " ++ showSDoc (ppr clas)
609 dict_bind = VarMonoBind this_dict_id dict_rhs
610 meth_binds = andMonoBindList meth_binds_s
611 all_binds = sc_binds_inner `AndMonoBinds` meth_binds `AndMonoBinds` dict_bind
615 (map instToId dfun_arg_dicts)
616 [(inst_tyvars', local_dfun_id, this_dict_id)]
619 showLIE "instance" `thenM_`
620 returnM (main_bind `AndMonoBinds` prag_binds `AndMonoBinds` sc_binds_outer)
625 We have to be very, very careful when generating superclasses, lest we
626 accidentally build a loop. Here's an example:
630 class S a => C a where { opc :: a -> a }
631 class S b => D b where { opd :: b -> b }
639 From (instance C Int) we get the constraint set {ds1:S Int, dd:D Int}
640 Simplifying, we may well get:
641 $dfCInt = :C ds1 (opd dd)
644 Notice that we spot that we can extract ds1 from dd.
646 Alas! Alack! We can do the same for (instance D Int):
648 $dfDInt = :D ds2 (opc dc)
652 And now we've defined the superclass in terms of itself.
655 Solution: treat the superclass context separately, and simplify it
656 all the way down to nothing on its own. Don't toss any 'free' parts
657 out to be simplified together with other bits of context.
658 Hence the tcSimplifyTop below.
660 At a more basic level, don't include this_dict in the context wrt
661 which we simplify sc_dicts, else sc_dicts get bound by just selecting
665 tcSuperClasses inst_tyvars' dfun_arg_dicts sc_dicts
666 = addErrCtxt superClassCtxt $
667 getLIE (tcSimplifyCheck doc inst_tyvars'
669 sc_dicts) `thenM` \ (sc_binds1, sc_lie) ->
671 -- It's possible that the superclass stuff might have done unification
672 checkSigTyVars inst_tyvars' `thenM` \ zonked_inst_tyvars ->
674 -- We must simplify this all the way down
675 -- lest we build superclass loops
676 -- See notes about superclass loops above
677 tcSimplifyTop sc_lie `thenM` \ sc_binds2 ->
679 returnM (zonked_inst_tyvars, sc_binds1, sc_binds2)
682 doc = ptext SLIT("instance declaration superclass context")
686 mkMethodBinds clas inst_tys' op_items monobinds
687 = -- Check that all the method bindings come from this class
688 mappM (addErrTc . badMethodErr clas) bad_bndrs `thenM_`
690 -- Make the method bindings
691 mapAndUnzipM mk_method_bind op_items
694 mk_method_bind op_item = mkMethodBind InstanceDeclOrigin clas
695 inst_tys' monobinds op_item
697 -- Find any definitions in monobinds that aren't from the class
698 sel_names = [idName sel_id | (sel_id, _) <- op_items]
699 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
703 ------------------------------
704 Inlining dfuns unconditionally
705 ------------------------------
707 The code above unconditionally inlines dict funs. Here's why.
708 Consider this program:
710 test :: Int -> Int -> Bool
711 test x y = (x,y) == (y,x) || test y x
712 -- Recursive to avoid making it inline.
714 This needs the (Eq (Int,Int)) instance. If we inline that dfun
715 the code we end up with is good:
718 \r -> case ==# [ww ww1] of wild {
719 PrelBase.False -> Test.$wtest ww1 ww;
721 case ==# [ww1 ww] of wild1 {
722 PrelBase.False -> Test.$wtest ww1 ww;
723 PrelBase.True -> PrelBase.True [];
726 Test.test = \r [w w1]
729 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
732 If we don't inline the dfun, the code is not nearly as good:
734 (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
735 PrelBase.:DEq tpl1 tpl2 -> tpl2;
740 let { y = PrelBase.I#! [ww1]; } in
741 let { x = PrelBase.I#! [ww]; } in
742 let { sat_slx = PrelTup.(,)! [y x]; } in
743 let { sat_sly = PrelTup.(,)! [x y];
745 case == sat_sly sat_slx of wild {
746 PrelBase.False -> Test.$wtest ww1 ww;
747 PrelBase.True -> PrelBase.True [];
754 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
757 Why doesn't GHC inline $fEq? Because it looks big:
759 PrelTup.zdfEqZ1T{-rcX-}
760 = \ @ a{-reT-} :: * @ b{-reS-} :: *
761 zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
762 zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
764 zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
765 zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
767 zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
768 zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
770 zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
771 zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
772 ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
774 of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
776 of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
778 (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
779 (zeze{-rf0-} a2{-reZ-} b2{-reY-})
783 a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
784 a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
785 b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
786 PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
788 PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
790 and it's not as bad as it seems, because it's further dramatically
791 simplified: only zeze2 is extracted and its body is simplified.
794 %************************************************************************
796 \subsection{Error messages}
798 %************************************************************************
801 tcAddDeclCtxt decl thing_inside
802 = addSrcLoc (tcdLoc decl) $
807 ClassDecl {} -> "class"
808 TySynonym {} -> "type synonym"
809 TyData {tcdND = NewType} -> "newtype"
810 TyData {tcdND = DataType} -> "data type"
812 ctxt = hsep [ptext SLIT("In the"), text thing,
813 ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
815 instDeclCtxt inst_ty = ptext SLIT("In the instance declaration for") <+> quotes doc
817 doc = case inst_ty of
818 HsForAllTy _ _ (HsPredTy pred) -> ppr pred
819 HsPredTy pred -> ppr pred
820 other -> ppr inst_ty -- Don't expect this
824 badGenericInstanceType binds
825 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
828 missingGenericInstances missing
829 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
831 dupGenericInsts tc_inst_infos
832 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
833 nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
834 ptext SLIT("All the type patterns for a generic type constructor must be identical")
837 ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
839 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
840 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")