3 TcId, TcIdSet, tcInstId,
5 TcEnv, TyThing(..), TyThingDetails(..),
9 -- Getting stuff from the environment
10 tcEnvTyCons, tcEnvClasses, tcEnvIds, tcEnvTcIds,
13 tcLookupTy, tcLookupTyCon, tcLookupClass, tcLookupGlobalId, tcLookupDataCon,
16 tcExtendKindEnv, tcExtendTyVarEnv,
17 tcExtendTyVarEnvForMeths, tcExtendTypeEnv, tcGetInScopeTyVars,
19 -- Global type variables
20 tcGetGlobalTyVars, tcExtendGlobalTyVars,
22 tcExtendGlobalValEnv, tcExtendLocalValEnv,
23 tcGetValueEnv, tcSetValueEnv,
26 tcLookupValue, tcLookupValueMaybe,
29 newLocalId, newSpecPragmaId,
30 newDefaultMethodName, newDFunName,
32 InstEnv, emptyInstEnv, addToInstEnv,
33 lookupInstEnv, InstLookupResult(..),
34 tcGetInstEnv, tcSetInstEnv, classInstEnv,
39 #include "HsVersions.h"
41 import Id ( mkUserLocal, isDataConWrapId_maybe )
42 import MkId ( mkSpecPragmaId )
43 import Var ( TyVar, Id, setVarName,
44 idType, lazySetIdInfo, idInfo, tyVarKind, UVar,
46 import TcType ( TcType, TcTyVar, TcTyVarSet, TcThetaType,
47 tcInstTyVars, zonkTcTyVars,
51 import Type ( Kind, Type, superKind,
52 tyVarsOfType, tyVarsOfTypes,
53 splitForAllTys, splitRhoTy, splitFunTys,
54 splitAlgTyConApp_maybe, getTyVar, getDFunTyKey
56 import Subst ( substTy )
57 import UsageSPUtils ( unannotTy )
58 import DataCon ( DataCon )
59 import TyCon ( TyCon, tyConKind, tyConArity, isSynTyCon )
60 import Class ( Class, ClassOpItem, ClassContext, classTyCon )
64 import IdInfo ( vanillaIdInfo )
65 import Name ( Name, OccName, Provenance(..), ExportFlag(..), NamedThing(..),
66 nameOccName, nameModule, getSrcLoc, mkGlobalName,
67 maybeWiredInTyConName, maybeWiredInIdName, isLocallyDefined,
68 NameEnv, emptyNameEnv, lookupNameEnv, nameEnvElts,
69 extendNameEnv, extendNameEnvList
71 import OccName ( mkDFunOcc, mkDefaultMethodOcc, occNameString )
72 import Module ( Module )
73 import Unify ( unifyTyListsX, matchTys )
74 import Unique ( pprUnique10, Unique, Uniquable(..) )
76 import Unique ( Uniquable(..) )
77 import Util ( zipEqual, zipWith3Equal, mapAccumL )
78 import VarEnv ( TyVarSubstEnv )
79 import SrcLoc ( SrcLoc )
80 import FastString ( FastString )
85 %************************************************************************
89 %************************************************************************
94 tcGST :: GlobalSymbolTable, -- The symbol table at the moment we began this compilation
96 tcInst :: InstEnv, -- All instances (both imported and in this module)
98 tcGEnv :: NameEnv TyThing -- The global type environment we've accumulated while
99 -- compiling this module:
100 -- types and classes (both imported and local)
102 -- (Ids defined in this module are in the local envt)
104 tcLEnv :: NameEnv TcTyThing, -- The local type environment: Ids and TyVars
105 -- defined in this module
107 tcTyVars :: TcRef TcTyVarSet -- The "global tyvars"
108 -- Namely, the in-scope TyVars bound in tcLEnv, plus the tyvars
109 -- mentioned in the types of Ids bound in tcLEnv
110 -- Why mutable? see notes with tcGetGlobalTyVars
115 The Global-Env/Local-Env story
116 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
117 During type checking, we keep in the GlobalEnv
118 * All types and classes
119 * All Ids derived from types and classes (constructors, selectors)
122 At the end of type checking, we zonk the local bindings,
123 and as we do so we add to the GlobalEnv
124 * Locally defined top-level Ids
126 Why? Because they are now Ids not TcIds. This final GlobalEnv is
128 a) fed back (via the knot) to typechecking the
129 unfoldings of interface signatures
131 b) used to augment the GlobalSymbolTable
136 = AGlobal TyThing -- Used only in the return type of a lookup
137 | ATcId TcId -- Ids defined in this module
138 | ATyVar TyVar -- Type variables
139 | AThing TcKind -- Used temporarily, during kind checking
140 -- Here's an example of how the AThing guy is used
141 -- Suppose we are checking (forall a. T a Int):
142 -- 1. We first bind (a -> AThink kv), where kv is a kind variable.
143 -- 2. Then we kind-check the (T a Int) part.
144 -- 3. Then we zonk the kind variable.
145 -- 4. Now we know the kind for 'a', and we add (a -> ATyVar a::K) to the environment
147 initEnv :: GlobalSymbolTable -> InstEnv -> NF_TcM TcEnv
149 = tcNewMutVar emptyVarSet `thenNF_Tc` \ gtv_var ->
150 returnTc (TcEnv { tcGST = gst,
151 tcGEnv = emptyNameEnv,
153 tcLEnv = emptyNameEnv,
157 tcEnvClasses env = [cl | AClass cl <- nameEnvElts (tcGEnv env)]
158 tcEnvTyCons env = [tc | ATyCon tc <- nameEnvElts (tcGEnv env)]
159 tcEnvIds env = [id | AnId id <- nameEnvElts (tcGEnv env)]
160 tcEnvTyVars env = [tv | ATyVar tv <- nameEnvElts (tcLEnv env)]
161 tcEnvTcIds env = [id | ATcId id <- nameEnvElts (tcLEnv env)]
163 -- This data type is used to help tie the knot
164 -- when type checking type and class declarations
165 data TyThingDetails = SynTyDetails Type
166 | DataTyDetails ClassContext [DataCon] [Class]
167 | ClassDetails ClassContext [Id] [ClassOpItem] DataCon
171 %************************************************************************
173 \subsection{Basic lookups}
175 %************************************************************************
178 lookup_global :: TcEnv -> Name -> Maybe TyThing
179 lookup_global env name
180 = -- Try the global envt
181 case lookupNameEnv (tcGEnv env) name of {
182 Just thing -> Just thing ;
185 -- Try the global symbol table
186 case lookupModuleEnv (tcGST env) of {
188 Just genv -> lookupNameEnv genv name
191 lookup_local :: TcEnv -> Name -> Maybe TcTyThing
192 lookup_local env name
193 = case lookupNameEnv (tcLEnv env) name of
194 Just thing -> Just thing ;
195 Nothing -> case lookup_global env name of
196 Just thing -> AGlobal thing
201 %************************************************************************
205 %************************************************************************
209 type TcId = Id -- Type may be a TcType
212 -- A useful function that takes an occurrence of a global thing
213 -- and instantiates its type with fresh type variables
215 -> NF_TcM ([TcTyVar], -- It's instantiated type
220 (tyvars, rho) = splitForAllTys (idType id)
222 tcInstTyVars tyvars `thenNF_Tc` \ (tyvars', arg_tys, tenv) ->
224 rho' = substTy tenv rho
225 (theta', tau') = splitRhoTy rho'
227 returnNF_Tc (tyvars', theta', tau')
231 %************************************************************************
233 \subsection{The global environment}
235 %************************************************************************
238 tcExtendGlobalEnv :: [(Name, TyThing)] -> TcM r -> TcM r
239 tcExtendGlobalEnv bindings thing_inside
240 = tcGetEnv `thenNF_Tc` \ env ->
242 ge' = extendNameEnvList (tcGEnv env) bindings
244 tcSetEnv (env {tcGEnv = ge'}) thing_inside
246 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
247 tcExtendGlobalValEnv ids thing_inside
248 = tcExtendGlobalEnv [(getName id, AnId id) | id <- ids] thing_inside
253 tcLookupGlobal_maybe :: Name -> NF_TcM (Maybe TyThing)
254 tcLookupGlobal_maybe name
255 = tcGetEnv `thenNF_Tc` \ env ->
256 returnNF_Tc (lookup_global env name)
259 A variety of global lookups, when we know what we are looking for.
262 tcLookupGlobal :: Name -> NF_TcM TyThing
263 = tcLookupGlobal_maybe name `thenNF_Tc` \ maybe_thing ->
265 Just thing -> returnNF_Tc thing
266 other -> notFound "tcLookupGlobal:" name
268 tcLookupGlobalId :: Name -> NF_TcM Id
269 tcLookupGlobalId name
270 = tcLookupGlobal_maybe name `thenNF_Tc` \ maybe_id ->
272 Just (AnId clas) -> returnNF_Tc id
273 other -> notFound "tcLookupGlobalId:" name
275 tcLookupDataCon :: Name -> TcM DataCon
276 tcLookupDataCon con_name
277 = tcLookupGlobalId con_name `thenNF_Tc` \ con_id ->
278 case isDataConWrapId_maybe con_id of {
279 Just data_con -> returnTc data_con
280 Nothing -> failWithTc (badCon con_id);
283 tcLookupClass :: Name -> NF_TcM Class
285 = tcLookupGlobal_maybe name `thenNF_Tc` \ maybe_clas ->
287 Just (AClass clas) -> returnNF_Tc clas
288 other -> notFound "tcLookupClass:" name
290 tcLookupTyCon :: Name -> NF_TcM TyCon
292 = tcLookupGlobal_maybe name `thenNF_Tc` \ maybe_tc ->
294 Just (ATyCon tc) -> returnNF_Tc tc
295 other -> notFound "tcLookupTyCon:" name
299 %************************************************************************
301 \subsection{The local environment}
303 %************************************************************************
306 tcExtendKindEnv :: [(Name,TcKind)] -> TcM r -> TcM r
307 tcExtendKindEnv pairs thing_inside
308 = tcGetEnv `thenNF_Tc` \ env ->
310 le' = extendNameEnvList (tcLEnv env) [(n, AThing k) | (n,k) <- pairs]
311 -- No need to extend global tyvars for kind checking
313 tcSetEnv (env {tcLEnv = le'}) thing_inside
315 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
316 tcExtendTyVarEnv tyvars thing_inside
317 = tcGetEnv `thenNF_Tc` \ env@(TcEnv {tcLEnv = le, tcTyVars = (in_scope_tvs, gtvs)}) ->
319 le' = extendNameEnvList le [ (getName tv, ATyVar tv) | tv <- tyvars]
320 new_tv_set = mkVarSet tyvars
322 -- It's important to add the in-scope tyvars to the global tyvar set
324 -- f (x::r) = let g y = y::r in ...
325 -- Here, g mustn't be generalised. This is also important during
326 -- class and instance decls, when we mustn't generalise the class tyvars
327 -- when typechecking the methods.
328 tc_extend_gtvs gtvs new_tv_set `thenNF_Tc` \ gtvs' ->
329 tcSetEnv (env {tcLEnv = le', tcTyVars = gtvs'}) thing_inside
331 -- This variant, tcExtendTyVarEnvForMeths, takes *two* bunches of tyvars:
332 -- the signature tyvars contain the original names
333 -- the instance tyvars are what those names should be mapped to
334 -- It's needed when typechecking the method bindings of class and instance decls
335 -- It does *not* extend the global tyvars; tcMethodBind does that for itself
337 tcExtendTyVarEnvForMeths :: [TyVar] -> [TcTyVar] -> TcM r -> TcM r
338 tcExtendTyVarEnvForMeths sig_tyvars inst_tyvars thing_inside
339 = tcGetEnv `thenNF_Tc` \ env ->
341 le' = extendNameEnvList (tcLEnv env) stuff
342 stuff = [ (getName sig_tv, ATyVar inst_tv)
343 | (sig_tv, inst_tv) <- zipEqual "tcMeth" sig_tyvars inst_tyvars
346 tcSetEnv (env {tcLEnv = le'}) thing_inside
351 tcExtendLocalValEnv :: [(Name,TcId)] -> TcM a -> TcM a
352 tcExtendLocalValEnv names_w_ids thing_inside
353 = tcGetEnv `thenNF_Tc` \ env ->
355 extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
356 extra_env = [(name, ATcId id) | (name,id) <- names_w_ids]
357 le' = extendNameEnvList (tcLEnv env) extra_env
359 tc_extend_gtvs (tcTyVars env) extra_global_tyvars `thenNF_Tc` \ gtvs' ->
360 tcSetEnv (env {tcLEnv = le', tcTyVars = gtvs'}) thing_inside
364 %************************************************************************
366 \subsection{The global tyvars}
368 %************************************************************************
371 tcExtendGlobalTyVars extra_global_tvs thing_inside
372 = tcGetEnv `thenNF_Tc` \ env ->
373 tc_extend_gtvs (tcTyVars env) extra_global_tvs `thenNF_Tc` \ gtvs' ->
374 tcSetEnv (env {tcTyVars = gtvs') thing_inside
376 tc_extend_gtvs gtvs extra_global_tvs
377 = tcReadMutVar gtvs `thenNF_Tc` \ global_tvs ->
378 tcNewMutVar (global_tvs `unionVarSet` extra_global_tvs)
381 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
382 To improve subsequent calls to the same function it writes the zonked set back into
386 tcGetGlobalTyVars :: NF_TcM TcTyVarSet
388 = tcGetEnv `thenNF_Tc` \ (TcEnv {tcTyVars = gtv_var}) ->
389 tcReadMutVar gtv_var `thenNF_Tc` \ global_tvs ->
390 zonkTcTyVars (varSetElems global_tvs) `thenNF_Tc` \ global_tys' ->
392 global_tvs' = (tyVarsOfTypes global_tys')
394 tcWriteMutVar gtv_var global_tvs' `thenNF_Tc_`
395 returnNF_Tc global_tvs'
399 %************************************************************************
401 \subsection{The local environment}
403 %************************************************************************
406 tcLookup_maybe :: Name -> NF_TcM (Maybe TcTyThing)
408 = tcGetEnv `thenNF_Tc` \ env ->
409 returnNF_Tc (lookup_local env name)
411 tcLookup :: Name -> NF_TcM TcTyThing
413 = tcLookup_maybe name `thenNF_Tc` \ maybe_thing ->
415 Just thing -> returnNF_Tc thing
416 other -> notFound "tcLookup:" name
420 tcGetValueEnv :: NF_TcM ValueEnv
422 = tcGetEnv `thenNF_Tc` \ (TcEnv ue te ve ie gtvs) ->
426 tcSetValueEnv :: ValueEnv -> TcM a -> TcM a
427 tcSetValueEnv ve thing_inside
428 = tcGetEnv `thenNF_Tc` \ (TcEnv ue te _ ie gtvs) ->
429 tcSetEnv (TcEnv ue te ve ie gtvs) thing_inside
431 explicitLookupValue :: ValueEnv -> Name -> Maybe Id
432 explicitLookupValue ve name
433 = case maybeWiredInIdName name of
435 Nothing -> lookupNameEnv ve name
437 -- Extract the IdInfo from an IfaceSig imported from an interface file
438 tcAddImportedIdInfo :: ValueEnv -> Id -> Id
439 tcAddImportedIdInfo unf_env id
440 | isLocallyDefined id -- Don't look up locally defined Ids, because they
441 -- have explicit local definitions, so we get a black hole!
444 = id `lazySetIdInfo` new_info
445 -- The Id must be returned without a data dependency on maybe_id
447 new_info = case explicitLookupValue unf_env (getName id) of
448 Nothing -> vanillaIdInfo
449 Just imported_id -> idInfo imported_id
450 -- ToDo: could check that types are the same
454 %************************************************************************
456 \subsection{The instance environment}
458 %************************************************************************
463 newLocalId :: OccName -> TcType -> SrcLoc -> NF_TcM TcId
464 newLocalId name ty loc
465 = tcGetUnique `thenNF_Tc` \ uniq ->
466 returnNF_Tc (mkUserLocal name uniq ty loc)
468 newSpecPragmaId :: Name -> TcType -> NF_TcM TcId
469 newSpecPragmaId name ty
470 = tcGetUnique `thenNF_Tc` \ uniq ->
471 returnNF_Tc (mkSpecPragmaId (nameOccName name) uniq ty (getSrcLoc name))
474 Make a name for the dict fun for an instance decl
477 newDFunName :: Module -> Class -> [Type] -> SrcLoc -> NF_TcM Name
478 newDFunName mod clas (ty:_) loc
479 = tcGetDFunUniq dfun_string `thenNF_Tc` \ inst_uniq ->
480 tcGetUnique `thenNF_Tc` \ uniq ->
481 returnNF_Tc (mkGlobalName uniq mod
482 (mkDFunOcc dfun_string inst_uniq)
483 (LocalDef loc Exported))
485 -- Any string that is somewhat unique will do
486 dfun_string = occNameString (getOccName clas) ++ occNameString (getDFunTyKey ty)
488 newDefaultMethodName :: Name -> SrcLoc -> NF_TcM Name
489 newDefaultMethodName op_name loc
490 = tcGetUnique `thenNF_Tc` \ uniq ->
491 returnNF_Tc (mkGlobalName uniq (nameModule op_name)
492 (mkDefaultMethodOcc (getOccName op_name))
493 (LocalDef loc Exported))
497 %************************************************************************
499 \subsection{The instance environment}
501 %************************************************************************
504 tcGetInstEnv :: NF_TcM InstEnv
505 tcGetInstEnv = tcGetEnv `thenNF_Tc` \ (TcEnv ue te ve ie (_,gtvs)) ->
508 tcSetInstEnv :: InstEnv -> TcM a -> TcM a
509 tcSetInstEnv ie thing_inside
510 = tcGetEnv `thenNF_Tc` \ (TcEnv ue te ve _ gtvs) ->
511 tcSetEnv (TcEnv ue te ve ie gtvs) thing_inside
516 type InstEnv = UniqFM ClsInstEnv -- Maps Class to instances for that class
517 type ClsInstEnv = [(TyVarSet, [Type], Id)] -- The instances for a particular class
519 classInstEnv :: InstEnv -> Class -> ClsInstEnv
520 classInstEnv env cls = lookupWithDefaultUFM env [] cls
523 A @ClsInstEnv@ lives inside a class, and identifies all the instances
524 of that class. The @Id@ inside a ClsInstEnv mapping is the dfun for
527 If class C maps to a list containing the item ([a,b], [t1,t2,t3], dfun), then
529 forall a b, C t1 t2 t3 can be constructed by dfun
531 or, to put it another way, we have
533 instance (...) => C t1 t2 t3, witnessed by dfun
535 There is an important consistency constraint in the elements of a ClsInstEnv:
537 * [a,b] must be a superset of the free vars of [t1,t2,t3]
539 * The dfun must itself be quantified over [a,b]
541 Thus, the @ClassInstEnv@ for @Eq@ might contain the following entry:
542 [a] ===> dfun_Eq_List :: forall a. Eq a => Eq [a]
543 The "a" in the pattern must be one of the forall'd variables in
548 Notes on overlapping instances
549 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
550 In some ClsInstEnvs, overlap is prohibited; that is, no pair of templates unify.
552 In others, overlap is permitted, but only in such a way that one can make
553 a unique choice when looking up. That is, overlap is only permitted if
554 one template matches the other, or vice versa. So this is ok:
562 If overlap is permitted, the list is kept most specific first, so that
563 the first lookup is the right choice.
566 For now we just use association lists.
568 \subsection{Avoiding a problem with overlapping}
570 Consider this little program:
573 class C a where c :: a
574 class C a => D a where d :: a
576 instance C Int where c = 17
577 instance D Int where d = 13
579 instance C a => C [a] where c = [c]
580 instance ({- C [a], -} D a) => D [a] where d = c
582 instance C [Int] where c = [37]
584 main = print (d :: [Int])
587 What do you think `main' prints (assuming we have overlapping instances, and
588 all that turned on)? Well, the instance for `D' at type `[a]' is defined to
589 be `c' at the same type, and we've got an instance of `C' at `[Int]', so the
590 answer is `[37]', right? (the generic `C [a]' instance shouldn't apply because
591 the `C [Int]' instance is more specific).
593 Ghc-4.04 gives `[37]', while ghc-4.06 gives `[17]', so 4.06 is wrong. That
594 was easy ;-) Let's just consult hugs for good measure. Wait - if I use old
595 hugs (pre-September99), I get `[17]', and stranger yet, if I use hugs98, it
596 doesn't even compile! What's going on!?
598 What hugs complains about is the `D [a]' instance decl.
601 ERROR "mj.hs" (line 10): Cannot build superclass instance
603 *** Context supplied : D a
604 *** Required superclass : C [a]
607 You might wonder what hugs is complaining about. It's saying that you
608 need to add `C [a]' to the context of the `D [a]' instance (as appears
609 in comments). But there's that `C [a]' instance decl one line above
610 that says that I can reduce the need for a `C [a]' instance to the
611 need for a `C a' instance, and in this case, I already have the
612 necessary `C a' instance (since we have `D a' explicitly in the
613 context, and `C' is a superclass of `D').
615 Unfortunately, the above reasoning indicates a premature commitment to the
616 generic `C [a]' instance. I.e., it prematurely rules out the more specific
617 instance `C [Int]'. This is the mistake that ghc-4.06 makes. The fix is to
618 add the context that hugs suggests (uncomment the `C [a]'), effectively
619 deferring the decision about which instance to use.
621 Now, interestingly enough, 4.04 has this same bug, but it's covered up
622 in this case by a little known `optimization' that was disabled in
623 4.06. Ghc-4.04 silently inserts any missing superclass context into
624 an instance declaration. In this case, it silently inserts the `C
625 [a]', and everything happens to work out.
627 (See `basicTypes/MkId:mkDictFunId' for the code in question. Search for
628 `Mark Jones', although Mark claims no credit for the `optimization' in
629 question, and would rather it stopped being called the `Mark Jones
632 So, what's the fix? I think hugs has it right. Here's why. Let's try
633 something else out with ghc-4.04. Let's add the following line:
638 Everyone raise their hand who thinks that `d :: [Int]' should give a
639 different answer from `d' :: [Int]'. Well, in ghc-4.04, it does. The
640 `optimization' only applies to instance decls, not to regular
641 bindings, giving inconsistent behavior.
643 Old hugs had this same bug. Here's how we fixed it: like GHC, the
644 list of instances for a given class is ordered, so that more specific
645 instances come before more generic ones. For example, the instance
646 list for C might contain:
647 ..., C Int, ..., C a, ...
648 When we go to look for a `C Int' instance we'll get that one first.
649 But what if we go looking for a `C b' (`b' is unconstrained)? We'll
650 pass the `C Int' instance, and keep going. But if `b' is
651 unconstrained, then we don't know yet if the more specific instance
652 will eventually apply. GHC keeps going, and matches on the generic `C
653 a'. The fix is to, at each step, check to see if there's a reverse
654 match, and if so, abort the search. This prevents hugs from
655 prematurely chosing a generic instance when a more specific one
661 emptyInstEnv :: InstEnv
662 emptyInstEnv = emptyUFM
665 @lookupInstEnv@ looks up in a @InstEnv@, using a one-way match. Since
666 the env is kept ordered, the first match must be the only one. The
667 thing we are looking up can have an arbitrary "flexi" part.
670 lookupInstEnv :: InstEnv -- The envt
671 -> Class -> [Type] -- Key
674 data InstLookupResult
675 = FoundInst -- There is a (template,substitution) pair
676 -- that makes the template match the key,
677 -- and no template is an instance of the key
680 | NoMatch Bool -- Boolean is true iff there is at least one
681 -- template that matches the key.
682 -- (but there are other template(s) that are
683 -- instances of the key, so we don't report
685 -- The NoMatch True case happens when we look up
687 -- in an InstEnv that has entries for
690 -- Then which we choose would depend on the way in which 'a'
691 -- is instantiated. So we say there is no match, but identify
692 -- it as ambiguous case in the hope of giving a better error msg.
693 -- See the notes above from Jeff Lewis
695 lookupInstEnv env key_cls key_tys
696 = find (classInstEnv env key_cls)
698 key_vars = tyVarsOfTypes key_tys
700 find [] = NoMatch False
701 find ((tpl_tyvars, tpl, val) : rest)
702 = case matchTys tpl_tyvars tpl key_tys of
704 case matchTys key_vars key_tys tpl of
706 Just (_, _) -> NoMatch (any_match rest)
707 Just (subst, leftovers) -> ASSERT( null leftovers )
710 any_match rest = or [ maybeToBool (matchTys tvs tpl key_tys)
711 | (tvs,tpl,_) <- rest
715 @addToClsInstEnv@ extends a @ClsInstEnv@, checking for overlaps.
717 A boolean flag controls overlap reporting.
719 True => overlap is permitted, but only if one template matches the other;
720 not if they unify but neither is
723 addToInstEnv :: Bool -- True <=> overlap permitted
725 -> Class -> [TyVar] -> [Type] -> Id -- New item
726 -> MaybeErr InstEnv -- Success...
727 ([Type], Id) -- Failure: Offending overlap
729 addToInstEnv overlap_ok inst_env clas ins_tvs ins_tys value
730 = case insert_into (classInstEnv inst_env clas) of
731 Failed stuff -> Failed stuff
732 Succeeded new_env -> Succeeded (addToUFM inst_env clas new_env)
735 ins_tv_set = mkVarSet ins_tvs
736 ins_item = (ins_tv_set, ins_tys, value)
738 insert_into [] = returnMaB [ins_item]
739 insert_into env@(cur_item@(tpl_tvs, tpl_tys, val) : rest)
742 -- (a) they are the same, or
743 -- (b) they unify, and any sort of overlap is prohibited,
744 -- (c) they unify but neither is more specific than t'other
746 || (unifiable && not overlap_ok)
747 || (unifiable && not (ins_item_more_specific || cur_item_more_specific))
748 = failMaB (tpl_tys, val)
750 -- New item is an instance of current item, so drop it here
751 | ins_item_more_specific = returnMaB (ins_item : env)
753 -- Otherwise carry on
754 | otherwise = insert_into rest `thenMaB` \ rest' ->
755 returnMaB (cur_item : rest')
757 unifiable = maybeToBool (unifyTyListsX (ins_tv_set `unionVarSet` tpl_tvs) tpl_tys ins_tys)
758 ins_item_more_specific = maybeToBool (matchTys tpl_tvs tpl_tys ins_tys)
759 cur_item_more_specific = maybeToBool (matchTys ins_tv_set ins_tys tpl_tys)
760 identical = ins_item_more_specific && cur_item_more_specific
764 %************************************************************************
768 %************************************************************************
771 badCon con_id = quotes (ppr con_id) <+> ptext SLIT("is not a data constructor")
772 badPrimOp op = quotes (ppr op) <+> ptext SLIT("is not a primop")
775 = failWithTc (text where <> colon <+> quotes (ppr name) <+> ptext SLIT("is not in scope"))