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 ( tcInstSigType, checkValidTheta, checkValidInstHead, instTypeErr,
28 UserTypeCtxt(..), SourceTyCtxt(..) )
29 import TcType ( mkClassPred, mkTyVarTy, mkTyVarTys, tcSplitForAllTys,
30 tcSplitSigmaTy, getClassPredTys, tcSplitPredTy_maybe,
33 import Inst ( InstOrigin(..), newDicts, instToId,
34 LIE, mkLIE, emptyLIE, plusLIE, plusLIEs )
35 import TcDeriv ( tcDeriving )
36 import TcEnv ( TcEnv, tcExtendGlobalValEnv, isLocalThing,
37 tcExtendTyVarEnvForMeths, tcLookupId, tcLookupClass,
38 InstInfo(..), pprInstInfo, simpleInstInfoTyCon,
39 simpleInstInfoTy, newDFunName
41 import InstEnv ( InstEnv, extendInstEnv )
42 import PprType ( pprClassPred )
43 import TcMonoType ( tcHsTyVars, kcHsSigType, tcHsType, tcHsSigType )
44 import TcUnify ( checkSigTyVars )
45 import TcSimplify ( tcSimplifyCheck )
46 import HscTypes ( HomeSymbolTable, DFunId,
47 ModDetails(..), PackageInstEnv, PersistentRenamerState
49 import Subst ( substTy, substTheta )
50 import DataCon ( classDataCon )
51 import Class ( Class, classBigSig )
52 import Var ( idName, idType )
53 import VarSet ( emptyVarSet )
54 import Id ( setIdLocalExported )
55 import MkId ( mkDictFunId, unsafeCoerceId, eRROR_ID )
56 import FunDeps ( checkInstFDs )
57 import Generics ( validGenericInstanceType )
58 import Module ( Module, foldModuleEnv )
59 import Name ( getSrcLoc )
60 import NameSet ( unitNameSet, emptyNameSet, nameSetToList )
61 import TyCon ( TyCon )
62 import Subst ( mkTopTyVarSubst, substTheta )
63 import TysWiredIn ( genericTyCons )
65 import SrcLoc ( SrcLoc )
66 import Unique ( Uniquable(..) )
67 import Util ( lengthExceeds, isSingleton )
68 import BasicTypes ( NewOrData(..), Fixity )
69 import ErrUtils ( dumpIfSet_dyn )
70 import ListSetOps ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc,
71 assocElts, extendAssoc_C, equivClassesByUniq, minusList
73 import Maybe ( catMaybes )
74 import List ( partition )
78 Typechecking instance declarations is done in two passes. The first
79 pass, made by @tcInstDecls1@, collects information to be used in the
82 This pre-processed info includes the as-yet-unprocessed bindings
83 inside the instance declaration. These are type-checked in the second
84 pass, when the class-instance envs and GVE contain all the info from
85 all the instance and value decls. Indeed that's the reason we need
86 two passes over the instance decls.
89 Here is the overall algorithm.
90 Assume that we have an instance declaration
92 instance c => k (t tvs) where b
96 $LIE_c$ is the LIE for the context of class $c$
98 $betas_bar$ is the free variables in the class method type, excluding the
101 $LIE_cop$ is the LIE constraining a particular class method
103 $tau_cop$ is the tau type of a class method
105 $LIE_i$ is the LIE for the context of instance $i$
107 $X$ is the instance constructor tycon
109 $gammas_bar$ is the set of type variables of the instance
111 $LIE_iop$ is the LIE for a particular class method instance
113 $tau_iop$ is the tau type for this instance of a class method
115 $alpha$ is the class variable
117 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
119 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
122 ToDo: Update the list above with names actually in the code.
126 First, make the LIEs for the class and instance contexts, which means
127 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
128 and make LIElistI and LIEI.
130 Then process each method in turn.
132 order the instance methods according to the ordering of the class methods
134 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
136 Create final dictionary function from bindings generated already
138 df = lambda inst_tyvars
145 in <op1,op2,...,opn,sd1,...,sdm>
147 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
148 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
152 %************************************************************************
154 \subsection{Extracting instance decls}
156 %************************************************************************
158 Gather up the instance declarations from their various sources
163 -> PersistentRenamerState
164 -> HomeSymbolTable -- Contains instances
165 -> TcEnv -- Contains IdInfo for dfun ids
166 -> (Name -> Maybe Fixity) -- for deriving Show and Read
167 -> Module -- Module for deriving
169 -> TcM (PackageInstEnv, -- cached package inst env
170 InstEnv, -- the full inst env
171 [InstInfo], -- instance decls to process
172 [DFunId], -- instances from this module, for its iface
173 RenamedHsBinds) -- derived instances
175 tcInstDecls1 inst_env0 prs hst unf_env get_fixity this_mod decls
177 inst_decls = [inst_decl | InstD inst_decl <- decls]
178 tycl_decls = [decl | TyClD decl <- decls]
179 clas_decls = filter isClassDecl tycl_decls
180 (iface_inst_ds, local_inst_ds) = partition isIfaceInstDecl inst_decls
182 -- (1) Do the ordinary instance declarations
183 mapNF_Tc tcLocalInstDecl1 local_inst_ds `thenNF_Tc` \ local_inst_infos ->
184 mapNF_Tc tcImportedInstDecl1 iface_inst_ds `thenNF_Tc` \ iface_dfuns ->
186 -- (2) Instances from generic class declarations
187 getGenericInstances clas_decls `thenTc` \ generic_inst_info ->
189 -- Next, construct the instance environment so far, consisting of
190 -- a) cached non-home-package InstEnv (gotten from pcs) inst_env0
191 -- b) imported instance decls (not in the home package) inst_env1
192 -- c) other modules in this package (gotten from hst) inst_env2
193 -- d) imported instance decls (from this module) inst_env3
194 -- e) local instance decls inst_env4
195 -- f) generic instances inst_env5
196 -- The result of (b) replaces the cached InstEnv in the PCS
198 -- Note that iface_dfuns may contain not only insts that we
199 -- demand-loaded from interface files, but also instances from
200 -- the current module in the case where we are loading this
201 -- module's interface file in GHCi, so we partition the
202 -- iface_dfuns into non-local and local instances so that we
203 -- don't end up with home package instances in the PCS.
205 -- There can't be any instance declarations from the home
206 -- package other than from the current module (with the
207 -- compilation manager) because they are loaded explicitly by
208 -- the compilation manager.
210 local_inst_info = catMaybes local_inst_infos
211 (local_iface_dfuns, pkg_iface_dfuns)
212 = partition (isLocalThing this_mod) iface_dfuns
213 hst_dfuns = foldModuleEnv ((++) . md_insts) [] hst
216 -- pprTrace "tcInstDecls" (vcat [ppr imported_dfuns, ppr hst_dfuns]) $
218 addInstDFuns inst_env0 pkg_iface_dfuns `thenNF_Tc` \ inst_env1 ->
219 addInstDFuns inst_env1 hst_dfuns `thenNF_Tc` \ inst_env2 ->
220 addInstDFuns inst_env2 local_iface_dfuns `thenNF_Tc` \ inst_env3 ->
221 addInstInfos inst_env3 local_inst_info `thenNF_Tc` \ inst_env4 ->
222 addInstInfos inst_env4 generic_inst_info `thenNF_Tc` \ inst_env5 ->
224 -- (3) Compute instances from "deriving" clauses;
225 -- note that we only do derivings for things in this module;
226 -- we ignore deriving decls from interfaces!
227 -- This stuff computes a context for the derived instance decl, so it
228 -- needs to know about all the instances possible; hence inst_env5
229 tcDeriving prs this_mod inst_env5 get_fixity tycl_decls
230 `thenTc` \ (deriv_inst_info, deriv_binds) ->
231 addInstInfos inst_env5 deriv_inst_info `thenNF_Tc` \ final_inst_env ->
232 let inst_info = generic_inst_info ++ deriv_inst_info ++ local_inst_info in
237 local_iface_dfuns ++ map iDFunId inst_info,
240 addInstInfos :: InstEnv -> [InstInfo] -> NF_TcM InstEnv
241 addInstInfos inst_env infos = addInstDFuns inst_env (map iDFunId infos)
243 addInstDFuns :: InstEnv -> [DFunId] -> NF_TcM InstEnv
244 addInstDFuns inst_env dfuns
245 = getDOptsTc `thenNF_Tc` \ dflags ->
247 (inst_env', errs) = extendInstEnv dflags inst_env dfuns
249 addErrsTc errs `thenNF_Tc_`
250 traceTc (text "Adding instances:" <+> vcat (map pp dfuns)) `thenTc_`
253 pp dfun = ppr dfun <+> dcolon <+> ppr (idType dfun)
257 tcImportedInstDecl1 :: RenamedInstDecl -> NF_TcM DFunId
258 -- An interface-file instance declaration
259 -- Should be in scope by now, because we should
260 -- have sucked in its interface-file definition
261 -- So it will be replete with its unfolding etc
262 tcImportedInstDecl1 decl@(InstDecl poly_ty binds uprags (Just dfun_name) src_loc)
263 = tcLookupId dfun_name
266 tcLocalInstDecl1 :: RenamedInstDecl
267 -> NF_TcM (Maybe InstInfo) -- Nothing if there was an error
268 -- A source-file instance declaration
269 -- Type-check all the stuff before the "where"
271 -- We check for respectable instance type, and context
272 -- but only do this for non-imported instance decls.
273 -- Imported ones should have been checked already, and may indeed
274 -- contain something illegal in normal Haskell, notably
275 -- instance CCallable [Char]
276 tcLocalInstDecl1 decl@(InstDecl poly_ty binds uprags Nothing src_loc)
277 = -- Prime error recovery, set source location
278 recoverNF_Tc (returnNF_Tc Nothing) $
279 tcAddSrcLoc src_loc $
280 tcAddErrCtxt (instDeclCtxt poly_ty) $
282 -- Typecheck the instance type itself. We can't use
283 -- tcHsSigType, because it's not a valid user type.
284 kcHsSigType poly_ty `thenTc_`
285 tcHsType poly_ty `thenTc` \ poly_ty' ->
287 (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
289 checkValidTheta InstThetaCtxt theta `thenTc_`
290 checkValidInstHead tau `thenTc` \ (clas,inst_tys) ->
291 checkTc (checkInstFDs theta clas inst_tys)
292 (instTypeErr (pprClassPred clas inst_tys) msg) `thenTc_`
293 newDFunName clas inst_tys src_loc `thenNF_Tc` \ dfun_name ->
294 returnTc (Just (InstInfo { iDFunId = mkDictFunId dfun_name clas tyvars inst_tys theta,
295 iBinds = binds, iPrags = uprags }))
297 msg = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
301 %************************************************************************
303 \subsection{Extracting generic instance declaration from class declarations}
305 %************************************************************************
307 @getGenericInstances@ extracts the generic instance declarations from a class
308 declaration. For exmaple
313 op{ x+y } (Inl v) = ...
314 op{ x+y } (Inr v) = ...
315 op{ x*y } (v :*: w) = ...
318 gives rise to the instance declarations
320 instance C (x+y) where
324 instance C (x*y) where
332 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo]
333 getGenericInstances class_decls
334 = mapTc get_generics class_decls `thenTc` \ gen_inst_infos ->
336 gen_inst_info = concat gen_inst_infos
338 if null gen_inst_info then
341 getDOptsTc `thenNF_Tc` \ dflags ->
342 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances"
343 (vcat (map pprInstInfo gen_inst_info)))
345 returnTc gen_inst_info
347 get_generics decl@(ClassDecl {tcdMeths = Nothing})
348 = returnTc [] -- Imported class decls
350 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = Just def_methods, tcdLoc = loc})
352 = returnTc [] -- The comon case: no generic default methods
354 | otherwise -- A source class decl with generic default methods
355 = recoverNF_Tc (returnNF_Tc []) $
357 tcLookupClass class_name `thenTc` \ clas ->
359 -- Make an InstInfo out of each group
360 mapTc (mkGenericInstance clas loc) groups `thenTc` \ inst_infos ->
362 -- Check that there is only one InstInfo for each type constructor
363 -- The main way this can fail is if you write
364 -- f {| a+b |} ... = ...
365 -- f {| x+y |} ... = ...
366 -- Then at this point we'll have an InstInfo for each
368 tc_inst_infos :: [(TyCon, InstInfo)]
369 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
371 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
372 group `lengthExceeds` 1]
373 get_uniq (tc,_) = getUnique tc
375 mapTc (addErrTc . dupGenericInsts) bad_groups `thenTc_`
377 -- Check that there is an InstInfo for each generic type constructor
379 missing = genericTyCons `minusList` [tc | (tc,_) <- tc_inst_infos]
381 checkTc (null missing) (missingGenericInstances missing) `thenTc_`
386 -- Group the declarations by type pattern
387 groups :: [(RenamedHsType, RenamedMonoBinds)]
388 groups = assocElts (getGenericBinds def_methods)
391 ---------------------------------
392 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
393 -- Takes a group of method bindings, finds the generic ones, and returns
394 -- them in finite map indexed by the type parameter in the definition.
396 getGenericBinds EmptyMonoBinds = emptyAssoc
397 getGenericBinds (AndMonoBinds m1 m2)
398 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
400 getGenericBinds (FunMonoBind id infixop matches loc)
401 = mapAssoc wrap (foldl add emptyAssoc matches)
402 -- Using foldl not foldr is vital, else
403 -- we reverse the order of the bindings!
405 add env match = case maybeGenericMatch match of
407 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
409 wrap ms = FunMonoBind id infixop ms loc
411 ---------------------------------
412 mkGenericInstance :: Class -> SrcLoc
413 -> (RenamedHsType, RenamedMonoBinds)
416 mkGenericInstance clas loc (hs_ty, binds)
417 -- Make a generic instance declaration
418 -- For example: instance (C a, C b) => C (a+b) where { binds }
420 = -- Extract the universally quantified type variables
422 sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
424 tcHsTyVars sig_tvs (kcHsSigType hs_ty) $ \ tyvars ->
426 -- Type-check the instance type, and check its form
427 tcHsSigType GenPatCtxt hs_ty `thenTc` \ inst_ty ->
428 checkTc (validGenericInstanceType inst_ty)
429 (badGenericInstanceType binds) `thenTc_`
431 -- Make the dictionary function.
432 newDFunName clas [inst_ty] loc `thenNF_Tc` \ dfun_name ->
434 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
435 dfun_id = mkDictFunId dfun_name clas tyvars [inst_ty] inst_theta
438 returnTc (InstInfo { iDFunId = dfun_id, iBinds = binds, iPrags = [] })
442 %************************************************************************
444 \subsection{Type-checking instance declarations, pass 2}
446 %************************************************************************
449 tcInstDecls2 :: [InstInfo]
450 -> NF_TcM (LIE, TcMonoBinds)
452 tcInstDecls2 inst_decls
453 -- = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
454 = foldr combine (returnNF_Tc (emptyLIE, EmptyMonoBinds))
455 (map tcInstDecl2 inst_decls)
457 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
458 tc2 `thenNF_Tc` \ (lie2, binds2) ->
459 returnNF_Tc (lie1 `plusLIE` lie2,
460 binds1 `AndMonoBinds` binds2)
463 ======= New documentation starts here (Sept 92) ==============
465 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
466 the dictionary function for this instance declaration. For example
468 instance Foo a => Foo [a] where
472 might generate something like
474 dfun.Foo.List dFoo_a = let op1 x = ...
480 HOWEVER, if the instance decl has no context, then it returns a
481 bigger @HsBinds@ with declarations for each method. For example
483 instance Foo [a] where
489 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
490 const.Foo.op1.List a x = ...
491 const.Foo.op2.List a y = ...
493 This group may be mutually recursive, because (for example) there may
494 be no method supplied for op2 in which case we'll get
496 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
498 that is, the default method applied to the dictionary at this type.
500 What we actually produce in either case is:
502 AbsBinds [a] [dfun_theta_dicts]
503 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
504 { d = (sd1,sd2, ..., op1, op2, ...)
509 The "maybe" says that we only ask AbsBinds to make global constant methods
510 if the dfun_theta is empty.
513 For an instance declaration, say,
515 instance (C1 a, C2 b) => C (T a b) where
518 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
519 function whose type is
521 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
523 Notice that we pass it the superclass dictionaries at the instance type; this
524 is the ``Mark Jones optimisation''. The stuff before the "=>" here
525 is the @dfun_theta@ below.
527 First comes the easy case of a non-local instance decl.
531 tcInstDecl2 :: InstInfo -> TcM (LIE, TcMonoBinds)
533 tcInstDecl2 (NewTypeDerived { iDFunId = dfun_id })
534 = tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
535 newDicts InstanceDeclOrigin dfun_theta' `thenNF_Tc` \ rep_dicts ->
537 rep_dict_id = ASSERT( isSingleton rep_dicts )
538 instToId (head rep_dicts) -- Derived newtypes have just one dict arg
540 body = TyLam inst_tyvars' $
541 DictLam [rep_dict_id] $
542 (HsVar unsafeCoerceId `TyApp` [idType rep_dict_id, inst_head'])
545 -- You might wonder why we have the 'coerce'. It's because the
546 -- type equality mechanism isn't clever enough; see comments with Type.eqType.
547 -- So Lint complains if we don't have this.
549 returnTc (emptyLIE, VarMonoBind dfun_id body)
551 tcInstDecl2 (InstInfo { iDFunId = dfun_id, iBinds = monobinds, iPrags = uprags })
552 = -- Prime error recovery
553 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
554 tcAddSrcLoc (getSrcLoc dfun_id) $
555 tcAddErrCtxt (instDeclCtxt (toHsType (idType dfun_id))) $
557 -- Instantiate the instance decl with tc-style type variables
558 tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
560 Just pred = tcSplitPredTy_maybe inst_head'
561 (clas, inst_tys') = getClassPredTys pred
562 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
564 sel_names = [idName sel_id | (sel_id, _) <- op_items]
566 -- Instantiate the super-class context with inst_tys
567 sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
569 -- Find any definitions in monobinds that aren't from the class
570 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
571 (inst_tyvars, _) = tcSplitForAllTys (idType dfun_id)
572 origin = InstanceDeclOrigin
574 -- Check that all the method bindings come from this class
575 mapTc (addErrTc . badMethodErr clas) bad_bndrs `thenNF_Tc_`
577 -- Create dictionary Ids from the specified instance contexts.
578 newDicts origin sc_theta' `thenNF_Tc` \ sc_dicts ->
579 newDicts origin dfun_theta' `thenNF_Tc` \ dfun_arg_dicts ->
580 newDicts origin [mkClassPred clas inst_tys'] `thenNF_Tc` \ [this_dict] ->
582 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
583 -- The type variable from the dict fun actually scope
584 -- over the bindings. They were gotten from
585 -- the original instance declaration
587 -- Default-method Ids may be mentioned in synthesised RHSs,
588 -- but they'll already be in the environment.
590 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
592 monobinds uprags True)
594 ) `thenTc` \ (method_binds_s, insts_needed_s, meth_insts) ->
596 -- Deal with SPECIALISE instance pragmas by making them
597 -- look like SPECIALISE pragmas for the dfun
599 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
601 tcExtendGlobalValEnv [dfun_id] (
602 tcSpecSigs dfun_prags
603 ) `thenTc` \ (prag_binds, prag_lie) ->
605 -- Check the overloading constraints of the methods and superclasses
607 -- These insts are in scope; quite a few, eh?
608 avail_insts = [this_dict] ++
613 methods_lie = plusLIEs insts_needed_s
616 -- Simplify the constraints from methods
617 tcAddErrCtxt methodCtxt (
619 (ptext SLIT("instance declaration context"))
623 ) `thenTc` \ (const_lie1, lie_binds1) ->
625 -- Figure out bindings for the superclass context
626 tcAddErrCtxt superClassCtxt (
628 (ptext SLIT("instance declaration context"))
630 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
631 -- get bound by just selecting from this_dict!!
633 ) `thenTc` \ (const_lie2, lie_binds2) ->
635 checkSigTyVars inst_tyvars' emptyVarSet `thenNF_Tc` \ zonked_inst_tyvars ->
637 -- Create the result bindings
639 local_dfun_id = setIdLocalExported dfun_id
640 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
642 dict_constr = classDataCon clas
643 scs_and_meths = map instToId (sc_dicts ++ meth_insts)
644 this_dict_id = instToId this_dict
645 inlines | null dfun_arg_dicts = emptyNameSet
646 | otherwise = unitNameSet (idName dfun_id)
647 -- Always inline the dfun; this is an experimental decision
648 -- because it makes a big performance difference sometimes.
649 -- Often it means we can do the method selection, and then
650 -- inline the method as well. Marcin's idea; see comments below.
652 -- BUT: don't inline it if it's a constant dictionary;
653 -- we'll get all the benefit without inlining, and we get
654 -- a **lot** of code duplication if we inline it
658 = -- Blatant special case for CCallable, CReturnable
659 -- If the dictionary is empty then we should never
660 -- select anything from it, so we make its RHS just
661 -- emit an error message. This in turn means that we don't
662 -- mention the constructor, which doesn't exist for CCallable, CReturnable
663 -- Hardly beautiful, but only three extra lines.
664 HsApp (TyApp (HsVar eRROR_ID) [idType this_dict_id])
665 (HsLit (HsString msg))
667 | otherwise -- The common case
668 = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
669 -- We don't produce a binding for the dict_constr; instead we
670 -- rely on the simplifier to unfold this saturated application
671 -- We do this rather than generate an HsCon directly, because
672 -- it means that the special cases (e.g. dictionary with only one
673 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
674 -- than needing to be repeated here.
677 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
679 dict_bind = VarMonoBind this_dict_id dict_rhs
680 method_binds = andMonoBindList method_binds_s
685 (map instToId dfun_arg_dicts)
686 [(inst_tyvars', local_dfun_id, this_dict_id)]
688 (lie_binds1 `AndMonoBinds`
689 lie_binds2 `AndMonoBinds`
690 method_binds `AndMonoBinds`
693 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
694 main_bind `AndMonoBinds` prag_binds)
697 ------------------------------
698 Inlining dfuns unconditionally
699 ------------------------------
701 The code above unconditionally inlines dict funs. Here's why.
702 Consider this program:
704 test :: Int -> Int -> Bool
705 test x y = (x,y) == (y,x) || test y x
706 -- Recursive to avoid making it inline.
708 This needs the (Eq (Int,Int)) instance. If we inline that dfun
709 the code we end up with is good:
712 \r -> case ==# [ww ww1] of wild {
713 PrelBase.False -> Test.$wtest ww1 ww;
715 case ==# [ww1 ww] of wild1 {
716 PrelBase.False -> Test.$wtest ww1 ww;
717 PrelBase.True -> PrelBase.True [];
720 Test.test = \r [w w1]
723 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
726 If we don't inline the dfun, the code is not nearly as good:
728 (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
729 PrelBase.:DEq tpl1 tpl2 -> tpl2;
734 let { y = PrelBase.I#! [ww1]; } in
735 let { x = PrelBase.I#! [ww]; } in
736 let { sat_slx = PrelTup.(,)! [y x]; } in
737 let { sat_sly = PrelTup.(,)! [x y];
739 case == sat_sly sat_slx of wild {
740 PrelBase.False -> Test.$wtest ww1 ww;
741 PrelBase.True -> PrelBase.True [];
748 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
751 Why doesn't GHC inline $fEq? Because it looks big:
753 PrelTup.zdfEqZ1T{-rcX-}
754 = \ @ a{-reT-} :: * @ b{-reS-} :: *
755 zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
756 zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
758 zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
759 zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
761 zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
762 zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
764 zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
765 zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
766 ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
768 of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
770 of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
772 (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
773 (zeze{-rf0-} a2{-reZ-} b2{-reY-})
777 a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
778 a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
779 b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
780 PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
782 PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
784 and it's not as bad as it seems, because it's further dramatically
785 simplified: only zeze2 is extracted and its body is simplified.
788 %************************************************************************
790 \subsection{Error messages}
792 %************************************************************************
795 tcAddDeclCtxt decl thing_inside
796 = tcAddSrcLoc (tcdLoc decl) $
801 ClassDecl {} -> "class"
802 TySynonym {} -> "type synonym"
803 TyData {tcdND = NewType} -> "newtype"
804 TyData {tcdND = DataType} -> "data type"
806 ctxt = hsep [ptext SLIT("In the"), text thing,
807 ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
809 instDeclCtxt inst_ty = ptext SLIT("In the instance declaration for") <+> quotes doc
811 doc = case inst_ty of
812 HsForAllTy _ _ (HsPredTy pred) -> ppr pred
813 HsPredTy pred -> ppr pred
814 other -> ppr inst_ty -- Don't expect this
818 badGenericInstanceType binds
819 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
822 missingGenericInstances missing
823 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
825 dupGenericInsts tc_inst_infos
826 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
827 nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
828 ptext SLIT("All the type patterns for a generic type constructor must be identical")
831 ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
833 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
834 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")