2 -- Type definitions for the constraint solver
5 -- Canonical constraints
6 CanonicalCts, emptyCCan, andCCan, andCCans,
7 singleCCan, extendCCans, isEmptyCCan,
8 CanonicalCt(..), Xi, tyVarsOfCanonical, tyVarsOfCanonicals,
9 mkWantedConstraints, deCanonicaliseWanted,
10 makeGivens, makeSolved,
12 CtFlavor (..), isWanted, isGiven, isDerived, canRewrite,
13 joinFlavors, mkGivenFlavor,
15 TcS, runTcS, failTcS, panicTcS, traceTcS, traceTcS0, -- Basic functionality
16 tryTcS, nestImplicTcS, wrapErrTcS, wrapWarnTcS,
17 SimplContext(..), isInteractive, simplEqsOnly, performDefaulting,
19 -- Creation of evidence variables
21 newWantedCoVar, newGivOrDerCoVar, newGivOrDerEvVar,
22 newIPVar, newDictVar, newKindConstraint,
24 -- Setting evidence variables
25 setWantedCoBind, setDerivedCoBind,
26 setIPBind, setDictBind, setEvBind,
32 getInstEnvs, getFamInstEnvs, -- Getting the environments
33 getTopEnv, getGblEnv, getTcEvBinds, getUntouchablesTcS,
34 getTcEvBindsBag, getTcSContext,
37 newFlattenSkolemTy, -- Flatten skolems
39 instDFunTypes, -- Instantiation
46 getDefaultInfo, getDynFlags,
48 matchClass, matchFam, MatchInstResult (..),
51 pprEq, -- Smaller utils, re-exported from TcM
52 -- TODO (DV): these are only really used in the
53 -- instance matcher in TcSimplify. I am wondering
54 -- if the whole instance matcher simply belongs
58 mkWantedFunDepEqns -- Instantiation of 'Equations' from FunDeps
62 #include "HsVersions.h"
74 import NameSet ( addOneToNameSet )
76 import qualified TcRnMonad as TcM
77 import qualified TcMType as TcM
78 import qualified TcEnv as TcM
79 ( checkWellStaged, topIdLvl, tcLookupFamInst, tcGetDefaultTys )
95 import HsBinds -- for TcEvBinds stuff
104 %************************************************************************
106 %* Canonical constraints *
108 %* These are the constraints the low-level simplifier works with *
110 %************************************************************************
113 -- Types without any type functions inside. However, note that xi
114 -- types CAN contain unexpanded type synonyms; however, the
115 -- (transitive) expansions of those type synonyms will not contain any
117 type Xi = Type -- In many comments, "xi" ranges over Xi
119 type CanonicalCts = Bag CanonicalCt
122 -- Atomic canonical constraints
123 = CDictCan { -- e.g. Num xi
125 cc_flavor :: CtFlavor,
130 | CIPCan { -- ?x::tau
131 -- See note [Canonical implicit parameter constraints].
133 cc_flavor :: CtFlavor,
134 cc_ip_nm :: IPName Name,
135 cc_ip_ty :: TcTauType
138 | CTyEqCan { -- tv ~ xi (recall xi means function free)
140 -- * tv not in tvs(xi) (occurs check)
141 -- * If tv is a MetaTyVar, then typeKind xi <: typeKind tv
142 -- a skolem, then typeKind xi = typeKind tv
144 cc_flavor :: CtFlavor,
149 | CFunEqCan { -- F xis ~ xi
150 -- Invariant: * isSynFamilyTyCon cc_fun
151 -- * cc_rhs is not a touchable unification variable
152 -- See Note [No touchables as FunEq RHS]
153 -- * typeKind (TyConApp cc_fun cc_tyargs) == typeKind cc_rhs
155 cc_flavor :: CtFlavor,
156 cc_fun :: TyCon, -- A type function
157 cc_tyargs :: [Xi], -- Either under-saturated or exactly saturated
158 cc_rhs :: Xi -- *never* over-saturated (because if so
159 -- we should have decomposed)
163 makeGivens :: CanonicalCts -> CanonicalCts
164 makeGivens = mapBag (\ct -> ct { cc_flavor = mkGivenFlavor (cc_flavor ct) UnkSkol })
165 -- The UnkSkol doesn't matter because these givens are
166 -- not contradictory (else we'd have rejected them already)
168 makeSolved :: CanonicalCt -> CanonicalCt
169 -- Record that a constraint is now solved
171 -- Given, Derived -> no-op
173 | Wanted loc <- cc_flavor ct = ct { cc_flavor = Derived loc }
176 mkWantedConstraints :: CanonicalCts -> Bag Implication -> WantedConstraints
177 mkWantedConstraints flats implics
178 = mapBag (WcEvVar . deCanonicaliseWanted) flats `unionBags` mapBag WcImplic implics
180 deCanonicaliseWanted :: CanonicalCt -> WantedEvVar
181 deCanonicaliseWanted ct
182 = WARN( not (isWanted $ cc_flavor ct), ppr ct )
183 let Wanted loc = cc_flavor ct
184 in WantedEvVar (cc_id ct) loc
186 tyVarsOfCanonical :: CanonicalCt -> TcTyVarSet
187 tyVarsOfCanonical (CTyEqCan { cc_tyvar = tv, cc_rhs = xi }) = extendVarSet (tyVarsOfType xi) tv
188 tyVarsOfCanonical (CFunEqCan { cc_tyargs = tys, cc_rhs = xi }) = tyVarsOfTypes (xi:tys)
189 tyVarsOfCanonical (CDictCan { cc_tyargs = tys }) = tyVarsOfTypes tys
190 tyVarsOfCanonical (CIPCan { cc_ip_ty = ty }) = tyVarsOfType ty
192 tyVarsOfCanonicals :: CanonicalCts -> TcTyVarSet
193 tyVarsOfCanonicals = foldrBag (unionVarSet . tyVarsOfCanonical) emptyVarSet
195 instance Outputable CanonicalCt where
196 ppr (CDictCan d fl cls tys)
197 = ppr fl <+> ppr d <+> dcolon <+> pprClassPred cls tys
198 ppr (CIPCan ip fl ip_nm ty)
199 = ppr fl <+> ppr ip <+> dcolon <+> parens (ppr ip_nm <> dcolon <> ppr ty)
200 ppr (CTyEqCan co fl tv ty)
201 = ppr fl <+> ppr co <+> dcolon <+> pprEqPred (mkTyVarTy tv, ty)
202 ppr (CFunEqCan co fl tc tys ty)
203 = ppr fl <+> ppr co <+> dcolon <+> pprEqPred (mkTyConApp tc tys, ty)
207 Note [No touchables as FunEq RHS]
208 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
209 Notice that (F xis ~ beta), where beta is an touchable unification
210 variable, is not canonical. Why?
211 * If (F xis ~ beta) was the only wanted constraint, we'd
212 definitely want to spontaneously-unify it
214 * But suppose we had an earlier wanted (beta ~ Int), and
215 have already spontaneously unified it. Then we have an
216 identity given (id : beta ~ Int) in the inert set.
218 * But (F xis ~ beta) does not react with that given (because we
219 don't subsitute on the RHS of a function equality). So there's a
220 serious danger that we'd spontaneously unify it a second time.
224 Note [Canonical implicit parameter constraints]
225 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
226 The type in a canonical implicit parameter constraint doesn't need to
227 be a xi (type-function-free type) since we can defer the flattening
228 until checking this type for equality with another type. If we
229 encounter two IP constraints with the same name, they MUST have the
230 same type, and at that point we can generate a flattened equality
231 constraint between the types. (On the other hand, the types in two
232 class constraints for the same class MAY be equal, so they need to be
233 flattened in the first place to facilitate comparing them.)
236 singleCCan :: CanonicalCt -> CanonicalCts
239 andCCan :: CanonicalCts -> CanonicalCts -> CanonicalCts
242 extendCCans :: CanonicalCts -> CanonicalCt -> CanonicalCts
243 extendCCans = snocBag
245 andCCans :: [CanonicalCts] -> CanonicalCts
246 andCCans = unionManyBags
248 emptyCCan :: CanonicalCts
251 isEmptyCCan :: CanonicalCts -> Bool
252 isEmptyCCan = isEmptyBag
255 %************************************************************************
258 The "flavor" of a canonical constraint
260 %************************************************************************
264 = Given GivenLoc -- We have evidence for this constraint in TcEvBinds
265 | Derived WantedLoc -- We have evidence for this constraint in TcEvBinds;
266 -- *however* this evidence can contain wanteds, so
267 -- it's valid only provisionally to the solution of
269 | Wanted WantedLoc -- We have no evidence bindings for this constraint.
271 instance Outputable CtFlavor where
272 ppr (Given _) = ptext (sLit "[Given]")
273 ppr (Wanted _) = ptext (sLit "[Wanted]")
274 ppr (Derived _) = ptext (sLit "[Derived]")
276 isWanted :: CtFlavor -> Bool
277 isWanted (Wanted {}) = True
280 isGiven :: CtFlavor -> Bool
281 isGiven (Given {}) = True
284 isDerived :: CtFlavor -> Bool
285 isDerived ctid = not $ isGiven ctid || isWanted ctid
287 canRewrite :: CtFlavor -> CtFlavor -> Bool
288 -- canRewrite ctid1 ctid2
289 -- The constraint ctid1 can be used to rewrite ctid2
290 canRewrite (Given {}) _ = True
291 canRewrite (Derived {}) (Wanted {}) = True
292 canRewrite (Derived {}) (Derived {}) = True
293 canRewrite (Wanted {}) (Wanted {}) = True
294 canRewrite _ _ = False
296 joinFlavors :: CtFlavor -> CtFlavor -> CtFlavor
297 joinFlavors (Wanted loc) _ = Wanted loc
298 joinFlavors _ (Wanted loc) = Wanted loc
299 joinFlavors (Derived loc) _ = Derived loc
300 joinFlavors _ (Derived loc) = Derived loc
301 joinFlavors (Given loc) _ = Given loc
303 mkGivenFlavor :: CtFlavor -> SkolemInfo -> CtFlavor
304 mkGivenFlavor (Wanted loc) sk = Given (setCtLocOrigin loc sk)
305 mkGivenFlavor (Derived loc) sk = Given (setCtLocOrigin loc sk)
306 mkGivenFlavor (Given loc) sk = Given (setCtLocOrigin loc sk)
310 %************************************************************************
312 %* The TcS solver monad *
314 %************************************************************************
318 The TcS monad is a weak form of the main Tc monad
322 * allocate new variables
323 * fill in evidence variables
325 Filling in a dictionary evidence variable means to create a binding
326 for it, so TcS carries a mutable location where the binding can be
327 added. This is initialised from the innermost implication constraint.
332 tcs_ev_binds :: EvBindsVar,
335 tcs_ty_binds :: IORef (Bag (TcTyVar, TcType)),
336 -- Global type bindings
338 tcs_context :: SimplContext
342 = SimplInfer -- Inferring type of a let-bound thing
343 | SimplRuleLhs -- Inferring type of a RULE lhs
344 | SimplInteractive -- Inferring type at GHCi prompt
345 | SimplCheck -- Checking a type signature or RULE rhs
347 instance Outputable SimplContext where
348 ppr SimplInfer = ptext (sLit "SimplInfer")
349 ppr SimplRuleLhs = ptext (sLit "SimplRuleLhs")
350 ppr SimplInteractive = ptext (sLit "SimplInteractive")
351 ppr SimplCheck = ptext (sLit "SimplCheck")
353 isInteractive :: SimplContext -> Bool
354 isInteractive SimplInteractive = True
355 isInteractive _ = False
357 simplEqsOnly :: SimplContext -> Bool
358 -- Simplify equalities only, not dictionaries
359 -- This is used for the LHS of rules; ee
360 -- Note [Simplifying RULE lhs constraints] in TcSimplify
361 simplEqsOnly SimplRuleLhs = True
362 simplEqsOnly _ = False
364 performDefaulting :: SimplContext -> Bool
365 performDefaulting SimplInfer = False
366 performDefaulting SimplRuleLhs = False
367 performDefaulting SimplInteractive = True
368 performDefaulting SimplCheck = True
371 newtype TcS a = TcS { unTcS :: TcSEnv -> TcM a }
373 instance Functor TcS where
374 fmap f m = TcS $ fmap f . unTcS m
376 instance Monad TcS where
377 return x = TcS (\_ -> return x)
378 fail err = TcS (\_ -> fail err)
379 m >>= k = TcS (\ebs -> unTcS m ebs >>= \r -> unTcS (k r) ebs)
381 -- Basic functionality
382 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
383 wrapTcS :: TcM a -> TcS a
384 -- Do not export wrapTcS, because it promotes an arbitrary TcM to TcS,
385 -- and TcS is supposed to have limited functionality
386 wrapTcS = TcS . const -- a TcM action will not use the TcEvBinds
388 wrapErrTcS :: TcM a -> TcS a
389 -- The thing wrapped should just fail
390 -- There's no static check; it's up to the user
391 -- Having a variant for each error message is too painful
394 wrapWarnTcS :: TcM a -> TcS a
395 -- The thing wrapped should just add a warning, or no-op
396 -- There's no static check; it's up to the user
397 wrapWarnTcS = wrapTcS
399 failTcS, panicTcS :: SDoc -> TcS a
400 failTcS = wrapTcS . TcM.failWith
401 panicTcS doc = pprPanic "TcCanonical" doc
403 traceTcS :: String -> SDoc -> TcS ()
404 traceTcS herald doc = TcS $ \_env -> TcM.traceTc herald doc
406 traceTcS0 :: String -> SDoc -> TcS ()
407 traceTcS0 herald doc = TcS $ \_env -> TcM.traceTcN 0 herald doc
409 runTcS :: SimplContext
410 -> TcTyVarSet -- Untouchables
411 -> TcS a -- What to run
412 -> TcM (a, Bag EvBind)
413 runTcS context untouch tcs
414 = do { ty_binds_var <- TcM.newTcRef emptyBag
415 ; ev_binds_var@(EvBindsVar evb_ref _) <- TcM.newTcEvBinds
416 ; let env = TcSEnv { tcs_ev_binds = ev_binds_var
417 , tcs_ty_binds = ty_binds_var
418 , tcs_context = context }
420 -- Run the computation
421 ; res <- TcM.setUntouchables untouch (unTcS tcs env)
423 -- Perform the type unifications required
424 ; ty_binds <- TcM.readTcRef ty_binds_var
425 ; mapBagM_ do_unification ty_binds
428 ; ev_binds <- TcM.readTcRef evb_ref
429 ; return (res, evBindMapBinds ev_binds) }
431 do_unification (tv,ty) = TcM.writeMetaTyVar tv ty
433 nestImplicTcS :: EvBindsVar -> TcTyVarSet -> TcS a -> TcS a
434 nestImplicTcS ref untouch tcs
435 = TcS $ \ TcSEnv { tcs_ty_binds = ty_binds, tcs_context = ctxt } ->
437 nest_env = TcSEnv { tcs_ev_binds = ref
438 , tcs_ty_binds = ty_binds
439 , tcs_context = ctxtUnderImplic ctxt }
441 TcM.setUntouchables untouch (unTcS tcs nest_env)
443 ctxtUnderImplic :: SimplContext -> SimplContext
444 -- See Note [Simplifying RULE lhs constraints] in TcSimplify
445 ctxtUnderImplic SimplRuleLhs = SimplCheck
446 ctxtUnderImplic ctxt = ctxt
448 tryTcS :: TcTyVarSet -> TcS a -> TcS a
449 -- Like runTcS, but from within the TcS monad
450 -- Ignore all the evidence generated, and do not affect caller's evidence!
452 = TcS (\env -> do { ty_binds_var <- TcM.newTcRef emptyBag
453 ; ev_binds_var <- TcM.newTcEvBinds
454 ; let env1 = env { tcs_ev_binds = ev_binds_var
455 , tcs_ty_binds = ty_binds_var }
456 ; TcM.setUntouchables untch (unTcS tcs env1) })
459 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
461 getDynFlags :: TcS DynFlags
462 getDynFlags = wrapTcS TcM.getDOpts
464 getTcSContext :: TcS SimplContext
465 getTcSContext = TcS (return . tcs_context)
467 getTcEvBinds :: TcS EvBindsVar
468 getTcEvBinds = TcS (return . tcs_ev_binds)
470 getTcSTyBinds :: TcS (IORef (Bag (TcTyVar, TcType)))
471 getTcSTyBinds = TcS (return . tcs_ty_binds)
473 getTcEvBindsBag :: TcS EvBindMap
475 = do { EvBindsVar ev_ref _ <- getTcEvBinds
476 ; wrapTcS $ TcM.readTcRef ev_ref }
478 setWantedCoBind :: CoVar -> Coercion -> TcS ()
479 setWantedCoBind cv co
480 = setEvBind cv (EvCoercion co)
481 -- Was: wrapTcS $ TcM.writeWantedCoVar cv co
483 setDerivedCoBind :: CoVar -> Coercion -> TcS ()
484 setDerivedCoBind cv co
485 = setEvBind cv (EvCoercion co)
487 setWantedTyBind :: TcTyVar -> TcType -> TcS ()
488 -- Add a type binding
489 setWantedTyBind tv ty
490 = do { ref <- getTcSTyBinds
492 do { ty_binds <- TcM.readTcRef ref
493 ; TcM.writeTcRef ref (ty_binds `snocBag` (tv,ty)) } }
495 setIPBind :: EvVar -> EvTerm -> TcS ()
496 setIPBind = setEvBind
498 setDictBind :: EvVar -> EvTerm -> TcS ()
499 setDictBind = setEvBind
501 setEvBind :: EvVar -> EvTerm -> TcS ()
504 = do { tc_evbinds <- getTcEvBinds
505 ; wrapTcS (TcM.addTcEvBind tc_evbinds ev rhs) }
507 newTcEvBindsTcS :: TcS EvBindsVar
508 newTcEvBindsTcS = wrapTcS (TcM.newTcEvBinds)
510 warnTcS :: CtLoc orig -> Bool -> SDoc -> TcS ()
511 warnTcS loc warn_if doc
512 | warn_if = wrapTcS $ TcM.setCtLoc loc $ TcM.addWarnTc doc
513 | otherwise = return ()
515 getDefaultInfo :: TcS (SimplContext, [Type], (Bool, Bool))
517 = do { ctxt <- getTcSContext
518 ; (tys, flags) <- wrapTcS (TcM.tcGetDefaultTys (isInteractive ctxt))
519 ; return (ctxt, tys, flags) }
521 -- Just get some environments needed for instance looking up and matching
522 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
524 getInstEnvs :: TcS (InstEnv, InstEnv)
525 getInstEnvs = wrapTcS $ Inst.tcGetInstEnvs
527 getFamInstEnvs :: TcS (FamInstEnv, FamInstEnv)
528 getFamInstEnvs = wrapTcS $ FamInst.tcGetFamInstEnvs
530 getTopEnv :: TcS HscEnv
531 getTopEnv = wrapTcS $ TcM.getTopEnv
533 getGblEnv :: TcS TcGblEnv
534 getGblEnv = wrapTcS $ TcM.getGblEnv
536 getUntouchablesTcS :: TcS TcTyVarSet
537 getUntouchablesTcS = wrapTcS $ TcM.getUntouchables
539 -- Various smaller utilities [TODO, maybe will be absorbed in the instance matcher]
540 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
542 checkWellStagedDFun :: PredType -> DFunId -> WantedLoc -> TcS ()
543 checkWellStagedDFun pred dfun_id loc
544 = wrapTcS $ TcM.setCtLoc loc $
545 do { use_stage <- TcM.getStage
546 ; TcM.checkWellStaged pp_thing bind_lvl (thLevel use_stage) }
548 pp_thing = ptext (sLit "instance for") <+> quotes (ppr pred)
549 bind_lvl = TcM.topIdLvl dfun_id
551 pprEq :: TcType -> TcType -> SDoc
552 pprEq ty1 ty2 = pprPred $ mkEqPred (ty1,ty2)
554 isTouchableMetaTyVar :: TcTyVar -> TcS Bool
555 -- is touchable variable!
556 isTouchableMetaTyVar v
557 | isMetaTyVar v = wrapTcS $ do { untch <- TcM.isUntouchable v;
558 ; return (not untch) }
559 | otherwise = return False
563 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
565 newFlattenSkolemTy :: TcType -> TcS TcType
566 newFlattenSkolemTy ty = mkTyVarTy <$> newFlattenSkolemTyVar ty
567 where newFlattenSkolemTyVar :: TcType -> TcS TcTyVar
568 newFlattenSkolemTyVar ty
569 = wrapTcS $ do { uniq <- TcM.newUnique
570 ; let name = mkSysTvName uniq (fsLit "f")
571 ; return $ mkTcTyVar name (typeKind ty) (FlatSkol ty)
575 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
577 instDFunTypes :: [Either TyVar TcType] -> TcS [TcType]
578 instDFunTypes mb_inst_tys =
579 let inst_tv :: Either TyVar TcType -> TcS Type
580 inst_tv (Left tv) = wrapTcS $ TcM.tcInstTyVar tv >>= return . mkTyVarTy
581 inst_tv (Right ty) = return ty
582 in mapM inst_tv mb_inst_tys
585 instDFunConstraints :: TcThetaType -> TcS [EvVar]
586 instDFunConstraints preds = wrapTcS $ TcM.newWantedEvVars preds
589 -- Superclasses and recursive dictionaries
590 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
592 newGivOrDerEvVar :: TcPredType -> EvTerm -> TcS EvVar
593 newGivOrDerEvVar pty evtrm
594 = do { ev <- wrapTcS $ TcM.newEvVar pty
598 newGivOrDerCoVar :: TcType -> TcType -> Coercion -> TcS EvVar
599 -- Note we create immutable variables for given or derived, since we
600 -- must bind them to TcEvBinds (because their evidence may involve
601 -- superclasses). However we should be able to override existing
602 -- 'derived' evidence, even in TcEvBinds
603 newGivOrDerCoVar ty1 ty2 co
604 = do { cv <- newCoVar ty1 ty2
605 ; setEvBind cv (EvCoercion co)
608 newWantedCoVar :: TcType -> TcType -> TcS EvVar
609 newWantedCoVar ty1 ty2 = wrapTcS $ TcM.newWantedCoVar ty1 ty2
611 newKindConstraint :: TcType -> Kind -> TcS (CoVar, TcType)
612 newKindConstraint ty kind = wrapTcS $ TcM.newKindConstraint ty kind
614 newCoVar :: TcType -> TcType -> TcS EvVar
615 newCoVar ty1 ty2 = wrapTcS $ TcM.newCoVar ty1 ty2
617 newIPVar :: IPName Name -> TcType -> TcS EvVar
618 newIPVar nm ty = wrapTcS $ TcM.newIP nm ty
620 newDictVar :: Class -> [TcType] -> TcS EvVar
621 newDictVar cl tys = wrapTcS $ TcM.newDict cl tys
626 isGoodRecEv :: EvVar -> WantedEvVar -> TcS Bool
627 -- In a call (isGoodRecEv ev wv), we are considering solving wv
628 -- using some term that involves ev, such as:
629 -- by setting wv = ev
630 -- or wv = EvCast x |> ev
632 -- But that would be Very Bad if the evidence for 'ev' mentions 'wv',
633 -- in an "unguarded" way. So isGoodRecEv looks at the evidence ev
634 -- recursively through the evidence binds, to see if uses of 'wv' are guarded.
636 -- Guarded means: more instance calls than superclass selections. We
637 -- compute this by chasing the evidence, adding +1 for every instance
638 -- call (constructor) and -1 for every superclass selection (destructor).
640 -- See Note [Superclasses and recursive dictionaries] in TcInteract
641 isGoodRecEv ev_var (WantedEvVar wv _)
642 = do { tc_evbinds <- getTcEvBindsBag
643 ; mb <- chase_ev_var tc_evbinds wv 0 [] ev_var
644 ; return $ case mb of
646 Just min_guardedness -> min_guardedness > 0
649 where chase_ev_var :: EvBindMap -- Evidence binds
650 -> EvVar -- Target variable whose gravity we want to return
651 -> Int -- Current gravity
652 -> [EvVar] -- Visited nodes
653 -> EvVar -- Current node
655 chase_ev_var assocs trg curr_grav visited orig
656 | trg == orig = return $ Just curr_grav
657 | orig `elem` visited = return $ Nothing
658 | Just (EvBind _ ev_trm) <- lookupEvBind assocs orig
659 = chase_ev assocs trg curr_grav (orig:visited) ev_trm
661 {- No longer needed: evidence is in the EvBinds
662 | isTcTyVar orig && isMetaTyVar orig
663 = do { meta_details <- wrapTcS $ TcM.readWantedCoVar orig
664 ; case meta_details of
665 Flexi -> return Nothing
666 Indirect tyco -> chase_ev assocs trg curr_grav
667 (orig:visited) (EvCoercion tyco)
670 | otherwise = return Nothing
672 chase_ev assocs trg curr_grav visited (EvId v)
673 = chase_ev_var assocs trg curr_grav visited v
674 chase_ev assocs trg curr_grav visited (EvSuperClass d_id _)
675 = chase_ev_var assocs trg (curr_grav-1) visited d_id
676 chase_ev assocs trg curr_grav visited (EvCast v co)
677 = do { m1 <- chase_ev_var assocs trg curr_grav visited v
678 ; m2 <- chase_co assocs trg curr_grav visited co
679 ; return (comb_chase_res Nothing [m1,m2]) }
681 chase_ev assocs trg curr_grav visited (EvCoercion co)
682 = chase_co assocs trg curr_grav visited co
683 chase_ev assocs trg curr_grav visited (EvDFunApp _ _ ev_vars)
684 = do { chase_results <- mapM (chase_ev_var assocs trg (curr_grav+1) visited) ev_vars
685 ; return (comb_chase_res Nothing chase_results) }
687 chase_co assocs trg curr_grav visited co
688 = -- Look for all the coercion variables in the coercion
689 -- chase them, and combine the results. This is OK since the
690 -- coercion will not contain any superclass terms -- anything
691 -- that involves dictionaries will be bound in assocs.
692 let co_vars = foldVarSet (\v vrs -> if isCoVar v then (v:vrs) else vrs) []
694 in do { chase_results <- mapM (chase_ev_var assocs trg curr_grav visited) co_vars
695 ; return (comb_chase_res Nothing chase_results) }
697 comb_chase_res f [] = f
698 comb_chase_res f (Nothing:rest) = comb_chase_res f rest
699 comb_chase_res Nothing (Just n:rest) = comb_chase_res (Just n) rest
700 comb_chase_res (Just m) (Just n:rest) = comb_chase_res (Just (min n m)) rest
703 -- Matching and looking up classes and family instances
704 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
706 data MatchInstResult mi
707 = MatchInstNo -- No matching instance
708 | MatchInstSingle mi -- Single matching instance
709 | MatchInstMany -- Multiple matching instances
712 matchClass :: Class -> [Type] -> TcS (MatchInstResult (DFunId, [Either TyVar TcType]))
713 -- Look up a class constraint in the instance environment
715 = do { let pred = mkClassPred clas tys
716 ; instEnvs <- getInstEnvs
717 ; case lookupInstEnv instEnvs clas tys of {
718 ([], unifs) -- Nothing matches
719 -> do { traceTcS "matchClass not matching"
720 (vcat [ text "dict" <+> ppr pred,
721 text "unifs" <+> ppr unifs ])
724 ([(ispec, inst_tys)], []) -- A single match
725 -> do { let dfun_id = is_dfun ispec
726 ; traceTcS "matchClass success"
727 (vcat [text "dict" <+> ppr pred,
728 text "witness" <+> ppr dfun_id
729 <+> ppr (idType dfun_id) ])
730 -- Record that this dfun is needed
731 ; record_dfun_usage dfun_id
732 ; return $ MatchInstSingle (dfun_id, inst_tys)
734 (matches, unifs) -- More than one matches
735 -> do { traceTcS "matchClass multiple matches, deferring choice"
736 (vcat [text "dict" <+> ppr pred,
737 text "matches" <+> ppr matches,
738 text "unifs" <+> ppr unifs])
739 ; return MatchInstMany
743 where record_dfun_usage :: Id -> TcS ()
744 record_dfun_usage dfun_id
745 = do { hsc_env <- getTopEnv
746 ; let dfun_name = idName dfun_id
747 dfun_mod = ASSERT( isExternalName dfun_name )
749 ; if isInternalName dfun_name || -- Internal name => defined in this module
750 modulePackageId dfun_mod /= thisPackage (hsc_dflags hsc_env)
751 then return () -- internal, or in another package
752 else do updInstUses dfun_id
755 updInstUses :: Id -> TcS ()
757 = do { tcg_env <- getGblEnv
758 ; wrapTcS $ TcM.updMutVar (tcg_inst_uses tcg_env)
759 (`addOneToNameSet` idName dfun_id)
764 -> TcS (MatchInstResult (TyCon, [Type]))
766 = do { mb <- wrapTcS $ TcM.tcLookupFamInst tycon args
768 Nothing -> return MatchInstNo
769 Just res -> return $ MatchInstSingle res
770 -- DV: We never return MatchInstMany, since tcLookupFamInst never returns
771 -- multiple matches. Check.
775 -- Functional dependencies, instantiation of equations
776 -------------------------------------------------------
778 mkWantedFunDepEqns :: WantedLoc -> [(Equation, (PredType, SDoc), (PredType, SDoc))]
780 mkWantedFunDepEqns _ [] = return []
781 mkWantedFunDepEqns loc eqns
782 = do { traceTcS "Improve:" (vcat (map pprEquationDoc eqns))
783 ; wevvars <- mapM to_work_item eqns
784 ; return $ concat wevvars }
786 to_work_item :: (Equation, (PredType,SDoc), (PredType,SDoc)) -> TcS [WantedEvVar]
787 to_work_item ((qtvs, pairs), _, _)
788 = do { (_, _, tenv) <- wrapTcS $ TcM.tcInstTyVars (varSetElems qtvs)
789 ; mapM (do_one tenv) pairs }
791 do_one tenv (ty1, ty2) = do { let sty1 = substTy tenv ty1
792 sty2 = substTy tenv ty2
793 ; ev <- newWantedCoVar sty1 sty2
794 ; return (WantedEvVar ev loc) }
796 pprEquationDoc :: (Equation, (PredType, SDoc), (PredType, SDoc)) -> SDoc
797 pprEquationDoc (eqn, (p1, _), (p2, _))
798 = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]