2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcInstDecls]{Typechecking instance declarations}
7 module TcInstDcls ( tcInstDecls1, tcInstDecls2, tcAddDeclCtxt ) where
9 #include "HsVersions.h"
12 import CmdLineOpts ( DynFlag(..) )
14 import HsSyn ( HsDecl(..), InstDecl(..), TyClDecl(..), HsType(..),
15 MonoBinds(..), HsExpr(..), HsLit(..), Sig(..), HsTyVarBndr(..),
16 andMonoBindList, collectMonoBinders,
17 isClassDecl, isIfaceInstDecl, toHsType
19 import RnHsSyn ( RenamedHsBinds, RenamedInstDecl, RenamedHsDecl,
20 RenamedMonoBinds, RenamedTyClDecl, RenamedHsType,
21 extractHsTyVars, maybeGenericMatch
23 import TcHsSyn ( TcMonoBinds, mkHsConApp )
24 import TcBinds ( tcSpecSigs )
25 import TcClassDcl ( tcMethodBind, badMethodErr )
27 import TcMType ( tcInstSigTyVars, checkValidTheta, checkValidInstHead, instTypeErr,
28 UserTypeCtxt(..), SourceTyCtxt(..) )
29 import TcType ( tcSplitDFunTy, mkClassPred, mkTyVarTy, mkTyVarTys,
30 tcSplitSigmaTy, tcSplitPredTy_maybe, getClassPredTys,
33 import Inst ( InstOrigin(..),
35 LIE, mkLIE, emptyLIE, plusLIE, plusLIEs )
36 import TcDeriv ( tcDeriving )
37 import TcEnv ( TcEnv, tcExtendGlobalValEnv,
38 tcExtendTyVarEnvForMeths, tcLookupId, tcLookupClass,
39 InstInfo(..), pprInstInfo, simpleInstInfoTyCon,
40 simpleInstInfoTy, newDFunName
42 import InstEnv ( InstEnv, extendInstEnv )
43 import PprType ( pprClassPred )
44 import TcMonoType ( tcHsTyVars, kcHsSigType, tcHsType, tcHsSigType )
45 import TcUnify ( checkSigTyVars )
46 import TcSimplify ( tcSimplifyCheck )
47 import HscTypes ( HomeSymbolTable, DFunId,
48 ModDetails(..), PackageInstEnv, PersistentRenamerState
51 import Subst ( substTy, substTheta )
52 import DataCon ( classDataCon )
53 import Class ( Class, classBigSig )
54 import Var ( idName, idType )
55 import VarSet ( emptyVarSet )
56 import Id ( setIdLocalExported )
57 import MkId ( mkDictFunId )
58 import FunDeps ( checkInstFDs )
59 import Generics ( validGenericInstanceType )
60 import Module ( Module, foldModuleEnv )
61 import Name ( getSrcLoc )
62 import NameSet ( unitNameSet, emptyNameSet, nameSetToList )
63 import PrelInfo ( eRROR_ID )
64 import TyCon ( TyCon )
65 import Subst ( mkTopTyVarSubst, substTheta )
66 import TysWiredIn ( genericTyCons )
68 import SrcLoc ( SrcLoc )
69 import Unique ( Uniquable(..) )
70 import Util ( lengthExceeds )
71 import BasicTypes ( NewOrData(..), Fixity )
72 import ErrUtils ( dumpIfSet_dyn )
73 import ListSetOps ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc,
74 assocElts, extendAssoc_C,
75 equivClassesByUniq, minusList
77 import List ( partition )
81 Typechecking instance declarations is done in two passes. The first
82 pass, made by @tcInstDecls1@, collects information to be used in the
85 This pre-processed info includes the as-yet-unprocessed bindings
86 inside the instance declaration. These are type-checked in the second
87 pass, when the class-instance envs and GVE contain all the info from
88 all the instance and value decls. Indeed that's the reason we need
89 two passes over the instance decls.
92 Here is the overall algorithm.
93 Assume that we have an instance declaration
95 instance c => k (t tvs) where b
99 $LIE_c$ is the LIE for the context of class $c$
101 $betas_bar$ is the free variables in the class method type, excluding the
104 $LIE_cop$ is the LIE constraining a particular class method
106 $tau_cop$ is the tau type of a class method
108 $LIE_i$ is the LIE for the context of instance $i$
110 $X$ is the instance constructor tycon
112 $gammas_bar$ is the set of type variables of the instance
114 $LIE_iop$ is the LIE for a particular class method instance
116 $tau_iop$ is the tau type for this instance of a class method
118 $alpha$ is the class variable
120 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
122 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
125 ToDo: Update the list above with names actually in the code.
129 First, make the LIEs for the class and instance contexts, which means
130 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
131 and make LIElistI and LIEI.
133 Then process each method in turn.
135 order the instance methods according to the ordering of the class methods
137 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
139 Create final dictionary function from bindings generated already
141 df = lambda inst_tyvars
148 in <op1,op2,...,opn,sd1,...,sdm>
150 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
151 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
155 %************************************************************************
157 \subsection{Extracting instance decls}
159 %************************************************************************
161 Gather up the instance declarations from their various sources
164 tcInstDecls1 :: PackageInstEnv
165 -> PersistentRenamerState
166 -> HomeSymbolTable -- Contains instances
167 -> TcEnv -- Contains IdInfo for dfun ids
168 -> (Name -> Maybe Fixity) -- for deriving Show and Read
169 -> Module -- Module for deriving
171 -> TcM (PackageInstEnv, InstEnv, [InstInfo], RenamedHsBinds)
173 tcInstDecls1 inst_env0 prs hst unf_env get_fixity this_mod decls
175 inst_decls = [inst_decl | InstD inst_decl <- decls]
176 tycl_decls = [decl | TyClD decl <- decls]
177 clas_decls = filter isClassDecl tycl_decls
178 (imported_inst_ds, local_inst_ds) = partition isIfaceInstDecl inst_decls
180 -- (1) Do the ordinary instance declarations
181 mapNF_Tc tcInstDecl1 local_inst_ds `thenNF_Tc` \ local_inst_infos ->
182 mapNF_Tc tcInstDecl1 imported_inst_ds `thenNF_Tc` \ imported_inst_infos ->
184 -- (2) Instances from generic class declarations
185 getGenericInstances clas_decls `thenTc` \ generic_inst_info ->
187 -- Next, construct the instance environment so far, consisting of
188 -- a) cached non-home-package InstEnv (gotten from pcs) pcs_insts pcs
189 -- b) imported instance decls (not in the home package) inst_env1
190 -- c) other modules in this package (gotten from hst) inst_env2
191 -- d) local instance decls inst_env3
192 -- e) generic instances inst_env4
193 -- The result of (b) replaces the cached InstEnv in the PCS
195 local_inst_info = concat local_inst_infos
196 imported_inst_info = concat imported_inst_infos
197 hst_dfuns = foldModuleEnv ((++) . md_insts) [] hst
200 -- pprTrace "tcInstDecls" (vcat [ppr imported_dfuns, ppr hst_dfuns]) $
202 addInstInfos inst_env0 imported_inst_info `thenNF_Tc` \ inst_env1 ->
203 addInstDFuns inst_env1 hst_dfuns `thenNF_Tc` \ inst_env2 ->
204 addInstInfos inst_env2 local_inst_info `thenNF_Tc` \ inst_env3 ->
205 addInstInfos inst_env3 generic_inst_info `thenNF_Tc` \ inst_env4 ->
207 -- (3) Compute instances from "deriving" clauses;
208 -- note that we only do derivings for things in this module;
209 -- we ignore deriving decls from interfaces!
210 -- This stuff computes a context for the derived instance decl, so it
211 -- needs to know about all the instances possible; hence inst_env4
212 tcDeriving prs this_mod inst_env4 get_fixity tycl_decls
213 `thenTc` \ (deriv_inst_info, deriv_binds) ->
214 addInstInfos inst_env4 deriv_inst_info `thenNF_Tc` \ final_inst_env ->
218 generic_inst_info ++ deriv_inst_info ++ local_inst_info,
221 addInstInfos :: InstEnv -> [InstInfo] -> NF_TcM InstEnv
222 addInstInfos inst_env infos = addInstDFuns inst_env (map iDFunId infos)
224 addInstDFuns :: InstEnv -> [DFunId] -> NF_TcM InstEnv
225 addInstDFuns inst_env dfuns
226 = getDOptsTc `thenTc` \ dflags ->
228 (inst_env', errs) = extendInstEnv dflags inst_env dfuns
230 addErrsTc errs `thenNF_Tc_`
231 traceTc (text "Adding instances:" <+> vcat (map pp dfuns)) `thenTc_`
234 pp dfun = ppr dfun <+> dcolon <+> ppr (idType dfun)
238 tcInstDecl1 :: RenamedInstDecl -> NF_TcM [InstInfo]
239 -- Deal with a single instance declaration
240 -- Type-check all the stuff before the "where"
241 tcInstDecl1 decl@(InstDecl poly_ty binds uprags maybe_dfun_name src_loc)
242 = -- Prime error recovery, set source location
243 recoverNF_Tc (returnNF_Tc []) $
244 tcAddSrcLoc src_loc $
245 tcAddErrCtxt (instDeclCtxt poly_ty) $
247 -- Typecheck the instance type itself. We can't use
248 -- tcHsSigType, because it's not a valid user type.
249 kcHsSigType poly_ty `thenTc_`
250 tcHsType poly_ty `thenTc` \ poly_ty' ->
252 (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
253 (clas,inst_tys) = case tcSplitPredTy_maybe tau of { Just st -> getClassPredTys st }
254 -- The checkValidInstHead makes sure these splits succeed
256 (case maybe_dfun_name of
257 Nothing -> -- A source-file instance declaration
258 -- Check for respectable instance type, and context
259 -- but only do this for non-imported instance decls.
260 -- Imported ones should have been checked already, and may indeed
261 -- contain something illegal in normal Haskell, notably
262 -- instance CCallable [Char]
263 checkValidTheta InstThetaCtxt theta `thenTc_`
264 checkValidInstHead tau `thenTc_`
265 checkTc (checkInstFDs theta clas inst_tys)
266 (instTypeErr (pprClassPred clas inst_tys) msg) `thenTc_`
267 newDFunName clas inst_tys src_loc `thenTc` \ dfun_name ->
268 returnTc (mkDictFunId dfun_name clas tyvars inst_tys theta)
270 Just dfun_name -> -- An interface-file instance declaration
271 -- Should be in scope by now, because we should
272 -- have sucked in its interface-file definition
273 -- So it will be replete with its unfolding etc
275 ) `thenNF_Tc` \ dfun_id ->
276 returnTc [InstInfo { iDFunId = dfun_id, iBinds = binds, iPrags = uprags }]
278 msg = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
282 %************************************************************************
284 \subsection{Extracting generic instance declaration from class declarations}
286 %************************************************************************
288 @getGenericInstances@ extracts the generic instance declarations from a class
289 declaration. For exmaple
294 op{ x+y } (Inl v) = ...
295 op{ x+y } (Inr v) = ...
296 op{ x*y } (v :*: w) = ...
299 gives rise to the instance declarations
301 instance C (x+y) where
305 instance C (x*y) where
313 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo]
314 getGenericInstances class_decls
315 = mapTc get_generics class_decls `thenTc` \ gen_inst_infos ->
317 gen_inst_info = concat gen_inst_infos
319 if null gen_inst_info then
322 getDOptsTc `thenTc` \ dflags ->
323 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances"
324 (vcat (map pprInstInfo gen_inst_info)))
326 returnTc gen_inst_info
328 get_generics decl@(ClassDecl {tcdMeths = Nothing})
329 = returnTc [] -- Imported class decls
331 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = Just def_methods, tcdLoc = loc})
333 = returnTc [] -- The comon case: no generic default methods
335 | otherwise -- A source class decl with generic default methods
336 = recoverNF_Tc (returnNF_Tc []) $
338 tcLookupClass class_name `thenTc` \ clas ->
340 -- Make an InstInfo out of each group
341 mapTc (mkGenericInstance clas loc) groups `thenTc` \ inst_infos ->
343 -- Check that there is only one InstInfo for each type constructor
344 -- The main way this can fail is if you write
345 -- f {| a+b |} ... = ...
346 -- f {| x+y |} ... = ...
347 -- Then at this point we'll have an InstInfo for each
349 tc_inst_infos :: [(TyCon, InstInfo)]
350 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
352 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
353 group `lengthExceeds` 1]
354 get_uniq (tc,_) = getUnique tc
356 mapTc (addErrTc . dupGenericInsts) bad_groups `thenTc_`
358 -- Check that there is an InstInfo for each generic type constructor
360 missing = genericTyCons `minusList` [tc | (tc,_) <- tc_inst_infos]
362 checkTc (null missing) (missingGenericInstances missing) `thenTc_`
367 -- Group the declarations by type pattern
368 groups :: [(RenamedHsType, RenamedMonoBinds)]
369 groups = assocElts (getGenericBinds def_methods)
372 ---------------------------------
373 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
374 -- Takes a group of method bindings, finds the generic ones, and returns
375 -- them in finite map indexed by the type parameter in the definition.
377 getGenericBinds EmptyMonoBinds = emptyAssoc
378 getGenericBinds (AndMonoBinds m1 m2)
379 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
381 getGenericBinds (FunMonoBind id infixop matches loc)
382 = mapAssoc wrap (foldl add emptyAssoc matches)
383 -- Using foldl not foldr is vital, else
384 -- we reverse the order of the bindings!
386 add env match = case maybeGenericMatch match of
388 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
390 wrap ms = FunMonoBind id infixop ms loc
392 ---------------------------------
393 mkGenericInstance :: Class -> SrcLoc
394 -> (RenamedHsType, RenamedMonoBinds)
397 mkGenericInstance clas loc (hs_ty, binds)
398 -- Make a generic instance declaration
399 -- For example: instance (C a, C b) => C (a+b) where { binds }
401 = -- Extract the universally quantified type variables
403 sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
405 tcHsTyVars sig_tvs (kcHsSigType hs_ty) $ \ tyvars ->
407 -- Type-check the instance type, and check its form
408 tcHsSigType GenPatCtxt hs_ty `thenTc` \ inst_ty ->
409 checkTc (validGenericInstanceType inst_ty)
410 (badGenericInstanceType binds) `thenTc_`
412 -- Make the dictionary function.
413 newDFunName clas [inst_ty] loc `thenNF_Tc` \ dfun_name ->
415 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
417 dfun_id = mkDictFunId dfun_name clas tyvars inst_tys inst_theta
420 returnTc (InstInfo { iDFunId = dfun_id,
421 iBinds = binds, iPrags = [] })
425 %************************************************************************
427 \subsection{Type-checking instance declarations, pass 2}
429 %************************************************************************
432 tcInstDecls2 :: [InstInfo]
433 -> NF_TcM (LIE, TcMonoBinds)
435 tcInstDecls2 inst_decls
436 -- = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
437 = foldr combine (returnNF_Tc (emptyLIE, EmptyMonoBinds))
438 (map tcInstDecl2 inst_decls)
440 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
441 tc2 `thenNF_Tc` \ (lie2, binds2) ->
442 returnNF_Tc (lie1 `plusLIE` lie2,
443 binds1 `AndMonoBinds` binds2)
446 ======= New documentation starts here (Sept 92) ==============
448 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
449 the dictionary function for this instance declaration. For example
451 instance Foo a => Foo [a] where
455 might generate something like
457 dfun.Foo.List dFoo_a = let op1 x = ...
463 HOWEVER, if the instance decl has no context, then it returns a
464 bigger @HsBinds@ with declarations for each method. For example
466 instance Foo [a] where
472 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
473 const.Foo.op1.List a x = ...
474 const.Foo.op2.List a y = ...
476 This group may be mutually recursive, because (for example) there may
477 be no method supplied for op2 in which case we'll get
479 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
481 that is, the default method applied to the dictionary at this type.
483 What we actually produce in either case is:
485 AbsBinds [a] [dfun_theta_dicts]
486 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
487 { d = (sd1,sd2, ..., op1, op2, ...)
492 The "maybe" says that we only ask AbsBinds to make global constant methods
493 if the dfun_theta is empty.
496 For an instance declaration, say,
498 instance (C1 a, C2 b) => C (T a b) where
501 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
502 function whose type is
504 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
506 Notice that we pass it the superclass dictionaries at the instance type; this
507 is the ``Mark Jones optimisation''. The stuff before the "=>" here
508 is the @dfun_theta@ below.
510 First comes the easy case of a non-local instance decl.
514 tcInstDecl2 :: InstInfo -> NF_TcM (LIE, TcMonoBinds)
515 -- tcInstDecl2 is called *only* on InstInfos
517 tcInstDecl2 (InstInfo { iDFunId = dfun_id,
518 iBinds = monobinds, iPrags = uprags })
519 = -- Prime error recovery
520 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
521 tcAddSrcLoc (getSrcLoc dfun_id) $
522 tcAddErrCtxt (instDeclCtxt (toHsType (idType dfun_id))) $
524 -- Instantiate the instance decl with tc-style type variables
526 (inst_tyvars, dfun_theta, clas, inst_tys) = tcSplitDFunTy (idType dfun_id)
528 tcInstSigTyVars InstTv inst_tyvars `thenNF_Tc` \ inst_tyvars' ->
530 tenv = mkTopTyVarSubst inst_tyvars (mkTyVarTys inst_tyvars')
531 inst_tys' = map (substTy tenv) inst_tys
532 dfun_theta' = substTheta tenv dfun_theta
533 origin = InstanceDeclOrigin
535 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
537 sel_names = [idName sel_id | (sel_id, _) <- op_items]
539 -- Instantiate the super-class context with inst_tys
540 sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
542 -- Find any definitions in monobinds that aren't from the class
543 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
545 -- Check that all the method bindings come from this class
546 mapTc (addErrTc . badMethodErr clas) bad_bndrs `thenNF_Tc_`
548 -- Create dictionary Ids from the specified instance contexts.
549 newDicts origin sc_theta' `thenNF_Tc` \ sc_dicts ->
550 newDicts origin dfun_theta' `thenNF_Tc` \ dfun_arg_dicts ->
551 newDicts origin [mkClassPred clas inst_tys'] `thenNF_Tc` \ [this_dict] ->
553 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
554 -- The type variable from the dict fun actually scope
555 -- over the bindings. They were gotten from
556 -- the original instance declaration
558 -- Default-method Ids may be mentioned in synthesised RHSs,
559 -- but they'll already be in the environment.
561 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
563 monobinds uprags True)
565 ) `thenTc` \ (method_binds_s, insts_needed_s, meth_insts) ->
567 -- Deal with SPECIALISE instance pragmas by making them
568 -- look like SPECIALISE pragmas for the dfun
570 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
572 tcExtendGlobalValEnv [dfun_id] (
573 tcSpecSigs dfun_prags
574 ) `thenTc` \ (prag_binds, prag_lie) ->
576 -- Check the overloading constraints of the methods and superclasses
578 -- These insts are in scope; quite a few, eh?
579 avail_insts = [this_dict] ++
584 methods_lie = plusLIEs insts_needed_s
587 -- Simplify the constraints from methods
588 tcAddErrCtxt methodCtxt (
590 (ptext SLIT("instance declaration context"))
594 ) `thenTc` \ (const_lie1, lie_binds1) ->
596 -- Figure out bindings for the superclass context
597 tcAddErrCtxt superClassCtxt (
599 (ptext SLIT("instance declaration context"))
601 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
602 -- get bound by just selecting from this_dict!!
604 ) `thenTc` \ (const_lie2, lie_binds2) ->
606 checkSigTyVars inst_tyvars' emptyVarSet `thenNF_Tc` \ zonked_inst_tyvars ->
608 -- Create the result bindings
610 local_dfun_id = setIdLocalExported dfun_id
611 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
613 dict_constr = classDataCon clas
614 scs_and_meths = map instToId (sc_dicts ++ meth_insts)
615 this_dict_id = instToId this_dict
616 inlines | null dfun_arg_dicts = emptyNameSet
617 | otherwise = unitNameSet (idName dfun_id)
618 -- Always inline the dfun; this is an experimental decision
619 -- because it makes a big performance difference sometimes.
620 -- Often it means we can do the method selection, and then
621 -- inline the method as well. Marcin's idea; see comments below.
623 -- BUT: don't inline it if it's a constant dictionary;
624 -- we'll get all the benefit without inlining, and we get
625 -- a **lot** of code duplication if we inline it
629 = -- Blatant special case for CCallable, CReturnable
630 -- If the dictionary is empty then we should never
631 -- select anything from it, so we make its RHS just
632 -- emit an error message. This in turn means that we don't
633 -- mention the constructor, which doesn't exist for CCallable, CReturnable
634 -- Hardly beautiful, but only three extra lines.
635 HsApp (TyApp (HsVar eRROR_ID) [idType this_dict_id])
636 (HsLit (HsString msg))
638 | otherwise -- The common case
639 = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
640 -- We don't produce a binding for the dict_constr; instead we
641 -- rely on the simplifier to unfold this saturated application
642 -- We do this rather than generate an HsCon directly, because
643 -- it means that the special cases (e.g. dictionary with only one
644 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
645 -- than needing to be repeated here.
648 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
650 dict_bind = VarMonoBind this_dict_id dict_rhs
651 method_binds = andMonoBindList method_binds_s
656 (map instToId dfun_arg_dicts)
657 [(inst_tyvars', local_dfun_id, this_dict_id)]
659 (lie_binds1 `AndMonoBinds`
660 lie_binds2 `AndMonoBinds`
661 method_binds `AndMonoBinds`
664 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
665 main_bind `AndMonoBinds` prag_binds)
668 ------------------------------
669 Inlining dfuns unconditionally
670 ------------------------------
672 The code above unconditionally inlines dict funs. Here's why.
673 Consider this program:
675 test :: Int -> Int -> Bool
676 test x y = (x,y) == (y,x) || test y x
677 -- Recursive to avoid making it inline.
679 This needs the (Eq (Int,Int)) instance. If we inline that dfun
680 the code we end up with is good:
683 \r -> case ==# [ww ww1] of wild {
684 PrelBase.False -> Test.$wtest ww1 ww;
686 case ==# [ww1 ww] of wild1 {
687 PrelBase.False -> Test.$wtest ww1 ww;
688 PrelBase.True -> PrelBase.True [];
691 Test.test = \r [w w1]
694 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
697 If we don't inline the dfun, the code is not nearly as good:
699 (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
700 PrelBase.:DEq tpl1 tpl2 -> tpl2;
705 let { y = PrelBase.I#! [ww1]; } in
706 let { x = PrelBase.I#! [ww]; } in
707 let { sat_slx = PrelTup.(,)! [y x]; } in
708 let { sat_sly = PrelTup.(,)! [x y];
710 case == sat_sly sat_slx of wild {
711 PrelBase.False -> Test.$wtest ww1 ww;
712 PrelBase.True -> PrelBase.True [];
719 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
722 Why doesn't GHC inline $fEq? Because it looks big:
724 PrelTup.zdfEqZ1T{-rcX-}
725 = \ @ a{-reT-} :: * @ b{-reS-} :: *
726 zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
727 zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
729 zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
730 zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
732 zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
733 zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
735 zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
736 zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
737 ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
739 of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
741 of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
743 (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
744 (zeze{-rf0-} a2{-reZ-} b2{-reY-})
748 a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
749 a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
750 b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
751 PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
753 PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
755 and it's not as bad as it seems, because it's further dramatically
756 simplified: only zeze2 is extracted and its body is simplified.
759 %************************************************************************
761 \subsection{Error messages}
763 %************************************************************************
766 tcAddDeclCtxt decl thing_inside
767 = tcAddSrcLoc (tcdLoc decl) $
772 ClassDecl {} -> "class"
773 TySynonym {} -> "type synonym"
774 TyData {tcdND = NewType} -> "newtype"
775 TyData {tcdND = DataType} -> "data type"
777 ctxt = hsep [ptext SLIT("In the"), text thing,
778 ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
780 instDeclCtxt inst_ty = ptext SLIT("In the instance declaration for") <+> quotes doc
782 doc = case inst_ty of
783 HsForAllTy _ _ (HsPredTy pred) -> ppr pred
784 HsPredTy pred -> ppr pred
785 other -> ppr inst_ty -- Don't expect this
789 badGenericInstanceType binds
790 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
793 missingGenericInstances missing
794 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
796 dupGenericInsts tc_inst_infos
797 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
798 nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
799 ptext SLIT("All the type patterns for a generic type constructor must be identical")
802 ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
804 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
805 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")