2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcInstDecls]{Typechecking instance declarations}
7 module TcInstDcls ( tcInstDecls1, tcIfaceInstDecls1, addInstDFuns,
8 tcInstDecls2, 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, PersistentCompilerState(..),
48 ModDetails(..), PackageInstEnv
50 import Subst ( substTy, substTheta )
51 import DataCon ( classDataCon )
52 import Class ( Class, classBigSig )
53 import Var ( idName, idType )
54 import VarSet ( emptyVarSet )
55 import Id ( setIdLocalExported )
56 import MkId ( mkDictFunId, unsafeCoerceId, eRROR_ID )
57 import FunDeps ( checkInstFDs )
58 import Generics ( validGenericInstanceType )
59 import Module ( Module, foldModuleEnv )
60 import Name ( getSrcLoc )
61 import NameSet ( unitNameSet, emptyNameSet, nameSetToList )
62 import TyCon ( TyCon )
63 import Subst ( mkTopTyVarSubst, substTheta )
64 import TysWiredIn ( genericTyCons )
66 import SrcLoc ( SrcLoc )
67 import Unique ( Uniquable(..) )
68 import Util ( lengthExceeds, isSingleton )
69 import BasicTypes ( NewOrData(..), Fixity )
70 import ErrUtils ( dumpIfSet_dyn )
71 import ListSetOps ( Assoc, emptyAssoc, plusAssoc_C, mapAssoc,
72 assocElts, extendAssoc_C, equivClassesByUniq, minusList
74 import Maybe ( catMaybes )
75 import List ( partition )
79 Typechecking instance declarations is done in two passes. The first
80 pass, made by @tcInstDecls1@, collects information to be used in the
83 This pre-processed info includes the as-yet-unprocessed bindings
84 inside the instance declaration. These are type-checked in the second
85 pass, when the class-instance envs and GVE contain all the info from
86 all the instance and value decls. Indeed that's the reason we need
87 two passes over the instance decls.
90 Here is the overall algorithm.
91 Assume that we have an instance declaration
93 instance c => k (t tvs) where b
97 $LIE_c$ is the LIE for the context of class $c$
99 $betas_bar$ is the free variables in the class method type, excluding the
102 $LIE_cop$ is the LIE constraining a particular class method
104 $tau_cop$ is the tau type of a class method
106 $LIE_i$ is the LIE for the context of instance $i$
108 $X$ is the instance constructor tycon
110 $gammas_bar$ is the set of type variables of the instance
112 $LIE_iop$ is the LIE for a particular class method instance
114 $tau_iop$ is the tau type for this instance of a class method
116 $alpha$ is the class variable
118 $LIE_cop' = LIE_cop [X gammas_bar / alpha, fresh betas_bar]$
120 $tau_cop' = tau_cop [X gammas_bar / alpha, fresh betas_bar]$
123 ToDo: Update the list above with names actually in the code.
127 First, make the LIEs for the class and instance contexts, which means
128 instantiate $thetaC [X inst_tyvars / alpha ]$, yielding LIElistC' and LIEC',
129 and make LIElistI and LIEI.
131 Then process each method in turn.
133 order the instance methods according to the ordering of the class methods
135 express LIEC' in terms of LIEI, yielding $dbinds_super$ or an error
137 Create final dictionary function from bindings generated already
139 df = lambda inst_tyvars
146 in <op1,op2,...,opn,sd1,...,sdm>
148 Here, Bop1 \ldots Bopn bind the methods op1 \ldots opn,
149 and $dbinds_super$ bind the superclass dictionaries sd1 \ldots sdm.
153 %************************************************************************
155 \subsection{Extracting instance decls}
157 %************************************************************************
159 Gather up the instance declarations from their various sources
162 tcInstDecls1 -- Deal with source-code instance decls
163 :: PersistentCompilerState
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
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 pcs hst unf_env get_fixity
176 this_mod tycl_decls inst_decls
178 pkg_inst_env = pcs_insts pcs
180 clas_decls = filter isClassDecl tycl_decls
182 -- (1) Do the ordinary instance declarations
183 mapNF_Tc tcLocalInstDecl1 inst_decls `thenNF_Tc` \ local_inst_infos ->
185 -- (2) Instances from generic class declarations
186 getGenericInstances clas_decls `thenTc` \ generic_inst_info ->
188 -- Next, construct the instance environment so far, consisting of
189 -- a) cached non-home-package InstEnv (gotten from pcs) inst_env0
190 -- b) imported instance decls (not in the home package) inst_env1
191 -- c) other modules in this package (gotten from hst) inst_env2
192 -- d) imported instance decls (from this module) inst_env3
193 -- e) local instance decls inst_env4
194 -- f) generic instances inst_env5
195 -- The result of (b) replaces the cached InstEnv in the PCS
197 -- Note that iface_dfuns may contain not only insts that we
198 -- demand-loaded from interface files, but also instances from
199 -- the current module in the case where we are loading this
200 -- module's interface file in GHCi, so we partition the
201 -- iface_dfuns into non-local and local instances so that we
202 -- don't end up with home package instances in the PCS.
204 -- There can't be any instance declarations from the home
205 -- package other than from the current module (with the
206 -- compilation manager) because they are loaded explicitly by
207 -- the compilation manager.
209 local_inst_info = catMaybes local_inst_infos
210 hst_dfuns = foldModuleEnv ((++) . md_insts) [] hst
213 -- pprTrace "tcInstDecls" (vcat [ppr imported_dfuns, ppr hst_dfuns]) $
215 addInstDFuns pkg_inst_env hst_dfuns `thenNF_Tc` \ inst_env2 ->
216 addInstInfos inst_env2 local_inst_info `thenNF_Tc` \ inst_env3 ->
217 addInstInfos inst_env3 generic_inst_info `thenNF_Tc` \ inst_env4 ->
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
225 get_fixity tycl_decls `thenTc` \ (deriv_inst_info, deriv_binds) ->
226 addInstInfos inst_env4 deriv_inst_info `thenNF_Tc` \ final_inst_env ->
228 returnTc (final_inst_env,
229 generic_inst_info ++ deriv_inst_info ++ local_inst_info,
232 addInstInfos :: InstEnv -> [InstInfo] -> NF_TcM InstEnv
233 addInstInfos inst_env infos = addInstDFuns inst_env (map iDFunId infos)
235 addInstDFuns :: InstEnv -> [DFunId] -> NF_TcM InstEnv
236 addInstDFuns inst_env dfuns
237 = getDOptsTc `thenNF_Tc` \ dflags ->
239 (inst_env', errs) = extendInstEnv dflags inst_env dfuns
241 addErrsTc errs `thenNF_Tc_`
242 traceTc (text "Adding instances:" <+> vcat (map pp dfuns)) `thenTc_`
245 pp dfun = ppr dfun <+> dcolon <+> ppr (idType dfun)
249 tcIfaceInstDecls1 :: [RenamedInstDecl] -> NF_TcM [DFunId]
250 tcIfaceInstDecls1 decls = mapNF_Tc tcIfaceInstDecl1 decls
252 tcIfaceInstDecl1 :: RenamedInstDecl -> NF_TcM DFunId
253 -- An interface-file instance declaration
254 -- Should be in scope by now, because we should
255 -- have sucked in its interface-file definition
256 -- So it will be replete with its unfolding etc
257 tcIfaceInstDecl1 decl@(InstDecl poly_ty binds uprags (Just dfun_name) src_loc)
258 = tcLookupId dfun_name
261 tcLocalInstDecl1 :: RenamedInstDecl
262 -> NF_TcM (Maybe InstInfo) -- Nothing if there was an error
263 -- A source-file instance declaration
264 -- Type-check all the stuff before the "where"
266 -- We check for respectable instance type, and context
267 -- but only do this for non-imported instance decls.
268 -- Imported ones should have been checked already, and may indeed
269 -- contain something illegal in normal Haskell, notably
270 -- instance CCallable [Char]
271 tcLocalInstDecl1 decl@(InstDecl poly_ty binds uprags Nothing src_loc)
272 = -- Prime error recovery, set source location
273 recoverNF_Tc (returnNF_Tc Nothing) $
274 tcAddSrcLoc src_loc $
275 tcAddErrCtxt (instDeclCtxt poly_ty) $
277 -- Typecheck the instance type itself. We can't use
278 -- tcHsSigType, because it's not a valid user type.
279 kcHsSigType poly_ty `thenTc_`
280 tcHsType poly_ty `thenTc` \ poly_ty' ->
282 (tyvars, theta, tau) = tcSplitSigmaTy poly_ty'
284 checkValidTheta InstThetaCtxt theta `thenTc_`
285 checkValidInstHead tau `thenTc` \ (clas,inst_tys) ->
286 checkTc (checkInstFDs theta clas inst_tys)
287 (instTypeErr (pprClassPred clas inst_tys) msg) `thenTc_`
288 newDFunName clas inst_tys src_loc `thenNF_Tc` \ dfun_name ->
289 returnTc (Just (InstInfo { iDFunId = mkDictFunId dfun_name clas tyvars inst_tys theta,
290 iBinds = binds, iPrags = uprags }))
292 msg = parens (ptext SLIT("the instance types do not agree with the functional dependencies of the class"))
296 %************************************************************************
298 \subsection{Extracting generic instance declaration from class declarations}
300 %************************************************************************
302 @getGenericInstances@ extracts the generic instance declarations from a class
303 declaration. For exmaple
308 op{ x+y } (Inl v) = ...
309 op{ x+y } (Inr v) = ...
310 op{ x*y } (v :*: w) = ...
313 gives rise to the instance declarations
315 instance C (x+y) where
319 instance C (x*y) where
327 getGenericInstances :: [RenamedTyClDecl] -> TcM [InstInfo]
328 getGenericInstances class_decls
329 = mapTc get_generics class_decls `thenTc` \ gen_inst_infos ->
331 gen_inst_info = concat gen_inst_infos
333 if null gen_inst_info then
336 getDOptsTc `thenNF_Tc` \ dflags ->
337 ioToTc (dumpIfSet_dyn dflags Opt_D_dump_deriv "Generic instances"
338 (vcat (map pprInstInfo gen_inst_info)))
340 returnTc gen_inst_info
342 get_generics decl@(ClassDecl {tcdMeths = Nothing})
343 = returnTc [] -- Imported class decls
345 get_generics decl@(ClassDecl {tcdName = class_name, tcdMeths = Just def_methods, tcdLoc = loc})
347 = returnTc [] -- The comon case: no generic default methods
349 | otherwise -- A source class decl with generic default methods
350 = recoverNF_Tc (returnNF_Tc []) $
352 tcLookupClass class_name `thenTc` \ clas ->
354 -- Make an InstInfo out of each group
355 mapTc (mkGenericInstance clas loc) groups `thenTc` \ inst_infos ->
357 -- Check that there is only one InstInfo for each type constructor
358 -- The main way this can fail is if you write
359 -- f {| a+b |} ... = ...
360 -- f {| x+y |} ... = ...
361 -- Then at this point we'll have an InstInfo for each
363 tc_inst_infos :: [(TyCon, InstInfo)]
364 tc_inst_infos = [(simpleInstInfoTyCon i, i) | i <- inst_infos]
366 bad_groups = [group | group <- equivClassesByUniq get_uniq tc_inst_infos,
367 group `lengthExceeds` 1]
368 get_uniq (tc,_) = getUnique tc
370 mapTc (addErrTc . dupGenericInsts) bad_groups `thenTc_`
372 -- Check that there is an InstInfo for each generic type constructor
374 missing = genericTyCons `minusList` [tc | (tc,_) <- tc_inst_infos]
376 checkTc (null missing) (missingGenericInstances missing) `thenTc_`
381 -- Group the declarations by type pattern
382 groups :: [(RenamedHsType, RenamedMonoBinds)]
383 groups = assocElts (getGenericBinds def_methods)
386 ---------------------------------
387 getGenericBinds :: RenamedMonoBinds -> Assoc RenamedHsType RenamedMonoBinds
388 -- Takes a group of method bindings, finds the generic ones, and returns
389 -- them in finite map indexed by the type parameter in the definition.
391 getGenericBinds EmptyMonoBinds = emptyAssoc
392 getGenericBinds (AndMonoBinds m1 m2)
393 = plusAssoc_C AndMonoBinds (getGenericBinds m1) (getGenericBinds m2)
395 getGenericBinds (FunMonoBind id infixop matches loc)
396 = mapAssoc wrap (foldl add emptyAssoc matches)
397 -- Using foldl not foldr is vital, else
398 -- we reverse the order of the bindings!
400 add env match = case maybeGenericMatch match of
402 Just (ty, match') -> extendAssoc_C (++) env (ty, [match'])
404 wrap ms = FunMonoBind id infixop ms loc
406 ---------------------------------
407 mkGenericInstance :: Class -> SrcLoc
408 -> (RenamedHsType, RenamedMonoBinds)
411 mkGenericInstance clas loc (hs_ty, binds)
412 -- Make a generic instance declaration
413 -- For example: instance (C a, C b) => C (a+b) where { binds }
415 = -- Extract the universally quantified type variables
417 sig_tvs = map UserTyVar (nameSetToList (extractHsTyVars hs_ty))
419 tcHsTyVars sig_tvs (kcHsSigType hs_ty) $ \ tyvars ->
421 -- Type-check the instance type, and check its form
422 tcHsSigType GenPatCtxt hs_ty `thenTc` \ inst_ty ->
423 checkTc (validGenericInstanceType inst_ty)
424 (badGenericInstanceType binds) `thenTc_`
426 -- Make the dictionary function.
427 newDFunName clas [inst_ty] loc `thenNF_Tc` \ dfun_name ->
429 inst_theta = [mkClassPred clas [mkTyVarTy tv] | tv <- tyvars]
430 dfun_id = mkDictFunId dfun_name clas tyvars [inst_ty] inst_theta
433 returnTc (InstInfo { iDFunId = dfun_id, iBinds = binds, iPrags = [] })
437 %************************************************************************
439 \subsection{Type-checking instance declarations, pass 2}
441 %************************************************************************
444 tcInstDecls2 :: [InstInfo]
445 -> NF_TcM (LIE, TcMonoBinds)
447 tcInstDecls2 inst_decls
448 -- = foldBag combine tcInstDecl2 (returnNF_Tc (emptyLIE, EmptyMonoBinds)) inst_decls
449 = foldr combine (returnNF_Tc (emptyLIE, EmptyMonoBinds))
450 (map tcInstDecl2 inst_decls)
452 combine tc1 tc2 = tc1 `thenNF_Tc` \ (lie1, binds1) ->
453 tc2 `thenNF_Tc` \ (lie2, binds2) ->
454 returnNF_Tc (lie1 `plusLIE` lie2,
455 binds1 `AndMonoBinds` binds2)
458 ======= New documentation starts here (Sept 92) ==============
460 The main purpose of @tcInstDecl2@ is to return a @HsBinds@ which defines
461 the dictionary function for this instance declaration. For example
463 instance Foo a => Foo [a] where
467 might generate something like
469 dfun.Foo.List dFoo_a = let op1 x = ...
475 HOWEVER, if the instance decl has no context, then it returns a
476 bigger @HsBinds@ with declarations for each method. For example
478 instance Foo [a] where
484 dfun.Foo.List a = Dict [Foo.op1.List a, Foo.op2.List a]
485 const.Foo.op1.List a x = ...
486 const.Foo.op2.List a y = ...
488 This group may be mutually recursive, because (for example) there may
489 be no method supplied for op2 in which case we'll get
491 const.Foo.op2.List a = default.Foo.op2 (dfun.Foo.List a)
493 that is, the default method applied to the dictionary at this type.
495 What we actually produce in either case is:
497 AbsBinds [a] [dfun_theta_dicts]
498 [(dfun.Foo.List, d)] ++ (maybe) [(const.Foo.op1.List, op1), ...]
499 { d = (sd1,sd2, ..., op1, op2, ...)
504 The "maybe" says that we only ask AbsBinds to make global constant methods
505 if the dfun_theta is empty.
508 For an instance declaration, say,
510 instance (C1 a, C2 b) => C (T a b) where
513 where the {\em immediate} superclasses of C are D1, D2, we build a dictionary
514 function whose type is
516 (C1 a, C2 b, D1 (T a b), D2 (T a b)) => C (T a b)
518 Notice that we pass it the superclass dictionaries at the instance type; this
519 is the ``Mark Jones optimisation''. The stuff before the "=>" here
520 is the @dfun_theta@ below.
522 First comes the easy case of a non-local instance decl.
526 tcInstDecl2 :: InstInfo -> TcM (LIE, TcMonoBinds)
528 tcInstDecl2 (NewTypeDerived { iDFunId = dfun_id })
529 = tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
530 newDicts InstanceDeclOrigin dfun_theta' `thenNF_Tc` \ rep_dicts ->
532 rep_dict_id = ASSERT( isSingleton rep_dicts )
533 instToId (head rep_dicts) -- Derived newtypes have just one dict arg
535 body = TyLam inst_tyvars' $
536 DictLam [rep_dict_id] $
537 (HsVar unsafeCoerceId `TyApp` [idType rep_dict_id, inst_head'])
540 -- You might wonder why we have the 'coerce'. It's because the
541 -- type equality mechanism isn't clever enough; see comments with Type.eqType.
542 -- So Lint complains if we don't have this.
544 returnTc (emptyLIE, VarMonoBind dfun_id body)
546 tcInstDecl2 (InstInfo { iDFunId = dfun_id, iBinds = monobinds, iPrags = uprags })
547 = -- Prime error recovery
548 recoverNF_Tc (returnNF_Tc (emptyLIE, EmptyMonoBinds)) $
549 tcAddSrcLoc (getSrcLoc dfun_id) $
550 tcAddErrCtxt (instDeclCtxt (toHsType (idType dfun_id))) $
552 -- Instantiate the instance decl with tc-style type variables
553 tcInstSigType InstTv (idType dfun_id) `thenNF_Tc` \ (inst_tyvars', dfun_theta', inst_head') ->
555 Just pred = tcSplitPredTy_maybe inst_head'
556 (clas, inst_tys') = getClassPredTys pred
557 (class_tyvars, sc_theta, _, op_items) = classBigSig clas
559 sel_names = [idName sel_id | (sel_id, _) <- op_items]
561 -- Instantiate the super-class context with inst_tys
562 sc_theta' = substTheta (mkTopTyVarSubst class_tyvars inst_tys') sc_theta
564 -- Find any definitions in monobinds that aren't from the class
565 bad_bndrs = collectMonoBinders monobinds `minusList` sel_names
566 (inst_tyvars, _) = tcSplitForAllTys (idType dfun_id)
567 origin = InstanceDeclOrigin
569 -- Check that all the method bindings come from this class
570 mapTc (addErrTc . badMethodErr clas) bad_bndrs `thenNF_Tc_`
572 -- Create dictionary Ids from the specified instance contexts.
573 newDicts origin sc_theta' `thenNF_Tc` \ sc_dicts ->
574 newDicts origin dfun_theta' `thenNF_Tc` \ dfun_arg_dicts ->
575 newDicts origin [mkClassPred clas inst_tys'] `thenNF_Tc` \ [this_dict] ->
577 tcExtendTyVarEnvForMeths inst_tyvars inst_tyvars' (
578 -- The type variable from the dict fun actually scope
579 -- over the bindings. They were gotten from
580 -- the original instance declaration
582 -- Default-method Ids may be mentioned in synthesised RHSs,
583 -- but they'll already be in the environment.
585 mapAndUnzip3Tc (tcMethodBind clas origin inst_tyvars' inst_tys'
587 monobinds uprags True)
589 ) `thenTc` \ (method_binds_s, insts_needed_s, meth_insts) ->
591 -- Deal with SPECIALISE instance pragmas by making them
592 -- look like SPECIALISE pragmas for the dfun
594 dfun_prags = [SpecSig (idName dfun_id) ty loc | SpecInstSig ty loc <- uprags]
596 tcExtendGlobalValEnv [dfun_id] (
597 tcSpecSigs dfun_prags
598 ) `thenTc` \ (prag_binds, prag_lie) ->
600 -- Check the overloading constraints of the methods and superclasses
602 -- These insts are in scope; quite a few, eh?
603 avail_insts = [this_dict] ++
608 methods_lie = plusLIEs insts_needed_s
611 -- Simplify the constraints from methods
612 tcAddErrCtxt methodCtxt (
614 (ptext SLIT("instance declaration context"))
618 ) `thenTc` \ (const_lie1, lie_binds1) ->
620 -- Figure out bindings for the superclass context
621 tcAddErrCtxt superClassCtxt (
623 (ptext SLIT("instance declaration context"))
625 dfun_arg_dicts -- NB! Don't include this_dict here, else the sc_dicts
626 -- get bound by just selecting from this_dict!!
628 ) `thenTc` \ (const_lie2, lie_binds2) ->
630 checkSigTyVars inst_tyvars' emptyVarSet `thenNF_Tc` \ zonked_inst_tyvars ->
632 -- Create the result bindings
634 local_dfun_id = setIdLocalExported dfun_id
635 -- Reason for setIdLocalExported: see notes with MkId.mkDictFunId
637 dict_constr = classDataCon clas
638 scs_and_meths = map instToId (sc_dicts ++ meth_insts)
639 this_dict_id = instToId this_dict
640 inlines | null dfun_arg_dicts = emptyNameSet
641 | otherwise = unitNameSet (idName dfun_id)
642 -- Always inline the dfun; this is an experimental decision
643 -- because it makes a big performance difference sometimes.
644 -- Often it means we can do the method selection, and then
645 -- inline the method as well. Marcin's idea; see comments below.
647 -- BUT: don't inline it if it's a constant dictionary;
648 -- we'll get all the benefit without inlining, and we get
649 -- a **lot** of code duplication if we inline it
653 = -- Blatant special case for CCallable, CReturnable
654 -- If the dictionary is empty then we should never
655 -- select anything from it, so we make its RHS just
656 -- emit an error message. This in turn means that we don't
657 -- mention the constructor, which doesn't exist for CCallable, CReturnable
658 -- Hardly beautiful, but only three extra lines.
659 HsApp (TyApp (HsVar eRROR_ID) [idType this_dict_id])
660 (HsLit (HsString msg))
662 | otherwise -- The common case
663 = mkHsConApp dict_constr inst_tys' (map HsVar scs_and_meths)
664 -- We don't produce a binding for the dict_constr; instead we
665 -- rely on the simplifier to unfold this saturated application
666 -- We do this rather than generate an HsCon directly, because
667 -- it means that the special cases (e.g. dictionary with only one
668 -- member) are dealt with by the common MkId.mkDataConWrapId code rather
669 -- than needing to be repeated here.
672 msg = _PK_ ("Compiler error: bad dictionary " ++ showSDoc (ppr clas))
674 dict_bind = VarMonoBind this_dict_id dict_rhs
675 method_binds = andMonoBindList method_binds_s
680 (map instToId dfun_arg_dicts)
681 [(inst_tyvars', local_dfun_id, this_dict_id)]
683 (lie_binds1 `AndMonoBinds`
684 lie_binds2 `AndMonoBinds`
685 method_binds `AndMonoBinds`
688 returnTc (const_lie1 `plusLIE` const_lie2 `plusLIE` prag_lie,
689 main_bind `AndMonoBinds` prag_binds)
692 ------------------------------
693 Inlining dfuns unconditionally
694 ------------------------------
696 The code above unconditionally inlines dict funs. Here's why.
697 Consider this program:
699 test :: Int -> Int -> Bool
700 test x y = (x,y) == (y,x) || test y x
701 -- Recursive to avoid making it inline.
703 This needs the (Eq (Int,Int)) instance. If we inline that dfun
704 the code we end up with is good:
707 \r -> case ==# [ww ww1] of wild {
708 PrelBase.False -> Test.$wtest ww1 ww;
710 case ==# [ww1 ww] of wild1 {
711 PrelBase.False -> Test.$wtest ww1 ww;
712 PrelBase.True -> PrelBase.True [];
715 Test.test = \r [w w1]
718 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
721 If we don't inline the dfun, the code is not nearly as good:
723 (==) = case PrelTup.$fEq(,) PrelBase.$fEqInt PrelBase.$fEqInt of tpl {
724 PrelBase.:DEq tpl1 tpl2 -> tpl2;
729 let { y = PrelBase.I#! [ww1]; } in
730 let { x = PrelBase.I#! [ww]; } in
731 let { sat_slx = PrelTup.(,)! [y x]; } in
732 let { sat_sly = PrelTup.(,)! [x y];
734 case == sat_sly sat_slx of wild {
735 PrelBase.False -> Test.$wtest ww1 ww;
736 PrelBase.True -> PrelBase.True [];
743 case w1 of w3 { PrelBase.I# ww1 -> Test.$wtest ww ww1; };
746 Why doesn't GHC inline $fEq? Because it looks big:
748 PrelTup.zdfEqZ1T{-rcX-}
749 = \ @ a{-reT-} :: * @ b{-reS-} :: *
750 zddEq{-rf6-} _Ks :: {PrelBase.Eq{-23-} a{-reT-}}
751 zddEq1{-rf7-} _Ks :: {PrelBase.Eq{-23-} b{-reS-}} ->
753 zeze{-rf0-} _Kl :: (b{-reS-} -> b{-reS-} -> PrelBase.Bool{-3c-})
754 zeze{-rf0-} = PrelBase.zeze{-01L-}@ b{-reS-} zddEq1{-rf7-} } in
756 zeze1{-rf3-} _Kl :: (a{-reT-} -> a{-reT-} -> PrelBase.Bool{-3c-})
757 zeze1{-rf3-} = PrelBase.zeze{-01L-} @ a{-reT-} zddEq{-rf6-} } in
759 zeze2{-reN-} :: ((a{-reT-}, b{-reS-}) -> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
760 zeze2{-reN-} = \ ds{-rf5-} _Ks :: (a{-reT-}, b{-reS-})
761 ds1{-rf4-} _Ks :: (a{-reT-}, b{-reS-}) ->
763 of wild{-reW-} _Kd { (a1{-rf2-} _Ks, a2{-reZ-} _Ks) ->
765 of wild1{-reX-} _Kd { (b1{-rf1-} _Ks, b2{-reY-} _Ks) ->
767 (zeze1{-rf3-} a1{-rf2-} b1{-rf1-})
768 (zeze{-rf0-} a2{-reZ-} b2{-reY-})
772 a1{-reR-} :: ((a{-reT-}, b{-reS-})-> (a{-reT-}, b{-reS-})-> PrelBase.Bool{-3c-})
773 a1{-reR-} = \ a2{-reV-} _Ks :: (a{-reT-}, b{-reS-})
774 b1{-reU-} _Ks :: (a{-reT-}, b{-reS-}) ->
775 PrelBase.not{-r6I-} (zeze2{-reN-} a2{-reV-} b1{-reU-})
777 PrelBase.zdwZCDEq{-r8J-} @ (a{-reT-}, b{-reS-}) a1{-reR-} zeze2{-reN-})
779 and it's not as bad as it seems, because it's further dramatically
780 simplified: only zeze2 is extracted and its body is simplified.
783 %************************************************************************
785 \subsection{Error messages}
787 %************************************************************************
790 tcAddDeclCtxt decl thing_inside
791 = tcAddSrcLoc (tcdLoc decl) $
796 ClassDecl {} -> "class"
797 TySynonym {} -> "type synonym"
798 TyData {tcdND = NewType} -> "newtype"
799 TyData {tcdND = DataType} -> "data type"
801 ctxt = hsep [ptext SLIT("In the"), text thing,
802 ptext SLIT("declaration for"), quotes (ppr (tcdName decl))]
804 instDeclCtxt inst_ty = ptext SLIT("In the instance declaration for") <+> quotes doc
806 doc = case inst_ty of
807 HsForAllTy _ _ (HsPredTy pred) -> ppr pred
808 HsPredTy pred -> ppr pred
809 other -> ppr inst_ty -- Don't expect this
813 badGenericInstanceType binds
814 = vcat [ptext SLIT("Illegal type pattern in the generic bindings"),
817 missingGenericInstances missing
818 = ptext SLIT("Missing type patterns for") <+> pprQuotedList missing
820 dupGenericInsts tc_inst_infos
821 = vcat [ptext SLIT("More than one type pattern for a single generic type constructor:"),
822 nest 4 (vcat (map ppr_inst_ty tc_inst_infos)),
823 ptext SLIT("All the type patterns for a generic type constructor must be identical")
826 ppr_inst_ty (tc,inst) = ppr (simpleInstInfoTy inst)
828 methodCtxt = ptext SLIT("When checking the methods of an instance declaration")
829 superClassCtxt = ptext SLIT("When checking the super-classes of an instance declaration")