2 -- Type definitions for the constraint solver
5 -- Canonical constraints
6 CanonicalCts, emptyCCan, andCCan, andCCans,
7 singleCCan, extendCCans, isEmptyCCan, isCTyEqCan,
8 isCDictCan_Maybe, isCIPCan_Maybe, isCFunEqCan_Maybe,
10 CanonicalCt(..), Xi, tyVarsOfCanonical, tyVarsOfCanonicals, tyVarsOfCDicts,
11 mkWantedConstraints, deCanonicaliseWanted,
12 makeGivens, makeSolvedByInst,
14 CtFlavor (..), isWanted, isGiven, isDerived,
15 isGivenCt, isWantedCt, pprFlavorArising,
21 combineCtLoc, mkGivenFlavor, mkWantedFlavor,
24 TcS, runTcS, failTcS, panicTcS, traceTcS, traceTcS0, -- Basic functionality
25 tryTcS, nestImplicTcS, recoverTcS, wrapErrTcS, wrapWarnTcS,
26 SimplContext(..), isInteractive, simplEqsOnly, performDefaulting,
28 -- Creation of evidence variables
30 newWantedCoVar, newGivOrDerCoVar, newGivOrDerEvVar,
31 newIPVar, newDictVar, newKindConstraint,
33 -- Setting evidence variables
34 setWantedCoBind, setDerivedCoBind,
35 setIPBind, setDictBind, setEvBind,
41 getInstEnvs, getFamInstEnvs, -- Getting the environments
42 getTopEnv, getGblEnv, getTcEvBinds, getUntouchables,
43 getTcEvBindsBag, getTcSContext, getTcSTyBinds, getTcSTyBindsMap, getTcSErrors,
44 getTcSErrorsBag, FrozenError (..),
48 newFlattenSkolemTy, -- Flatten skolems
51 instDFunTypes, -- Instantiation
62 isTouchableMetaTyVar_InRange,
64 getDefaultInfo, getDynFlags,
66 matchClass, matchFam, MatchInstResult (..),
69 pprEq, -- Smaller utils, re-exported from TcM
70 -- TODO (DV): these are only really used in the
71 -- instance matcher in TcSimplify. I am wondering
72 -- if the whole instance matcher simply belongs
76 mkWantedFunDepEqns -- Instantiation of 'Equations' from FunDeps
80 #include "HsVersions.h"
90 import NameSet ( addOneToNameSet )
92 import qualified TcRnMonad as TcM
93 import qualified TcMType as TcM
94 import qualified TcEnv as TcM
95 ( checkWellStaged, topIdLvl, tcLookupFamInst, tcGetDefaultTys )
114 import HsBinds -- for TcEvBinds stuff
125 %************************************************************************
127 %* Canonical constraints *
129 %* These are the constraints the low-level simplifier works with *
131 %************************************************************************
134 -- Types without any type functions inside. However, note that xi
135 -- types CAN contain unexpanded type synonyms; however, the
136 -- (transitive) expansions of those type synonyms will not contain any
138 type Xi = Type -- In many comments, "xi" ranges over Xi
140 type CanonicalCts = Bag CanonicalCt
143 -- Atomic canonical constraints
144 = CDictCan { -- e.g. Num xi
146 cc_flavor :: CtFlavor,
151 | CIPCan { -- ?x::tau
152 -- See note [Canonical implicit parameter constraints].
154 cc_flavor :: CtFlavor,
155 cc_ip_nm :: IPName Name,
156 cc_ip_ty :: TcTauType
159 | CTyEqCan { -- tv ~ xi (recall xi means function free)
161 -- * tv not in tvs(xi) (occurs check)
162 -- * If constraint is given then typeKind xi `compatKind` typeKind tv
163 -- See Note [Spontaneous solving and kind compatibility]
164 -- * We prefer unification variables on the left *JUST* for efficiency
166 cc_flavor :: CtFlavor,
171 | CFunEqCan { -- F xis ~ xi
172 -- Invariant: * isSynFamilyTyCon cc_fun
173 -- * If constraint is given then
174 -- typeKind (F xis) `compatKind` typeKind xi
176 cc_flavor :: CtFlavor,
177 cc_fun :: TyCon, -- A type function
178 cc_tyargs :: [Xi], -- Either under-saturated or exactly saturated
179 cc_rhs :: Xi -- *never* over-saturated (because if so
180 -- we should have decomposed)
184 compatKind :: Kind -> Kind -> Bool
185 compatKind k1 k2 = k1 `isSubKind` k2 || k2 `isSubKind` k1
187 makeGivens :: CanonicalCts -> CanonicalCts
188 makeGivens = mapBag (\ct -> ct { cc_flavor = mkGivenFlavor (cc_flavor ct) UnkSkol })
189 -- The UnkSkol doesn't matter because these givens are
190 -- not contradictory (else we'd have rejected them already)
192 makeSolvedByInst :: CanonicalCt -> CanonicalCt
193 -- Record that a constraint is now solved
195 -- Given, Derived -> no-op
197 | Wanted loc <- cc_flavor ct = ct { cc_flavor = Derived loc DerInst }
200 mkWantedConstraints :: CanonicalCts -> Bag Implication -> WantedConstraints
201 mkWantedConstraints flats implics
202 = mapBag (WcEvVar . deCanonicaliseWanted) flats `unionBags` mapBag WcImplic implics
204 deCanonicaliseWanted :: CanonicalCt -> WantedEvVar
205 deCanonicaliseWanted ct
206 = WARN( not (isWanted $ cc_flavor ct), ppr ct )
207 let Wanted loc = cc_flavor ct
208 in WantedEvVar (cc_id ct) loc
210 tyVarsOfCanonical :: CanonicalCt -> TcTyVarSet
211 tyVarsOfCanonical (CTyEqCan { cc_tyvar = tv, cc_rhs = xi }) = extendVarSet (tyVarsOfType xi) tv
212 tyVarsOfCanonical (CFunEqCan { cc_tyargs = tys, cc_rhs = xi }) = tyVarsOfTypes (xi:tys)
213 tyVarsOfCanonical (CDictCan { cc_tyargs = tys }) = tyVarsOfTypes tys
214 tyVarsOfCanonical (CIPCan { cc_ip_ty = ty }) = tyVarsOfType ty
216 tyVarsOfCDict :: CanonicalCt -> TcTyVarSet
217 tyVarsOfCDict (CDictCan { cc_tyargs = tys }) = tyVarsOfTypes tys
218 tyVarsOfCDict _ct = emptyVarSet
220 tyVarsOfCDicts :: CanonicalCts -> TcTyVarSet
221 tyVarsOfCDicts = foldrBag (unionVarSet . tyVarsOfCDict) emptyVarSet
223 tyVarsOfCanonicals :: CanonicalCts -> TcTyVarSet
224 tyVarsOfCanonicals = foldrBag (unionVarSet . tyVarsOfCanonical) emptyVarSet
226 instance Outputable CanonicalCt where
227 ppr (CDictCan d fl cls tys)
228 = ppr fl <+> ppr d <+> dcolon <+> pprClassPred cls tys
229 ppr (CIPCan ip fl ip_nm ty)
230 = ppr fl <+> ppr ip <+> dcolon <+> parens (ppr ip_nm <> dcolon <> ppr ty)
231 ppr (CTyEqCan co fl tv ty)
232 = ppr fl <+> ppr co <+> dcolon <+> pprEqPred (mkTyVarTy tv, ty)
233 ppr (CFunEqCan co fl tc tys ty)
234 = ppr fl <+> ppr co <+> dcolon <+> pprEqPred (mkTyConApp tc tys, ty)
237 Note [Canonical implicit parameter constraints]
238 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
239 The type in a canonical implicit parameter constraint doesn't need to
240 be a xi (type-function-free type) since we can defer the flattening
241 until checking this type for equality with another type. If we
242 encounter two IP constraints with the same name, they MUST have the
243 same type, and at that point we can generate a flattened equality
244 constraint between the types. (On the other hand, the types in two
245 class constraints for the same class MAY be equal, so they need to be
246 flattened in the first place to facilitate comparing them.)
249 singleCCan :: CanonicalCt -> CanonicalCts
252 andCCan :: CanonicalCts -> CanonicalCts -> CanonicalCts
255 extendCCans :: CanonicalCts -> CanonicalCt -> CanonicalCts
256 extendCCans = snocBag
258 andCCans :: [CanonicalCts] -> CanonicalCts
259 andCCans = unionManyBags
261 emptyCCan :: CanonicalCts
264 isEmptyCCan :: CanonicalCts -> Bool
265 isEmptyCCan = isEmptyBag
267 isCTyEqCan :: CanonicalCt -> Bool
268 isCTyEqCan (CTyEqCan {}) = True
269 isCTyEqCan (CFunEqCan {}) = False
272 isCDictCan_Maybe :: CanonicalCt -> Maybe Class
273 isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
274 isCDictCan_Maybe _ = Nothing
276 isCIPCan_Maybe :: CanonicalCt -> Maybe (IPName Name)
277 isCIPCan_Maybe (CIPCan {cc_ip_nm = nm }) = Just nm
278 isCIPCan_Maybe _ = Nothing
280 isCFunEqCan_Maybe :: CanonicalCt -> Maybe TyCon
281 isCFunEqCan_Maybe (CFunEqCan { cc_fun = tc }) = Just tc
282 isCFunEqCan_Maybe _ = Nothing
286 %************************************************************************
289 The "flavor" of a canonical constraint
291 %************************************************************************
295 = Given GivenLoc -- We have evidence for this constraint in TcEvBinds
296 | Derived WantedLoc DerivedOrig
297 -- We have evidence for this constraint in TcEvBinds;
298 -- *however* this evidence can contain wanteds, so
299 -- it's valid only provisionally to the solution of
301 | Wanted WantedLoc -- We have no evidence bindings for this constraint.
303 data DerivedOrig = DerSC | DerInst | DerSelf
304 -- Deriveds are either superclasses of other wanteds or deriveds, or partially
305 -- solved wanteds from instances, or 'self' dictionaries containing yet wanted
308 instance Outputable CtFlavor where
309 ppr (Given _) = ptext (sLit "[Given]")
310 ppr (Wanted _) = ptext (sLit "[Wanted]")
311 ppr (Derived {}) = ptext (sLit "[Derived]")
313 isWanted :: CtFlavor -> Bool
314 isWanted (Wanted {}) = True
317 isGiven :: CtFlavor -> Bool
318 isGiven (Given {}) = True
321 isDerived :: CtFlavor -> Bool
322 isDerived (Derived {}) = True
325 pprFlavorArising :: CtFlavor -> SDoc
326 pprFlavorArising (Derived wl _) = pprArisingAt wl
327 pprFlavorArising (Wanted wl) = pprArisingAt wl
328 pprFlavorArising (Given gl) = pprArisingAt gl
330 getWantedLoc :: CanonicalCt -> WantedLoc
332 = ASSERT (isWanted (cc_flavor ct))
335 _ -> pprPanic "Can't get WantedLoc of non-wanted constraint!" empty
338 isWantedCt :: CanonicalCt -> Bool
339 isWantedCt ct = isWanted (cc_flavor ct)
340 isGivenCt :: CanonicalCt -> Bool
341 isGivenCt ct = isGiven (cc_flavor ct)
343 canSolve :: CtFlavor -> CtFlavor -> Bool
344 -- canSolve ctid1 ctid2
345 -- The constraint ctid1 can be used to solve ctid2
346 -- "to solve" means a reaction where the active parts of the two constraints match.
347 -- active(F xis ~ xi) = F xis
348 -- active(tv ~ xi) = tv
349 -- active(D xis) = D xis
350 -- active(IP nm ty) = nm
351 -----------------------------------------
352 canSolve (Given {}) _ = True
353 canSolve (Derived {}) (Wanted {}) = True
354 canSolve (Derived {}) (Derived {}) = True
355 canSolve (Wanted {}) (Wanted {}) = True
358 canRewrite :: CtFlavor -> CtFlavor -> Bool
359 -- canRewrite ctid1 ctid2
360 -- The *equality_constraint* ctid1 can be used to rewrite inside ctid2
361 canRewrite = canSolve
363 combineCtLoc :: CtFlavor -> CtFlavor -> WantedLoc
364 -- Precondition: At least one of them should be wanted
365 combineCtLoc (Wanted loc) _ = loc
366 combineCtLoc _ (Wanted loc) = loc
367 combineCtLoc (Derived loc _) _ = loc
368 combineCtLoc _ (Derived loc _) = loc
369 combineCtLoc _ _ = panic "combineCtLoc: both given"
371 mkGivenFlavor :: CtFlavor -> SkolemInfo -> CtFlavor
372 mkGivenFlavor (Wanted loc) sk = Given (setCtLocOrigin loc sk)
373 mkGivenFlavor (Derived loc _) sk = Given (setCtLocOrigin loc sk)
374 mkGivenFlavor (Given loc) sk = Given (setCtLocOrigin loc sk)
376 mkWantedFlavor :: CtFlavor -> CtFlavor
377 mkWantedFlavor (Wanted loc) = Wanted loc
378 mkWantedFlavor (Derived loc _) = Wanted loc
379 mkWantedFlavor fl@(Given {}) = pprPanic "mkWantedFlavour" (ppr fl)
383 %************************************************************************
385 %* The TcS solver monad *
387 %************************************************************************
391 The TcS monad is a weak form of the main Tc monad
395 * allocate new variables
396 * fill in evidence variables
398 Filling in a dictionary evidence variable means to create a binding
399 for it, so TcS carries a mutable location where the binding can be
400 added. This is initialised from the innermost implication constraint.
405 tcs_ev_binds :: EvBindsVar,
408 tcs_ty_binds :: IORef (TyVarEnv (TcTyVar, TcType)),
409 -- Global type bindings
411 tcs_context :: SimplContext,
413 tcs_errors :: IORef (Bag FrozenError),
414 -- Frozen errors that we defer reporting as much as possible, in order to
415 -- make them as informative as possible. See Note [Frozen Errors]
417 tcs_untch :: TcsUntouchables
420 type TcsUntouchables = (Untouchables,TcTyVarSet)
421 -- Like the TcM Untouchables,
422 -- but records extra TcsTv variables generated during simplification
423 -- See Note [Extra TcsTv untouchables] in TcSimplify
426 = FrozenError ErrorKind CtFlavor TcType TcType
429 = MisMatchError | OccCheckError | KindError
431 instance Outputable FrozenError where
432 ppr (FrozenError _frknd fl ty1 ty2) = ppr fl <+> pprEq ty1 ty2 <+> text "(frozen)"
438 Some of the errors that we get during canonicalization are best reported when all constraints
439 have been simplified as much as possible. For instance, assume that during simplification
440 the following constraints arise:
442 [Wanted] F alpha ~ uf1
443 [Wanted] beta ~ uf1 beta
445 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail we will simply
447 'Can't construct the infinite type beta ~ uf1 beta'
448 and the user has no idea what the uf1 variable is.
450 Instead our plan is that we will NOT fail immediately, but:
451 (1) Record the "frozen" error in the tcs_errors field
452 (2) Isolate the offending constraint from the rest of the inerts
453 (3) Keep on simplifying/canonicalizing
455 At the end, we will hopefully have substituted uf1 := F alpha, and we will be able to
456 report a more informative error:
457 'Can't construct the infinite type beta ~ F alpha beta'
461 = SimplInfer -- Inferring type of a let-bound thing
462 | SimplRuleLhs -- Inferring type of a RULE lhs
463 | SimplInteractive -- Inferring type at GHCi prompt
464 | SimplCheck -- Checking a type signature or RULE rhs
466 instance Outputable SimplContext where
467 ppr SimplInfer = ptext (sLit "SimplInfer")
468 ppr SimplRuleLhs = ptext (sLit "SimplRuleLhs")
469 ppr SimplInteractive = ptext (sLit "SimplInteractive")
470 ppr SimplCheck = ptext (sLit "SimplCheck")
472 isInteractive :: SimplContext -> Bool
473 isInteractive SimplInteractive = True
474 isInteractive _ = False
476 simplEqsOnly :: SimplContext -> Bool
477 -- Simplify equalities only, not dictionaries
478 -- This is used for the LHS of rules; ee
479 -- Note [Simplifying RULE lhs constraints] in TcSimplify
480 simplEqsOnly SimplRuleLhs = True
481 simplEqsOnly _ = False
483 performDefaulting :: SimplContext -> Bool
484 performDefaulting SimplInfer = False
485 performDefaulting SimplRuleLhs = False
486 performDefaulting SimplInteractive = True
487 performDefaulting SimplCheck = True
490 newtype TcS a = TcS { unTcS :: TcSEnv -> TcM a }
492 instance Functor TcS where
493 fmap f m = TcS $ fmap f . unTcS m
495 instance Monad TcS where
496 return x = TcS (\_ -> return x)
497 fail err = TcS (\_ -> fail err)
498 m >>= k = TcS (\ebs -> unTcS m ebs >>= \r -> unTcS (k r) ebs)
500 -- Basic functionality
501 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 wrapTcS :: TcM a -> TcS a
503 -- Do not export wrapTcS, because it promotes an arbitrary TcM to TcS,
504 -- and TcS is supposed to have limited functionality
505 wrapTcS = TcS . const -- a TcM action will not use the TcEvBinds
507 wrapErrTcS :: TcM a -> TcS a
508 -- The thing wrapped should just fail
509 -- There's no static check; it's up to the user
510 -- Having a variant for each error message is too painful
513 wrapWarnTcS :: TcM a -> TcS a
514 -- The thing wrapped should just add a warning, or no-op
515 -- There's no static check; it's up to the user
516 wrapWarnTcS = wrapTcS
518 failTcS, panicTcS :: SDoc -> TcS a
519 failTcS = wrapTcS . TcM.failWith
520 panicTcS doc = pprPanic "TcCanonical" doc
522 traceTcS :: String -> SDoc -> TcS ()
523 traceTcS herald doc = TcS $ \_env -> TcM.traceTc herald doc
525 traceTcS0 :: String -> SDoc -> TcS ()
526 traceTcS0 herald doc = TcS $ \_env -> TcM.traceTcN 0 herald doc
528 runTcS :: SimplContext
529 -> Untouchables -- Untouchables
530 -> TcS a -- What to run
531 -> TcM (a, Bag FrozenError, Bag EvBind)
532 runTcS context untouch tcs
533 = do { ty_binds_var <- TcM.newTcRef emptyVarEnv
534 ; ev_binds_var@(EvBindsVar evb_ref _) <- TcM.newTcEvBinds
535 ; err_ref <- TcM.newTcRef emptyBag
536 ; let env = TcSEnv { tcs_ev_binds = ev_binds_var
537 , tcs_ty_binds = ty_binds_var
538 , tcs_context = context
539 , tcs_untch = (untouch, emptyVarSet) -- No Tcs untouchables yet
540 , tcs_errors = err_ref
543 -- Run the computation
544 ; res <- unTcS tcs env
545 -- Perform the type unifications required
546 ; ty_binds <- TcM.readTcRef ty_binds_var
547 ; mapM_ do_unification (varEnvElts ty_binds)
550 ; frozen_errors <- TcM.readTcRef err_ref
551 ; ev_binds <- TcM.readTcRef evb_ref
552 ; return (res, frozen_errors, evBindMapBinds ev_binds) }
554 do_unification (tv,ty) = TcM.writeMetaTyVar tv ty
556 nestImplicTcS :: EvBindsVar -> TcsUntouchables -> TcS a -> TcS a
557 nestImplicTcS ref untch (TcS thing_inside)
558 = TcS $ \ TcSEnv { tcs_ty_binds = ty_binds,
560 tcs_errors = err_ref } ->
562 nest_env = TcSEnv { tcs_ev_binds = ref
563 , tcs_ty_binds = ty_binds
565 , tcs_context = ctxtUnderImplic ctxt
566 , tcs_errors = err_ref }
568 thing_inside nest_env
570 recoverTcS :: TcS a -> TcS a -> TcS a
571 recoverTcS (TcS recovery_code) (TcS thing_inside)
573 TcM.recoverM (recovery_code env) (thing_inside env)
575 ctxtUnderImplic :: SimplContext -> SimplContext
576 -- See Note [Simplifying RULE lhs constraints] in TcSimplify
577 ctxtUnderImplic SimplRuleLhs = SimplCheck
578 ctxtUnderImplic ctxt = ctxt
580 tryTcS :: TcS a -> TcS a
581 -- Like runTcS, but from within the TcS monad
582 -- Ignore all the evidence generated, and do not affect caller's evidence!
584 = TcS (\env -> do { ty_binds_var <- TcM.newTcRef emptyVarEnv
585 ; ev_binds_var <- TcM.newTcEvBinds
586 ; err_ref <- TcM.newTcRef emptyBag
587 ; let env1 = env { tcs_ev_binds = ev_binds_var
588 , tcs_ty_binds = ty_binds_var
589 , tcs_errors = err_ref }
593 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
595 getDynFlags :: TcS DynFlags
596 getDynFlags = wrapTcS TcM.getDOpts
598 getTcSContext :: TcS SimplContext
599 getTcSContext = TcS (return . tcs_context)
601 getTcEvBinds :: TcS EvBindsVar
602 getTcEvBinds = TcS (return . tcs_ev_binds)
604 getUntouchables :: TcS TcsUntouchables
605 getUntouchables = TcS (return . tcs_untch)
607 getTcSTyBinds :: TcS (IORef (TyVarEnv (TcTyVar, TcType)))
608 getTcSTyBinds = TcS (return . tcs_ty_binds)
610 getTcSErrors :: TcS (IORef (Bag FrozenError))
611 getTcSErrors = TcS (return . tcs_errors)
613 getTcSErrorsBag :: TcS (Bag FrozenError)
614 getTcSErrorsBag = do { err_ref <- getTcSErrors
615 ; wrapTcS $ TcM.readTcRef err_ref }
617 getTcSTyBindsMap :: TcS (TyVarEnv (TcTyVar, TcType))
618 getTcSTyBindsMap = getTcSTyBinds >>= wrapTcS . (TcM.readTcRef)
621 getTcEvBindsBag :: TcS EvBindMap
623 = do { EvBindsVar ev_ref _ <- getTcEvBinds
624 ; wrapTcS $ TcM.readTcRef ev_ref }
626 setWantedCoBind :: CoVar -> Coercion -> TcS ()
627 setWantedCoBind cv co
628 = setEvBind cv (EvCoercion co)
629 -- Was: wrapTcS $ TcM.writeWantedCoVar cv co
631 setDerivedCoBind :: CoVar -> Coercion -> TcS ()
632 setDerivedCoBind cv co
633 = setEvBind cv (EvCoercion co)
635 setWantedTyBind :: TcTyVar -> TcType -> TcS ()
636 -- Add a type binding
637 -- We never do this twice!
638 setWantedTyBind tv ty
639 = do { ref <- getTcSTyBinds
641 do { ty_binds <- TcM.readTcRef ref
643 ; TcM.checkErr (not (tv `elemVarEnv` ty_binds)) $
644 vcat [ text "TERRIBLE ERROR: double set of meta type variable"
645 , ppr tv <+> text ":=" <+> ppr ty
646 , text "Old value =" <+> ppr (lookupVarEnv_NF ty_binds tv)]
648 ; TcM.writeTcRef ref (extendVarEnv ty_binds tv (tv,ty)) } }
650 setIPBind :: EvVar -> EvTerm -> TcS ()
651 setIPBind = setEvBind
653 setDictBind :: EvVar -> EvTerm -> TcS ()
654 setDictBind = setEvBind
656 setEvBind :: EvVar -> EvTerm -> TcS ()
659 = do { tc_evbinds <- getTcEvBinds
660 ; wrapTcS (TcM.addTcEvBind tc_evbinds ev rhs) }
662 newTcEvBindsTcS :: TcS EvBindsVar
663 newTcEvBindsTcS = wrapTcS (TcM.newTcEvBinds)
665 warnTcS :: CtLoc orig -> Bool -> SDoc -> TcS ()
666 warnTcS loc warn_if doc
667 | warn_if = wrapTcS $ TcM.setCtLoc loc $ TcM.addWarnTc doc
668 | otherwise = return ()
670 getDefaultInfo :: TcS (SimplContext, [Type], (Bool, Bool))
672 = do { ctxt <- getTcSContext
673 ; (tys, flags) <- wrapTcS (TcM.tcGetDefaultTys (isInteractive ctxt))
674 ; return (ctxt, tys, flags) }
678 -- Recording errors in the TcS monad
679 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681 addErrorTcS :: ErrorKind -> CtFlavor -> TcType -> TcType -> TcS ()
682 addErrorTcS frknd fl ty1 ty2
683 = do { err_ref <- getTcSErrors
685 { TcM.updTcRef err_ref $ \ errs ->
686 consBag (FrozenError frknd fl ty1 ty2) errs
688 -- If there's an error in the *given* constraints,
689 -- stop right now, to avoid a cascade of errors
691 ; when (isGiven fl) TcM.failM
695 -- Just get some environments needed for instance looking up and matching
696 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
698 getInstEnvs :: TcS (InstEnv, InstEnv)
699 getInstEnvs = wrapTcS $ Inst.tcGetInstEnvs
701 getFamInstEnvs :: TcS (FamInstEnv, FamInstEnv)
702 getFamInstEnvs = wrapTcS $ FamInst.tcGetFamInstEnvs
704 getTopEnv :: TcS HscEnv
705 getTopEnv = wrapTcS $ TcM.getTopEnv
707 getGblEnv :: TcS TcGblEnv
708 getGblEnv = wrapTcS $ TcM.getGblEnv
710 -- Various smaller utilities [TODO, maybe will be absorbed in the instance matcher]
711 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
713 checkWellStagedDFun :: PredType -> DFunId -> WantedLoc -> TcS ()
714 checkWellStagedDFun pred dfun_id loc
715 = wrapTcS $ TcM.setCtLoc loc $
716 do { use_stage <- TcM.getStage
717 ; TcM.checkWellStaged pp_thing bind_lvl (thLevel use_stage) }
719 pp_thing = ptext (sLit "instance for") <+> quotes (ppr pred)
720 bind_lvl = TcM.topIdLvl dfun_id
722 pprEq :: TcType -> TcType -> SDoc
723 pprEq ty1 ty2 = pprPred $ mkEqPred (ty1,ty2)
725 isTouchableMetaTyVar :: TcTyVar -> TcS Bool
726 isTouchableMetaTyVar tv
727 = do { untch <- getUntouchables
728 ; return $ isTouchableMetaTyVar_InRange untch tv }
730 isTouchableMetaTyVar_InRange :: TcsUntouchables -> TcTyVar -> Bool
731 isTouchableMetaTyVar_InRange (untch,untch_tcs) tv
732 = case tcTyVarDetails tv of
733 MetaTv TcsTv _ -> not (tv `elemVarSet` untch_tcs)
734 -- See Note [Touchable meta type variables]
735 MetaTv {} -> inTouchableRange untch tv
742 Note [Touchable meta type variables]
743 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
744 Meta type variables allocated *by the constraint solver itself* are always
746 instance C a b => D [a] where...
747 if we use this instance declaration we "make up" a fresh meta type
748 variable for 'b', which we must later guess. (Perhaps C has a
749 functional dependency.) But since we aren't in the constraint *generator*
750 we can't allocate a Unique in the touchable range for this implication
751 constraint. Instead, we mark it as a "TcsTv", which makes it always-touchable.
756 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
758 newFlattenSkolemTy :: TcType -> TcS TcType
759 newFlattenSkolemTy ty = mkTyVarTy <$> newFlattenSkolemTyVar ty
761 newFlattenSkolemTyVar :: TcType -> TcS TcTyVar
762 newFlattenSkolemTyVar ty
763 = do { tv <- wrapTcS $ do { uniq <- TcM.newUnique
764 ; let name = mkSysTvName uniq (fsLit "f")
765 ; return $ mkTcTyVar name (typeKind ty) (FlatSkol ty) }
766 ; traceTcS "New Flatten Skolem Born" $
767 (ppr tv <+> text "[:= " <+> ppr ty <+> text "]")
771 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
773 instDFunTypes :: [Either TyVar TcType] -> TcS [TcType]
774 instDFunTypes mb_inst_tys
775 = mapM inst_tv mb_inst_tys
777 inst_tv :: Either TyVar TcType -> TcS Type
778 inst_tv (Left tv) = mkTyVarTy <$> instFlexiTcS tv
779 inst_tv (Right ty) = return ty
781 instDFunConstraints :: TcThetaType -> TcS [EvVar]
782 instDFunConstraints preds = wrapTcS $ TcM.newWantedEvVars preds
785 instFlexiTcS :: TyVar -> TcS TcTyVar
786 -- Like TcM.instMetaTyVar but the variable that is created is always
787 -- touchable; we are supposed to guess its instantiation.
788 -- See Note [Touchable meta type variables]
789 instFlexiTcS tv = instFlexiTcSHelper (tyVarName tv) (tyVarKind tv)
791 newFlexiTcSTy :: Kind -> TcS TcType
794 do { uniq <- TcM.newUnique
795 ; ref <- TcM.newMutVar Flexi
796 ; let name = mkSysTvName uniq (fsLit "uf")
797 ; return $ mkTyVarTy (mkTcTyVar name knd (MetaTv TcsTv ref)) }
799 isFlexiTcsTv :: TyVar -> Bool
801 | not (isTcTyVar tv) = False
802 | MetaTv TcsTv _ <- tcTyVarDetails tv = True
805 newKindConstraint :: TcTyVar -> Kind -> TcS CoVar
806 -- Create new wanted CoVar that constrains the type to have the specified kind.
807 newKindConstraint tv knd
808 = do { tv_k <- instFlexiTcSHelper (tyVarName tv) knd
809 ; let ty_k = mkTyVarTy tv_k
810 ; co_var <- newWantedCoVar (mkTyVarTy tv) ty_k
813 instFlexiTcSHelper :: Name -> Kind -> TcS TcTyVar
814 instFlexiTcSHelper tvname tvkind
816 do { uniq <- TcM.newUnique
817 ; ref <- TcM.newMutVar Flexi
818 ; let name = setNameUnique tvname uniq
820 ; return (mkTcTyVar name kind (MetaTv TcsTv ref)) }
822 -- Superclasses and recursive dictionaries
823 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
825 newGivOrDerEvVar :: TcPredType -> EvTerm -> TcS EvVar
826 newGivOrDerEvVar pty evtrm
827 = do { ev <- wrapTcS $ TcM.newEvVar pty
831 newGivOrDerCoVar :: TcType -> TcType -> Coercion -> TcS EvVar
832 -- Note we create immutable variables for given or derived, since we
833 -- must bind them to TcEvBinds (because their evidence may involve
834 -- superclasses). However we should be able to override existing
835 -- 'derived' evidence, even in TcEvBinds
836 newGivOrDerCoVar ty1 ty2 co
837 = do { cv <- newCoVar ty1 ty2
838 ; setEvBind cv (EvCoercion co)
841 newWantedCoVar :: TcType -> TcType -> TcS EvVar
842 newWantedCoVar ty1 ty2 = wrapTcS $ TcM.newWantedCoVar ty1 ty2
845 newCoVar :: TcType -> TcType -> TcS EvVar
846 newCoVar ty1 ty2 = wrapTcS $ TcM.newCoVar ty1 ty2
848 newIPVar :: IPName Name -> TcType -> TcS EvVar
849 newIPVar nm ty = wrapTcS $ TcM.newIP nm ty
851 newDictVar :: Class -> [TcType] -> TcS EvVar
852 newDictVar cl tys = wrapTcS $ TcM.newDict cl tys
857 isGoodRecEv :: EvVar -> EvVar -> TcS Bool
858 -- In a call (isGoodRecEv ev wv), we are considering solving wv
859 -- using some term that involves ev, such as:
860 -- by setting wv = ev
861 -- or wv = EvCast x |> ev
863 -- But that would be Very Bad if the evidence for 'ev' mentions 'wv',
864 -- in an "unguarded" way. So isGoodRecEv looks at the evidence ev
865 -- recursively through the evidence binds, to see if uses of 'wv' are guarded.
867 -- Guarded means: more instance calls than superclass selections. We
868 -- compute this by chasing the evidence, adding +1 for every instance
869 -- call (constructor) and -1 for every superclass selection (destructor).
871 -- See Note [Superclasses and recursive dictionaries] in TcInteract
872 isGoodRecEv ev_var wv
873 = do { tc_evbinds <- getTcEvBindsBag
874 ; mb <- chase_ev_var tc_evbinds wv 0 [] ev_var
875 ; return $ case mb of
877 Just min_guardedness -> min_guardedness > 0
880 where chase_ev_var :: EvBindMap -- Evidence binds
881 -> EvVar -- Target variable whose gravity we want to return
882 -> Int -- Current gravity
883 -> [EvVar] -- Visited nodes
884 -> EvVar -- Current node
886 chase_ev_var assocs trg curr_grav visited orig
887 | trg == orig = return $ Just curr_grav
888 | orig `elem` visited = return $ Nothing
889 | Just (EvBind _ ev_trm) <- lookupEvBind assocs orig
890 = chase_ev assocs trg curr_grav (orig:visited) ev_trm
892 | otherwise = return Nothing
894 chase_ev assocs trg curr_grav visited (EvId v)
895 = chase_ev_var assocs trg curr_grav visited v
896 chase_ev assocs trg curr_grav visited (EvSuperClass d_id _)
897 = chase_ev_var assocs trg (curr_grav-1) visited d_id
898 chase_ev assocs trg curr_grav visited (EvCast v co)
899 = do { m1 <- chase_ev_var assocs trg curr_grav visited v
900 ; m2 <- chase_co assocs trg curr_grav visited co
901 ; return (comb_chase_res Nothing [m1,m2]) }
903 chase_ev assocs trg curr_grav visited (EvCoercion co)
904 = chase_co assocs trg curr_grav visited co
905 chase_ev assocs trg curr_grav visited (EvDFunApp _ _ _ev_vars ev_deps)
906 = do { chase_results <- mapM (chase_ev_var assocs trg (curr_grav+1) visited) ev_deps
907 -- Notice that we chase the ev_deps and not the ev_vars
908 -- See Note [Dependencies in self dictionaries] in TcSimplify
909 ; return (comb_chase_res Nothing chase_results) }
911 chase_co assocs trg curr_grav visited co
912 = -- Look for all the coercion variables in the coercion
913 -- chase them, and combine the results. This is OK since the
914 -- coercion will not contain any superclass terms -- anything
915 -- that involves dictionaries will be bound in assocs.
916 let co_vars = foldVarSet (\v vrs -> if isCoVar v then (v:vrs) else vrs) []
918 in do { chase_results <- mapM (chase_ev_var assocs trg curr_grav visited) co_vars
919 ; return (comb_chase_res Nothing chase_results) }
921 comb_chase_res f [] = f
922 comb_chase_res f (Nothing:rest) = comb_chase_res f rest
923 comb_chase_res Nothing (Just n:rest) = comb_chase_res (Just n) rest
924 comb_chase_res (Just m) (Just n:rest) = comb_chase_res (Just (min n m)) rest
927 -- Matching and looking up classes and family instances
928 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
930 data MatchInstResult mi
931 = MatchInstNo -- No matching instance
932 | MatchInstSingle mi -- Single matching instance
933 | MatchInstMany -- Multiple matching instances
936 matchClass :: Class -> [Type] -> TcS (MatchInstResult (DFunId, [Either TyVar TcType]))
937 -- Look up a class constraint in the instance environment
939 = do { let pred = mkClassPred clas tys
940 ; instEnvs <- getInstEnvs
941 ; case lookupInstEnv instEnvs clas tys of {
942 ([], unifs) -- Nothing matches
943 -> do { traceTcS "matchClass not matching"
944 (vcat [ text "dict" <+> ppr pred,
945 text "unifs" <+> ppr unifs ])
948 ([(ispec, inst_tys)], []) -- A single match
949 -> do { let dfun_id = is_dfun ispec
950 ; traceTcS "matchClass success"
951 (vcat [text "dict" <+> ppr pred,
952 text "witness" <+> ppr dfun_id
953 <+> ppr (idType dfun_id) ])
954 -- Record that this dfun is needed
955 ; record_dfun_usage dfun_id
956 ; return $ MatchInstSingle (dfun_id, inst_tys)
958 (matches, unifs) -- More than one matches
959 -> do { traceTcS "matchClass multiple matches, deferring choice"
960 (vcat [text "dict" <+> ppr pred,
961 text "matches" <+> ppr matches,
962 text "unifs" <+> ppr unifs])
963 ; return MatchInstMany
967 where record_dfun_usage :: Id -> TcS ()
968 record_dfun_usage dfun_id
969 = do { hsc_env <- getTopEnv
970 ; let dfun_name = idName dfun_id
971 dfun_mod = ASSERT( isExternalName dfun_name )
973 ; if isInternalName dfun_name || -- Internal name => defined in this module
974 modulePackageId dfun_mod /= thisPackage (hsc_dflags hsc_env)
975 then return () -- internal, or in another package
976 else do updInstUses dfun_id
979 updInstUses :: Id -> TcS ()
981 = do { tcg_env <- getGblEnv
982 ; wrapTcS $ TcM.updMutVar (tcg_inst_uses tcg_env)
983 (`addOneToNameSet` idName dfun_id)
988 -> TcS (MatchInstResult (TyCon, [Type]))
990 = do { mb <- wrapTcS $ TcM.tcLookupFamInst tycon args
992 Nothing -> return MatchInstNo
993 Just res -> return $ MatchInstSingle res
994 -- DV: We never return MatchInstMany, since tcLookupFamInst never returns
995 -- multiple matches. Check.
999 -- Functional dependencies, instantiation of equations
1000 -------------------------------------------------------
1002 mkWantedFunDepEqns :: WantedLoc
1003 -> [(Equation, (PredType, SDoc), (PredType, SDoc))]
1004 -> TcS [WantedEvVar]
1005 mkWantedFunDepEqns _ [] = return []
1006 mkWantedFunDepEqns loc eqns
1007 = do { traceTcS "Improve:" (vcat (map pprEquationDoc eqns))
1008 ; wevvars <- mapM to_work_item eqns
1009 ; return $ concat wevvars }
1011 to_work_item :: (Equation, (PredType,SDoc), (PredType,SDoc)) -> TcS [WantedEvVar]
1012 to_work_item ((qtvs, pairs), d1, d2)
1013 = do { let tvs = varSetElems qtvs
1014 ; tvs' <- mapM instFlexiTcS tvs
1015 ; let subst = zipTopTvSubst tvs (mkTyVarTys tvs')
1016 loc' = pushErrCtxt FunDepOrigin (False, mkEqnMsg d1 d2) loc
1017 ; mapM (do_one subst loc') pairs }
1019 do_one subst loc' (ty1, ty2)
1020 = do { let sty1 = substTy subst ty1
1021 sty2 = substTy subst ty2
1022 ; ev <- newWantedCoVar sty1 sty2
1023 ; return (WantedEvVar ev loc') }
1025 pprEquationDoc :: (Equation, (PredType, SDoc), (PredType, SDoc)) -> SDoc
1026 pprEquationDoc (eqn, (p1, _), (p2, _))
1027 = vcat [pprEquation eqn, nest 2 (ppr p1), nest 2 (ppr p2)]
1029 mkEqnMsg :: (TcPredType, SDoc) -> (TcPredType, SDoc) -> TidyEnv
1030 -> TcM (TidyEnv, SDoc)
1031 mkEqnMsg (pred1,from1) (pred2,from2) tidy_env
1032 = do { pred1' <- TcM.zonkTcPredType pred1
1033 ; pred2' <- TcM.zonkTcPredType pred2
1034 ; let { pred1'' = tidyPred tidy_env pred1'
1035 ; pred2'' = tidyPred tidy_env pred2' }
1036 ; let msg = vcat [ptext (sLit "When using functional dependencies to combine"),
1037 nest 2 (sep [ppr pred1'' <> comma, nest 2 from1]),
1038 nest 2 (sep [ppr pred2'' <> comma, nest 2 from2])]
1039 ; return (tidy_env, msg) }