2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcInstDecls]{Typechecking instance declarations}
7 module TcInstDcls ( tcInstDecls1, tcIfaceInstDecls1, addInstDFuns,
8 tcInstDecls2, initInstEnv, tcAddDeclCtxt ) where
10 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlag(..) )
15 import HsSyn ( HsDecl(..), InstDecl(..), TyClDecl(..), HsType(..),
16 MonoBinds(..), HsExpr(..), HsLit(..), Sig(..), HsTyVarBndr(..),
17 andMonoBindList, collectMonoBinders,
20 import RnHsSyn ( RenamedHsBinds, RenamedInstDecl, RenamedHsDecl,
21 RenamedMonoBinds, RenamedTyClDecl, RenamedHsType,
22 extractHsTyVars, maybeGenericMatch
24 import TcHsSyn ( TcMonoBinds, mkHsConApp )
25 import TcBinds ( tcSpecSigs )
26 import TcClassDcl ( tcMethodBind, badMethodErr )
28 import TcMType ( tcInstSigType, checkValidTheta, checkValidInstHead, instTypeErr,
29 UserTypeCtxt(..), SourceTyCtxt(..) )
30 import TcType ( mkClassPred, mkTyVarTy, mkTyVarTys, tcSplitForAllTys,
31 tcSplitSigmaTy, getClassPredTys, tcSplitPredTy_maybe,
34 import Inst ( InstOrigin(..), newDicts, instToId,
35 LIE, mkLIE, emptyLIE, plusLIE, plusLIEs )
36 import TcDeriv ( tcDeriving )
37 import TcEnv ( TcEnv, tcExtendGlobalValEnv, isLocalThing,
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 PersistentCompilerState(..), PersistentRenamerState,
49 ModDetails(..), PackageInstEnv
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, unsafeCoerceId, eRROR_ID )
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 TyCon ( TyCon )
64 import Subst ( mkTopTyVarSubst, substTheta )
65 import TysWiredIn ( genericTyCons )
67 import SrcLoc ( SrcLoc )
68 import Unique ( Uniquable(..) )
69 import Util ( lengthExceeds, isSingleton )
70 import BasicTypes ( NewOrData(..), Fixity )
71 import ErrUtils ( dumpIfSet_dyn )
72 import ListSetOps ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc,
73 assocElts, extendAssoc_C, equivClassesByUniq, minusList
75 import Maybe ( catMaybes )
76 import List ( partition )
80 Typechecking instance declarations is done in two passes. The first
81 pass, made by @tcInstDecls1@, collects information to be used in the
84 This pre-processed info includes the as-yet-unprocessed bindings
85 inside the instance declaration. These are type-checked in the second
86 pass, when the class-instance envs and GVE contain all the info from
87 all the instance and value decls. Indeed that's the reason we need
88 two passes over the instance decls.
91 Here is the overall algorithm.
92 Assume that we have an instance declaration
94 instance c => k (t tvs) where b
98 $LIE_c$ is the LIE for the context of class $c$
100 $betas_bar$ is the free variables in the class method type, excluding the
103 $LIE_cop$ is the LIE constraining a particular class method
105 $tau_cop$ is the tau type of a class method
107 $LIE_i$ is the LIE for the context of instance $i$
109 $X$ is the instance constructor tycon
111 $gammas_bar$ is the set of type variables of the instance
113 $LIE_iop$ is the LIE for a particular class method instance
115 $tau_iop$ is the tau type for this instance of a class method
117 $alpha$ is the class variable
119 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
121 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
124 ToDo: Update the list above with names actually in the code.
128 First, make the LIEs for the class and instance contexts, which means
129 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
130 and make LIElistI and LIEI.
132 Then process each method in turn.
134 order the instance methods according to the ordering of the class methods
136 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
138 Create final dictionary function from bindings generated already
140 df = lambda inst_tyvars
147 in <op1,op2,...,opn,sd1,...,sdm>
149 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
150 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
154 %************************************************************************
156 \subsection{Extracting instance decls}
158 %************************************************************************
160 Gather up the instance declarations from their various sources
163 tcInstDecls1 -- Deal with source-code instance decls
164 :: PersistentRenamerState
165 -> InstEnv -- Imported instance envt
166 -> (Name -> Maybe Fixity) -- for deriving Show and Read
167 -> Module -- Module for deriving
168 -> [RenamedTyClDecl] -- For deriving stuff
169 -> [RenamedInstDecl] -- Source code instance decls
170 -> TcM (InstEnv, -- the full inst env
171 [InstInfo], -- instance decls to process; contains all dfuns
173 RenamedHsBinds) -- derived instances
175 tcInstDecls1 prs inst_env get_fixity this_mod
176 tycl_decls inst_decls
177 -- The incoming inst_env includes all the imported instances already
179 -- Stop if addInstInfos etc discovers any errors
180 -- (they recover, so that we get more than one error each round)
181 -- (1) Do the ordinary instance declarations
182 mapNF_Tc tcLocalInstDecl1 inst_decls `thenNF_Tc` \ local_inst_infos ->
185 local_inst_info = catMaybes local_inst_infos
186 clas_decls = filter isClassDecl tycl_decls
188 -- (2) Instances from generic class declarations
189 getGenericInstances clas_decls `thenTc` \ generic_inst_info ->
191 -- Next, construct the instance environment so far, consisting of
192 -- a) imported instance decls (from this module) inst_env1
193 -- b) local instance decls inst_env2
194 -- c) generic instances final_inst_env
195 addInstInfos inst_env local_inst_info `thenNF_Tc` \ inst_env1 ->
196 addInstInfos inst_env1 generic_inst_info `thenNF_Tc` \ inst_env2 ->
198 -- (3) Compute instances from "deriving" clauses;
199 -- note that we only do derivings for things in this module;
200 -- we ignore deriving decls from interfaces!
201 -- This stuff computes a context for the derived instance decl, so it
202 -- needs to know about all the instances possible; hence inst_env4
203 tcDeriving prs this_mod inst_env2
204 get_fixity tycl_decls `thenTc` \ (deriv_inst_info, deriv_binds) ->
205 addInstInfos inst_env2 deriv_inst_info `thenNF_Tc` \ final_inst_env ->
207 returnTc (final_inst_env,
208 generic_inst_info ++ deriv_inst_info ++ local_inst_info,
211 initInstEnv :: PersistentCompilerState -> HomeSymbolTable -> NF_TcM InstEnv
212 -- Initialise the instance environment from the
213 -- persistent compiler state and the home symbol table
216 pkg_inst_env = pcs_insts pcs
217 hst_dfuns = foldModuleEnv ((++) . md_insts) [] hst
219 addInstDFuns pkg_inst_env hst_dfuns
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 `thenNF_Tc` \ 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 tcIfaceInstDecls1 :: [RenamedInstDecl] -> NF_TcM [DFunId]
239 tcIfaceInstDecls1 decls = mapNF_Tc tcIfaceInstDecl1 decls
241 tcIfaceInstDecl1 :: RenamedInstDecl -> NF_TcM DFunId
242 -- An interface-file instance declaration
243 -- Should be in scope by now, because we should
244 -- have sucked in its interface-file definition
245 -- So it will be replete with its unfolding etc
246 tcIfaceInstDecl1 decl@(InstDecl poly_ty binds uprags (Just dfun_name) src_loc)
247 = tcLookupId dfun_name
250 tcLocalInstDecl1 :: RenamedInstDecl
251 -> NF_TcM (Maybe InstInfo) -- Nothing if there was an error
252 -- A source-file instance declaration
253 -- Type-check all the stuff before the "where"
255 -- We check for respectable instance type, and context
256 -- but only do this for non-imported instance decls.
257 -- Imported ones should have been checked already, and may indeed
258 -- contain something illegal in normal Haskell, notably
259 -- instance CCallable [Char]
260 tcLocalInstDecl1 decl@(InstDecl poly_ty binds uprags Nothing src_loc)
261 = -- Prime error recovery, set source location
262 recoverNF_Tc (returnNF_Tc Nothing) $
263 tcAddSrcLoc src_loc $
264 tcAddErrCtxt (instDeclCtxt poly_ty) $
266 -- Typecheck the instance type itself. We can't use
267 -- tcHsSigType, because it's not a valid user type.
268 kcHsSigType poly_ty `thenTc_`
269 tcHsType poly_ty `thenTc` \ poly_ty' ->
271 (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
273 checkValidTheta InstThetaCtxt theta `thenTc_`
274 checkValidInstHead tau `thenTc` \ (clas,inst_tys) ->
275 checkTc (checkInstFDs theta clas inst_tys)
276 (instTypeErr (pprClassPred clas inst_tys) msg) `thenTc_`
277 newDFunName clas inst_tys src_loc `thenNF_Tc` \ dfun_name ->
278 returnTc (Just (InstInfo { iDFunId = mkDictFunId dfun_name clas tyvars inst_tys theta,
279 iBinds = binds, iPrags = uprags }))
281 msg = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
285 %************************************************************************
287 \subsection{Extracting generic instance declaration from class declarations}
289 %************************************************************************
291 @getGenericInstances@ extracts the generic instance declarations from a class
292 declaration. For exmaple
297 op{ x+y } (Inl v) = ...
298 op{ x+y } (Inr v) = ...
299 op{ x*y } (v :*: w) = ...
302 gives rise to the instance declarations
304 instance C (x+y) where
308 instance C (x*y) where
316 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo]
317 getGenericInstances class_decls
318 = mapTc get_generics class_decls `thenTc` \ gen_inst_infos ->
320 gen_inst_info = concat gen_inst_infos
322 if null gen_inst_info then
325 getDOptsTc `thenNF_Tc` \ dflags ->
326 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances"
327 (vcat (map pprInstInfo gen_inst_info)))
329 returnTc gen_inst_info
331 get_generics decl@(ClassDecl {tcdMeths = Nothing})
332 = returnTc [] -- Imported class decls
334 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = Just def_methods, tcdLoc = loc})
336 = returnTc [] -- The comon case: no generic default methods
338 | otherwise -- A source class decl with generic default methods
339 = recoverNF_Tc (returnNF_Tc []) $
341 tcLookupClass class_name `thenTc` \ clas ->
343 -- Make an InstInfo out of each group
344 mapTc (mkGenericInstance clas loc) groups `thenTc` \ inst_infos ->
346 -- Check that there is only one InstInfo for each type constructor
347 -- The main way this can fail is if you write
348 -- f {| a+b |} ... = ...
349 -- f {| x+y |} ... = ...
350 -- Then at this point we'll have an InstInfo for each
352 tc_inst_infos :: [(TyCon, InstInfo)]
353 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
355 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
356 group `lengthExceeds` 1]
357 get_uniq (tc,_) = getUnique tc
359 mapTc (addErrTc . dupGenericInsts) bad_groups `thenTc_`
361 -- Check that there is an InstInfo for each generic type constructor
363 missing = genericTyCons `minusList` [tc | (tc,_) <- tc_inst_infos]
365 checkTc (null missing) (missingGenericInstances missing) `thenTc_`
370 -- Group the declarations by type pattern
371 groups :: [(RenamedHsType, RenamedMonoBinds)]
372 groups = assocElts (getGenericBinds def_methods)
375 ---------------------------------
376 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
377 -- Takes a group of method bindings, finds the generic ones, and returns
378 -- them in finite map indexed by the type parameter in the definition.
380 getGenericBinds EmptyMonoBinds = emptyAssoc
381 getGenericBinds (AndMonoBinds m1 m2)
382 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
384 getGenericBinds (FunMonoBind id infixop matches loc)
385 = mapAssoc wrap (foldl add emptyAssoc matches)
386 -- Using foldl not foldr is vital, else
387 -- we reverse the order of the bindings!
389 add env match = case maybeGenericMatch match of
391 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
393 wrap ms = FunMonoBind id infixop ms loc
395 ---------------------------------
396 mkGenericInstance :: Class -> SrcLoc
397 -> (RenamedHsType, RenamedMonoBinds)
400 mkGenericInstance clas loc (hs_ty, binds)
401 -- Make a generic instance declaration
402 -- For example: instance (C a, C b) => C (a+b) where { binds }
404 = -- Extract the universally quantified type variables
406 sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
408 tcHsTyVars sig_tvs (kcHsSigType hs_ty) $ \ tyvars ->
410 -- Type-check the instance type, and check its form
411 tcHsSigType GenPatCtxt hs_ty `thenTc` \ inst_ty ->
412 checkTc (validGenericInstanceType inst_ty)
413 (badGenericInstanceType binds) `thenTc_`
415 -- Make the dictionary function.
416 newDFunName clas [inst_ty] loc `thenNF_Tc` \ dfun_name ->
418 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
419 dfun_id = mkDictFunId dfun_name clas tyvars [inst_ty] inst_theta
422 returnTc (InstInfo { iDFunId = dfun_id, iBinds = binds, iPrags = [] })
426 %************************************************************************
428 \subsection{Type-checking instance declarations, pass 2}
430 %************************************************************************
433 tcInstDecls2 :: [InstInfo]
434 -> NF_TcM (LIE, TcMonoBinds)
436 tcInstDecls2 inst_decls
437 -- = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
438 = foldr combine (returnNF_Tc (emptyLIE, EmptyMonoBinds))
439 (map tcInstDecl2 inst_decls)
441 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
442 tc2 `thenNF_Tc` \ (lie2, binds2) ->
443 returnNF_Tc (lie1 `plusLIE` lie2,
444 binds1 `AndMonoBinds` binds2)
447 ======= New documentation starts here (Sept 92) ==============
449 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
450 the dictionary function for this instance declaration. For example
452 instance Foo a => Foo [a] where
456 might generate something like
458 dfun.Foo.List dFoo_a = let op1 x = ...
464 HOWEVER, if the instance decl has no context, then it returns a
465 bigger @HsBinds@ with declarations for each method. For example
467 instance Foo [a] where
473 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
474 const.Foo.op1.List a x = ...
475 const.Foo.op2.List a y = ...
477 This group may be mutually recursive, because (for example) there may
478 be no method supplied for op2 in which case we'll get
480 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
482 that is, the default method applied to the dictionary at this type.
484 What we actually produce in either case is:
486 AbsBinds [a] [dfun_theta_dicts]
487 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
488 { d = (sd1,sd2, ..., op1, op2, ...)
493 The "maybe" says that we only ask AbsBinds to make global constant methods
494 if the dfun_theta is empty.
497 For an instance declaration, say,
499 instance (C1 a, C2 b) => C (T a b) where
502 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
503 function whose type is
505 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
507 Notice that we pass it the superclass dictionaries at the instance type; this
508 is the ``Mark Jones optimisation''. The stuff before the "=>" here
509 is the @dfun_theta@ below.
511 First comes the easy case of a non-local instance decl.
515 tcInstDecl2 :: InstInfo -> TcM (LIE, TcMonoBinds)
517 tcInstDecl2 (NewTypeDerived { iDFunId = dfun_id })
518 = tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
519 newDicts InstanceDeclOrigin dfun_theta' `thenNF_Tc` \ rep_dicts ->
521 rep_dict_id = ASSERT( isSingleton rep_dicts )
522 instToId (head rep_dicts) -- Derived newtypes have just one dict arg
524 body = TyLam inst_tyvars' $
525 DictLam [rep_dict_id] $
526 (HsVar unsafeCoerceId `TyApp` [idType rep_dict_id, inst_head'])
529 -- You might wonder why we have the 'coerce'. It's because the
530 -- type equality mechanism isn't clever enough; see comments with Type.eqType.
531 -- So Lint complains if we don't have this.
533 returnTc (emptyLIE, VarMonoBind dfun_id body)
535 tcInstDecl2 (InstInfo { iDFunId = dfun_id, iBinds = monobinds, iPrags = uprags })
536 = -- Prime error recovery
537 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
538 tcAddSrcLoc (getSrcLoc dfun_id) $
539 tcAddErrCtxt (instDeclCtxt (toHsType (idType dfun_id))) $
541 -- Instantiate the instance decl with tc-style type variables
542 tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
544 Just pred = tcSplitPredTy_maybe inst_head'
545 (clas, inst_tys') = getClassPredTys pred
546 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
548 sel_names = [idName sel_id | (sel_id, _) <- op_items]
550 -- Instantiate the super-class context with inst_tys
551 sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
553 -- Find any definitions in monobinds that aren't from the class
554 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
555 (inst_tyvars, _) = tcSplitForAllTys (idType dfun_id)
556 origin = InstanceDeclOrigin
558 -- Check that all the method bindings come from this class
559 mapTc (addErrTc . badMethodErr clas) bad_bndrs `thenNF_Tc_`
561 -- Create dictionary Ids from the specified instance contexts.
562 newDicts origin sc_theta' `thenNF_Tc` \ sc_dicts ->
563 newDicts origin dfun_theta' `thenNF_Tc` \ dfun_arg_dicts ->
564 newDicts origin [mkClassPred clas inst_tys'] `thenNF_Tc` \ [this_dict] ->
566 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
567 -- The type variable from the dict fun actually scope
568 -- over the bindings. They were gotten from
569 -- the original instance declaration
571 -- Default-method Ids may be mentioned in synthesised RHSs,
572 -- but they'll already be in the environment.
574 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
576 monobinds uprags True)
578 ) `thenTc` \ (method_binds_s, insts_needed_s, meth_insts) ->
580 -- Deal with SPECIALISE instance pragmas by making them
581 -- look like SPECIALISE pragmas for the dfun
583 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
585 tcExtendGlobalValEnv [dfun_id] (
586 tcSpecSigs dfun_prags
587 ) `thenTc` \ (prag_binds, prag_lie) ->
589 -- Check the overloading constraints of the methods and superclasses
591 -- These insts are in scope; quite a few, eh?
592 avail_insts = [this_dict] ++
597 methods_lie = plusLIEs insts_needed_s
600 -- Simplify the constraints from methods
601 tcAddErrCtxt methodCtxt (
603 (ptext SLIT("instance declaration context"))
607 ) `thenTc` \ (const_lie1, lie_binds1) ->
609 -- Figure out bindings for the superclass context
610 tcAddErrCtxt superClassCtxt (
612 (ptext SLIT("instance declaration context"))
614 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
615 -- get bound by just selecting from this_dict!!
617 ) `thenTc` \ (const_lie2, lie_binds2) ->
619 checkSigTyVars inst_tyvars' emptyVarSet `thenNF_Tc` \ zonked_inst_tyvars ->
621 -- Create the result bindings
623 local_dfun_id = setIdLocalExported dfun_id
624 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
626 dict_constr = classDataCon clas
627 scs_and_meths = map instToId (sc_dicts ++ meth_insts)
628 this_dict_id = instToId this_dict
629 inlines | null dfun_arg_dicts = emptyNameSet
630 | otherwise = unitNameSet (idName dfun_id)
631 -- Always inline the dfun; this is an experimental decision
632 -- because it makes a big performance difference sometimes.
633 -- Often it means we can do the method selection, and then
634 -- inline the method as well. Marcin's idea; see comments below.
636 -- BUT: don't inline it if it's a constant dictionary;
637 -- we'll get all the benefit without inlining, and we get
638 -- a **lot** of code duplication if we inline it
642 = -- Blatant special case for CCallable, CReturnable
643 -- If the dictionary is empty then we should never
644 -- select anything from it, so we make its RHS just
645 -- emit an error message. This in turn means that we don't
646 -- mention the constructor, which doesn't exist for CCallable, CReturnable
647 -- Hardly beautiful, but only three extra lines.
648 HsApp (TyApp (HsVar eRROR_ID) [idType this_dict_id])
649 (HsLit (HsString msg))
651 | otherwise -- The common case
652 = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
653 -- We don't produce a binding for the dict_constr; instead we
654 -- rely on the simplifier to unfold this saturated application
655 -- We do this rather than generate an HsCon directly, because
656 -- it means that the special cases (e.g. dictionary with only one
657 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
658 -- than needing to be repeated here.
661 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
663 dict_bind = VarMonoBind this_dict_id dict_rhs
664 method_binds = andMonoBindList method_binds_s
669 (map instToId dfun_arg_dicts)
670 [(inst_tyvars', local_dfun_id, this_dict_id)]
672 (lie_binds1 `AndMonoBinds`
673 lie_binds2 `AndMonoBinds`
674 method_binds `AndMonoBinds`
677 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
678 main_bind `AndMonoBinds` prag_binds)
681 ------------------------------
682 Inlining dfuns unconditionally
683 ------------------------------
685 The code above unconditionally inlines dict funs. Here's why.
686 Consider this program:
688 test :: Int -> Int -> Bool
689 test x y = (x,y) == (y,x) || test y x
690 -- Recursive to avoid making it inline.
692 This needs the (Eq (Int,Int)) instance. If we inline that dfun
693 the code we end up with is good:
696 \r -> case ==# [ww ww1] of wild {
697 PrelBase.False -> Test.$wtest ww1 ww;
699 case ==# [ww1 ww] of wild1 {
700 PrelBase.False -> Test.$wtest ww1 ww;
701 PrelBase.True -> PrelBase.True [];
704 Test.test = \r [w w1]
707 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
710 If we don't inline the dfun, the code is not nearly as good:
712 (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
713 PrelBase.:DEq tpl1 tpl2 -> tpl2;
718 let { y = PrelBase.I#! [ww1]; } in
719 let { x = PrelBase.I#! [ww]; } in
720 let { sat_slx = PrelTup.(,)! [y x]; } in
721 let { sat_sly = PrelTup.(,)! [x y];
723 case == sat_sly sat_slx of wild {
724 PrelBase.False -> Test.$wtest ww1 ww;
725 PrelBase.True -> PrelBase.True [];
732 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
735 Why doesn't GHC inline $fEq? Because it looks big:
737 PrelTup.zdfEqZ1T{-rcX-}
738 = \ @ a{-reT-} :: * @ b{-reS-} :: *
739 zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
740 zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
742 zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
743 zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
745 zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
746 zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
748 zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
749 zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
750 ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
752 of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
754 of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
756 (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
757 (zeze{-rf0-} a2{-reZ-} b2{-reY-})
761 a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
762 a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
763 b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
764 PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
766 PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
768 and it's not as bad as it seems, because it's further dramatically
769 simplified: only zeze2 is extracted and its body is simplified.
772 %************************************************************************
774 \subsection{Error messages}
776 %************************************************************************
779 tcAddDeclCtxt decl thing_inside
780 = tcAddSrcLoc (tcdLoc decl) $
785 ClassDecl {} -> "class"
786 TySynonym {} -> "type synonym"
787 TyData {tcdND = NewType} -> "newtype"
788 TyData {tcdND = DataType} -> "data type"
790 ctxt = hsep [ptext SLIT("In the"), text thing,
791 ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
793 instDeclCtxt inst_ty = ptext SLIT("In the instance declaration for") <+> quotes doc
795 doc = case inst_ty of
796 HsForAllTy _ _ (HsPredTy pred) -> ppr pred
797 HsPredTy pred -> ppr pred
798 other -> ppr inst_ty -- Don't expect this
802 badGenericInstanceType binds
803 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
806 missingGenericInstances missing
807 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
809 dupGenericInsts tc_inst_infos
810 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
811 nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
812 ptext SLIT("All the type patterns for a generic type constructor must be identical")
815 ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
817 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
818 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")