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
161 tcInstDecls1 :: PackageInstEnv
162 -> PersistentRenamerState
163 -> HomeSymbolTable -- Contains instances
164 -> TcEnv -- Contains IdInfo for dfun ids
165 -> (Name -> Maybe Fixity) -- for deriving Show and Read
166 -> Module -- Module for deriving
168 -> TcM (PackageInstEnv, InstEnv, [InstInfo], RenamedHsBinds)
170 tcInstDecls1 inst_env0 prs hst unf_env get_fixity this_mod decls
172 inst_decls = [inst_decl | InstD inst_decl <- decls]
173 tycl_decls = [decl | TyClD decl <- decls]
174 clas_decls = filter isClassDecl tycl_decls
175 (iface_inst_ds, local_inst_ds) = partition isIfaceInstDecl inst_decls
177 -- (1) Do the ordinary instance declarations
178 mapNF_Tc tcLocalInstDecl1 local_inst_ds `thenNF_Tc` \ local_inst_infos ->
179 mapNF_Tc tcImportedInstDecl1 iface_inst_ds `thenNF_Tc` \ iface_dfuns ->
181 -- (2) Instances from generic class declarations
182 getGenericInstances clas_decls `thenTc` \ generic_inst_info ->
184 -- Next, construct the instance environment so far, consisting of
185 -- a) cached non-home-package InstEnv (gotten from pcs) inst_env0
186 -- b) imported instance decls (not in the home package) inst_env1
187 -- c) imported instance decls (from this module) inst_env2
188 -- c) other modules in this package (gotten from hst) inst_env3
189 -- d) local instance decls inst_env4
190 -- e) generic instances inst_env5
191 -- The result of (b) replaces the cached InstEnv in the PCS
193 -- Note that iface_dfuns may contain not only insts that we demand-loaded
194 -- from package interface files, but also instances from the current module
195 -- in the case where we are loading this module's interface file in GHCi,
196 -- so we partition the iface_dfuns into package instances and local instances
197 -- below so that we don't end up with home package instances in the PCS.
199 -- There can't be any instance declarations from the home
200 -- package other than from the current module (with the
201 -- compilation manager) because they are loaded explicitly by
202 -- the compilation manager. The partition is really only
203 -- necessary when we're under control of the compilation
206 local_inst_info = catMaybes local_inst_infos
207 (local_iface_dfuns, pkg_iface_dfuns) = partition (isLocalThing this_mod) iface_dfuns
208 hst_dfuns = foldModuleEnv ((++) . md_insts) [] hst
211 -- pprTrace "tcInstDecls" (vcat [ppr imported_dfuns, ppr hst_dfuns]) $
213 addInstDFuns inst_env0 pkg_iface_dfuns `thenNF_Tc` \ inst_env1 ->
214 addInstDFuns inst_env1 hst_dfuns `thenNF_Tc` \ inst_env2 ->
215 addInstDFuns inst_env2 local_iface_dfuns `thenNF_Tc` \ inst_env3 ->
216 addInstInfos inst_env3 local_inst_info `thenNF_Tc` \ inst_env4 ->
217 addInstInfos inst_env4 generic_inst_info `thenNF_Tc` \ inst_env5 ->
219 -- (3) Compute instances from "deriving" clauses;
220 -- note that we only do derivings for things in this module;
221 -- we ignore deriving decls from interfaces!
222 -- This stuff computes a context for the derived instance decl, so it
223 -- needs to know about all the instances possible; hence inst_env4
224 tcDeriving prs this_mod inst_env4 get_fixity tycl_decls
225 `thenTc` \ (deriv_inst_info, deriv_binds) ->
226 addInstInfos inst_env4 deriv_inst_info `thenNF_Tc` \ final_inst_env ->
230 generic_inst_info ++ deriv_inst_info ++ local_inst_info,
233 addInstInfos :: InstEnv -> [InstInfo] -> NF_TcM InstEnv
234 addInstInfos inst_env infos = addInstDFuns inst_env (map iDFunId infos)
236 addInstDFuns :: InstEnv -> [DFunId] -> NF_TcM InstEnv
237 addInstDFuns inst_env dfuns
238 = getDOptsTc `thenNF_Tc` \ dflags ->
240 (inst_env', errs) = extendInstEnv dflags inst_env dfuns
242 addErrsTc errs `thenNF_Tc_`
243 traceTc (text "Adding instances:" <+> vcat (map pp dfuns)) `thenTc_`
246 pp dfun = ppr dfun <+> dcolon <+> ppr (idType dfun)
250 tcImportedInstDecl1 :: RenamedInstDecl -> NF_TcM DFunId
251 -- An interface-file instance declaration
252 -- Should be in scope by now, because we should
253 -- have sucked in its interface-file definition
254 -- So it will be replete with its unfolding etc
255 tcImportedInstDecl1 decl@(InstDecl poly_ty binds uprags (Just dfun_name) src_loc)
256 = tcLookupId dfun_name
259 tcLocalInstDecl1 :: RenamedInstDecl
260 -> NF_TcM (Maybe InstInfo) -- Nothing if there was an error
261 -- A source-file instance declaration
262 -- Type-check all the stuff before the "where"
264 -- We check for respectable instance type, and context
265 -- but only do this for non-imported instance decls.
266 -- Imported ones should have been checked already, and may indeed
267 -- contain something illegal in normal Haskell, notably
268 -- instance CCallable [Char]
269 tcLocalInstDecl1 decl@(InstDecl poly_ty binds uprags Nothing src_loc)
270 = -- Prime error recovery, set source location
271 recoverNF_Tc (returnNF_Tc Nothing) $
272 tcAddSrcLoc src_loc $
273 tcAddErrCtxt (instDeclCtxt poly_ty) $
275 -- Typecheck the instance type itself. We can't use
276 -- tcHsSigType, because it's not a valid user type.
277 kcHsSigType poly_ty `thenTc_`
278 tcHsType poly_ty `thenTc` \ poly_ty' ->
280 (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
282 checkValidTheta InstThetaCtxt theta `thenTc_`
283 checkValidInstHead tau `thenTc` \ (clas,inst_tys) ->
284 checkTc (checkInstFDs theta clas inst_tys)
285 (instTypeErr (pprClassPred clas inst_tys) msg) `thenTc_`
286 newDFunName clas inst_tys src_loc `thenNF_Tc` \ dfun_name ->
287 returnTc (Just (InstInfo { iDFunId = mkDictFunId dfun_name clas tyvars inst_tys theta,
288 iBinds = binds, iPrags = uprags }))
290 msg = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
294 %************************************************************************
296 \subsection{Extracting generic instance declaration from class declarations}
298 %************************************************************************
300 @getGenericInstances@ extracts the generic instance declarations from a class
301 declaration. For exmaple
306 op{ x+y } (Inl v) = ...
307 op{ x+y } (Inr v) = ...
308 op{ x*y } (v :*: w) = ...
311 gives rise to the instance declarations
313 instance C (x+y) where
317 instance C (x*y) where
325 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo]
326 getGenericInstances class_decls
327 = mapTc get_generics class_decls `thenTc` \ gen_inst_infos ->
329 gen_inst_info = concat gen_inst_infos
331 if null gen_inst_info then
334 getDOptsTc `thenNF_Tc` \ dflags ->
335 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances"
336 (vcat (map pprInstInfo gen_inst_info)))
338 returnTc gen_inst_info
340 get_generics decl@(ClassDecl {tcdMeths = Nothing})
341 = returnTc [] -- Imported class decls
343 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = Just def_methods, tcdLoc = loc})
345 = returnTc [] -- The comon case: no generic default methods
347 | otherwise -- A source class decl with generic default methods
348 = recoverNF_Tc (returnNF_Tc []) $
350 tcLookupClass class_name `thenTc` \ clas ->
352 -- Make an InstInfo out of each group
353 mapTc (mkGenericInstance clas loc) groups `thenTc` \ inst_infos ->
355 -- Check that there is only one InstInfo for each type constructor
356 -- The main way this can fail is if you write
357 -- f {| a+b |} ... = ...
358 -- f {| x+y |} ... = ...
359 -- Then at this point we'll have an InstInfo for each
361 tc_inst_infos :: [(TyCon, InstInfo)]
362 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
364 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
365 group `lengthExceeds` 1]
366 get_uniq (tc,_) = getUnique tc
368 mapTc (addErrTc . dupGenericInsts) bad_groups `thenTc_`
370 -- Check that there is an InstInfo for each generic type constructor
372 missing = genericTyCons `minusList` [tc | (tc,_) <- tc_inst_infos]
374 checkTc (null missing) (missingGenericInstances missing) `thenTc_`
379 -- Group the declarations by type pattern
380 groups :: [(RenamedHsType, RenamedMonoBinds)]
381 groups = assocElts (getGenericBinds def_methods)
384 ---------------------------------
385 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
386 -- Takes a group of method bindings, finds the generic ones, and returns
387 -- them in finite map indexed by the type parameter in the definition.
389 getGenericBinds EmptyMonoBinds = emptyAssoc
390 getGenericBinds (AndMonoBinds m1 m2)
391 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
393 getGenericBinds (FunMonoBind id infixop matches loc)
394 = mapAssoc wrap (foldl add emptyAssoc matches)
395 -- Using foldl not foldr is vital, else
396 -- we reverse the order of the bindings!
398 add env match = case maybeGenericMatch match of
400 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
402 wrap ms = FunMonoBind id infixop ms loc
404 ---------------------------------
405 mkGenericInstance :: Class -> SrcLoc
406 -> (RenamedHsType, RenamedMonoBinds)
409 mkGenericInstance clas loc (hs_ty, binds)
410 -- Make a generic instance declaration
411 -- For example: instance (C a, C b) => C (a+b) where { binds }
413 = -- Extract the universally quantified type variables
415 sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
417 tcHsTyVars sig_tvs (kcHsSigType hs_ty) $ \ tyvars ->
419 -- Type-check the instance type, and check its form
420 tcHsSigType GenPatCtxt hs_ty `thenTc` \ inst_ty ->
421 checkTc (validGenericInstanceType inst_ty)
422 (badGenericInstanceType binds) `thenTc_`
424 -- Make the dictionary function.
425 newDFunName clas [inst_ty] loc `thenNF_Tc` \ dfun_name ->
427 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
428 dfun_id = mkDictFunId dfun_name clas tyvars [inst_ty] inst_theta
431 returnTc (InstInfo { iDFunId = dfun_id, iBinds = binds, iPrags = [] })
435 %************************************************************************
437 \subsection{Type-checking instance declarations, pass 2}
439 %************************************************************************
442 tcInstDecls2 :: [InstInfo]
443 -> NF_TcM (LIE, TcMonoBinds)
445 tcInstDecls2 inst_decls
446 -- = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
447 = foldr combine (returnNF_Tc (emptyLIE, EmptyMonoBinds))
448 (map tcInstDecl2 inst_decls)
450 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
451 tc2 `thenNF_Tc` \ (lie2, binds2) ->
452 returnNF_Tc (lie1 `plusLIE` lie2,
453 binds1 `AndMonoBinds` binds2)
456 ======= New documentation starts here (Sept 92) ==============
458 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
459 the dictionary function for this instance declaration. For example
461 instance Foo a => Foo [a] where
465 might generate something like
467 dfun.Foo.List dFoo_a = let op1 x = ...
473 HOWEVER, if the instance decl has no context, then it returns a
474 bigger @HsBinds@ with declarations for each method. For example
476 instance Foo [a] where
482 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
483 const.Foo.op1.List a x = ...
484 const.Foo.op2.List a y = ...
486 This group may be mutually recursive, because (for example) there may
487 be no method supplied for op2 in which case we'll get
489 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
491 that is, the default method applied to the dictionary at this type.
493 What we actually produce in either case is:
495 AbsBinds [a] [dfun_theta_dicts]
496 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
497 { d = (sd1,sd2, ..., op1, op2, ...)
502 The "maybe" says that we only ask AbsBinds to make global constant methods
503 if the dfun_theta is empty.
506 For an instance declaration, say,
508 instance (C1 a, C2 b) => C (T a b) where
511 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
512 function whose type is
514 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
516 Notice that we pass it the superclass dictionaries at the instance type; this
517 is the ``Mark Jones optimisation''. The stuff before the "=>" here
518 is the @dfun_theta@ below.
520 First comes the easy case of a non-local instance decl.
524 tcInstDecl2 :: InstInfo -> TcM (LIE, TcMonoBinds)
526 tcInstDecl2 (NewTypeDerived { iDFunId = dfun_id })
527 = tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
528 newDicts InstanceDeclOrigin dfun_theta' `thenNF_Tc` \ rep_dicts ->
530 rep_dict_id = ASSERT( isSingleton rep_dicts )
531 instToId (head rep_dicts) -- Derived newtypes have just one dict arg
533 body = TyLam inst_tyvars' $
534 DictLam [rep_dict_id] $
535 (HsVar unsafeCoerceId `TyApp` [idType rep_dict_id, inst_head'])
538 -- You might wonder why we have the 'coerce'. It's because the
539 -- type equality mechanism isn't clever enough; see comments with Type.eqType.
540 -- So Lint complains if we don't have this.
542 returnTc (emptyLIE, VarMonoBind dfun_id body)
544 tcInstDecl2 (InstInfo { iDFunId = dfun_id, iBinds = monobinds, iPrags = uprags })
545 = -- Prime error recovery
546 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
547 tcAddSrcLoc (getSrcLoc dfun_id) $
548 tcAddErrCtxt (instDeclCtxt (toHsType (idType dfun_id))) $
550 -- Instantiate the instance decl with tc-style type variables
551 tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
553 Just pred = tcSplitPredTy_maybe inst_head'
554 (clas, inst_tys') = getClassPredTys pred
555 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
557 sel_names = [idName sel_id | (sel_id, _) <- op_items]
559 -- Instantiate the super-class context with inst_tys
560 sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
562 -- Find any definitions in monobinds that aren't from the class
563 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
564 (inst_tyvars, _) = tcSplitForAllTys (idType dfun_id)
565 origin = InstanceDeclOrigin
567 -- Check that all the method bindings come from this class
568 mapTc (addErrTc . badMethodErr clas) bad_bndrs `thenNF_Tc_`
570 -- Create dictionary Ids from the specified instance contexts.
571 newDicts origin sc_theta' `thenNF_Tc` \ sc_dicts ->
572 newDicts origin dfun_theta' `thenNF_Tc` \ dfun_arg_dicts ->
573 newDicts origin [mkClassPred clas inst_tys'] `thenNF_Tc` \ [this_dict] ->
575 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
576 -- The type variable from the dict fun actually scope
577 -- over the bindings. They were gotten from
578 -- the original instance declaration
580 -- Default-method Ids may be mentioned in synthesised RHSs,
581 -- but they'll already be in the environment.
583 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
585 monobinds uprags True)
587 ) `thenTc` \ (method_binds_s, insts_needed_s, meth_insts) ->
589 -- Deal with SPECIALISE instance pragmas by making them
590 -- look like SPECIALISE pragmas for the dfun
592 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
594 tcExtendGlobalValEnv [dfun_id] (
595 tcSpecSigs dfun_prags
596 ) `thenTc` \ (prag_binds, prag_lie) ->
598 -- Check the overloading constraints of the methods and superclasses
600 -- These insts are in scope; quite a few, eh?
601 avail_insts = [this_dict] ++
606 methods_lie = plusLIEs insts_needed_s
609 -- Simplify the constraints from methods
610 tcAddErrCtxt methodCtxt (
612 (ptext SLIT("instance declaration context"))
616 ) `thenTc` \ (const_lie1, lie_binds1) ->
618 -- Figure out bindings for the superclass context
619 tcAddErrCtxt superClassCtxt (
621 (ptext SLIT("instance declaration context"))
623 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
624 -- get bound by just selecting from this_dict!!
626 ) `thenTc` \ (const_lie2, lie_binds2) ->
628 checkSigTyVars inst_tyvars' emptyVarSet `thenNF_Tc` \ zonked_inst_tyvars ->
630 -- Create the result bindings
632 local_dfun_id = setIdLocalExported dfun_id
633 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
635 dict_constr = classDataCon clas
636 scs_and_meths = map instToId (sc_dicts ++ meth_insts)
637 this_dict_id = instToId this_dict
638 inlines | null dfun_arg_dicts = emptyNameSet
639 | otherwise = unitNameSet (idName dfun_id)
640 -- Always inline the dfun; this is an experimental decision
641 -- because it makes a big performance difference sometimes.
642 -- Often it means we can do the method selection, and then
643 -- inline the method as well. Marcin's idea; see comments below.
645 -- BUT: don't inline it if it's a constant dictionary;
646 -- we'll get all the benefit without inlining, and we get
647 -- a **lot** of code duplication if we inline it
651 = -- Blatant special case for CCallable, CReturnable
652 -- If the dictionary is empty then we should never
653 -- select anything from it, so we make its RHS just
654 -- emit an error message. This in turn means that we don't
655 -- mention the constructor, which doesn't exist for CCallable, CReturnable
656 -- Hardly beautiful, but only three extra lines.
657 HsApp (TyApp (HsVar eRROR_ID) [idType this_dict_id])
658 (HsLit (HsString msg))
660 | otherwise -- The common case
661 = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
662 -- We don't produce a binding for the dict_constr; instead we
663 -- rely on the simplifier to unfold this saturated application
664 -- We do this rather than generate an HsCon directly, because
665 -- it means that the special cases (e.g. dictionary with only one
666 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
667 -- than needing to be repeated here.
670 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
672 dict_bind = VarMonoBind this_dict_id dict_rhs
673 method_binds = andMonoBindList method_binds_s
678 (map instToId dfun_arg_dicts)
679 [(inst_tyvars', local_dfun_id, this_dict_id)]
681 (lie_binds1 `AndMonoBinds`
682 lie_binds2 `AndMonoBinds`
683 method_binds `AndMonoBinds`
686 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
687 main_bind `AndMonoBinds` prag_binds)
690 ------------------------------
691 Inlining dfuns unconditionally
692 ------------------------------
694 The code above unconditionally inlines dict funs. Here's why.
695 Consider this program:
697 test :: Int -> Int -> Bool
698 test x y = (x,y) == (y,x) || test y x
699 -- Recursive to avoid making it inline.
701 This needs the (Eq (Int,Int)) instance. If we inline that dfun
702 the code we end up with is good:
705 \r -> case ==# [ww ww1] of wild {
706 PrelBase.False -> Test.$wtest ww1 ww;
708 case ==# [ww1 ww] of wild1 {
709 PrelBase.False -> Test.$wtest ww1 ww;
710 PrelBase.True -> PrelBase.True [];
713 Test.test = \r [w w1]
716 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
719 If we don't inline the dfun, the code is not nearly as good:
721 (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
722 PrelBase.:DEq tpl1 tpl2 -> tpl2;
727 let { y = PrelBase.I#! [ww1]; } in
728 let { x = PrelBase.I#! [ww]; } in
729 let { sat_slx = PrelTup.(,)! [y x]; } in
730 let { sat_sly = PrelTup.(,)! [x y];
732 case == sat_sly sat_slx of wild {
733 PrelBase.False -> Test.$wtest ww1 ww;
734 PrelBase.True -> PrelBase.True [];
741 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
744 Why doesn't GHC inline $fEq? Because it looks big:
746 PrelTup.zdfEqZ1T{-rcX-}
747 = \ @ a{-reT-} :: * @ b{-reS-} :: *
748 zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
749 zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
751 zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
752 zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
754 zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
755 zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
757 zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
758 zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
759 ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
761 of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
763 of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
765 (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
766 (zeze{-rf0-} a2{-reZ-} b2{-reY-})
770 a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
771 a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
772 b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
773 PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
775 PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
777 and it's not as bad as it seems, because it's further dramatically
778 simplified: only zeze2 is extracted and its body is simplified.
781 %************************************************************************
783 \subsection{Error messages}
785 %************************************************************************
788 tcAddDeclCtxt decl thing_inside
789 = tcAddSrcLoc (tcdLoc decl) $
794 ClassDecl {} -> "class"
795 TySynonym {} -> "type synonym"
796 TyData {tcdND = NewType} -> "newtype"
797 TyData {tcdND = DataType} -> "data type"
799 ctxt = hsep [ptext SLIT("In the"), text thing,
800 ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
802 instDeclCtxt inst_ty = ptext SLIT("In the instance declaration for") <+> quotes doc
804 doc = case inst_ty of
805 HsForAllTy _ _ (HsPredTy pred) -> ppr pred
806 HsPredTy pred -> ppr pred
807 other -> ppr inst_ty -- Don't expect this
811 badGenericInstanceType binds
812 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
815 missingGenericInstances missing
816 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
818 dupGenericInsts tc_inst_infos
819 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
820 nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
821 ptext SLIT("All the type patterns for a generic type constructor must be identical")
824 ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
826 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
827 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")