1 use crate::infer
::{InferCtxt, ShallowResolver}
;
2 use crate::ty
::error
::ExpectedFound
;
3 use crate::ty
::{self, ToPolyTraitRef, Ty, TypeFoldable}
;
4 use rustc_data_structures
::obligation_forest
::ProcessResult
;
5 use rustc_data_structures
::obligation_forest
::{DoCompleted, Error, ForestObligation}
;
6 use rustc_data_structures
::obligation_forest
::{ObligationForest, ObligationProcessor}
;
7 use std
::marker
::PhantomData
;
9 use super::engine
::{TraitEngine, TraitEngineExt}
;
11 use super::select
::SelectionContext
;
13 use super::CodeAmbiguity
;
14 use super::CodeProjectionError
;
15 use super::CodeSelectionError
;
16 use super::{ConstEvalFailure, Unimplemented}
;
17 use super::{FulfillmentError, FulfillmentErrorCode}
;
18 use super::{ObligationCause, PredicateObligation}
;
20 impl<'tcx
> ForestObligation
for PendingPredicateObligation
<'tcx
> {
21 type Predicate
= ty
::Predicate
<'tcx
>;
23 fn as_predicate(&self) -> &Self::Predicate
{
24 &self.obligation
.predicate
28 /// The fulfillment context is used to drive trait resolution. It
29 /// consists of a list of obligations that must be (eventually)
30 /// satisfied. The job is to track which are satisfied, which yielded
31 /// errors, and which are still pending. At any point, users can call
32 /// `select_where_possible`, and the fulfillment context will try to do
33 /// selection, retaining only those obligations that remain
34 /// ambiguous. This may be helpful in pushing type inference
35 /// along. Once all type inference constraints have been generated, the
36 /// method `select_all_or_error` can be used to report any remaining
37 /// ambiguous cases as errors.
38 pub struct FulfillmentContext
<'tcx
> {
39 // A list of all obligations that have been registered with this
40 // fulfillment context.
41 predicates
: ObligationForest
<PendingPredicateObligation
<'tcx
>>,
42 // Should this fulfillment context register type-lives-for-region
43 // obligations on its parent infcx? In some cases, region
44 // obligations are either already known to hold (normalization) or
45 // hopefully verifed elsewhere (type-impls-bound), and therefore
46 // should not be checked.
48 // Note that if we are normalizing a type that we already
49 // know is well-formed, there should be no harm setting this
50 // to true - all the region variables should be determinable
51 // using the RFC 447 rules, which don't depend on
52 // type-lives-for-region constraints, and because the type
53 // is well-formed, the constraints should hold.
54 register_region_obligations
: bool
,
55 // Is it OK to register obligations into this infcx inside
58 // The "primary fulfillment" in many cases in typeck lives
59 // outside of any snapshot, so any use of it inside a snapshot
60 // will lead to trouble and therefore is checked against, but
61 // other fulfillment contexts sometimes do live inside of
62 // a snapshot (they don't *straddle* a snapshot, so there
63 // is no trouble there).
64 usable_in_snapshot
: bool
,
67 #[derive(Clone, Debug)]
68 pub struct PendingPredicateObligation
<'tcx
> {
69 pub obligation
: PredicateObligation
<'tcx
>,
70 pub stalled_on
: Vec
<ty
::InferTy
>,
73 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
74 #[cfg(target_arch = "x86_64")]
75 static_assert_size
!(PendingPredicateObligation
<'_
>, 136);
77 impl<'a
, 'tcx
> FulfillmentContext
<'tcx
> {
78 /// Creates a new fulfillment context.
79 pub fn new() -> FulfillmentContext
<'tcx
> {
81 predicates
: ObligationForest
::new(),
82 register_region_obligations
: true,
83 usable_in_snapshot
: false,
87 pub fn new_in_snapshot() -> FulfillmentContext
<'tcx
> {
89 predicates
: ObligationForest
::new(),
90 register_region_obligations
: true,
91 usable_in_snapshot
: true,
95 pub fn new_ignoring_regions() -> FulfillmentContext
<'tcx
> {
97 predicates
: ObligationForest
::new(),
98 register_region_obligations
: false,
99 usable_in_snapshot
: false,
103 /// Attempts to select obligations using `selcx`.
106 selcx
: &mut SelectionContext
<'a
, 'tcx
>,
107 ) -> Result
<(), Vec
<FulfillmentError
<'tcx
>>> {
108 debug
!("select(obligation-forest-size={})", self.predicates
.len());
110 let mut errors
= Vec
::new();
113 debug
!("select: starting another iteration");
115 // Process pending obligations.
116 let outcome
= self.predicates
.process_obligations(
117 &mut FulfillProcessor
{
119 register_region_obligations
: self.register_region_obligations
,
123 debug
!("select: outcome={:#?}", outcome
);
125 // FIXME: if we kept the original cache key, we could mark projection
126 // obligations as complete for the projection cache here.
128 errors
.extend(outcome
.errors
.into_iter().map(|e
| to_fulfillment_error(e
)));
130 // If nothing new was added, no need to keep looping.
137 "select({} predicates remaining, {} errors) done",
138 self.predicates
.len(),
142 if errors
.is_empty() { Ok(()) }
else { Err(errors) }
146 impl<'tcx
> TraitEngine
<'tcx
> for FulfillmentContext
<'tcx
> {
147 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
148 /// creating a fresh type variable `$0` as well as a projection
149 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
150 /// inference engine runs, it will attempt to find an impl of
151 /// `SomeTrait` or a where-clause that lets us unify `$0` with
152 /// something concrete. If this fails, we'll unify `$0` with
153 /// `projection_ty` again.
154 fn normalize_projection_type(
156 infcx
: &InferCtxt
<'_
, 'tcx
>,
157 param_env
: ty
::ParamEnv
<'tcx
>,
158 projection_ty
: ty
::ProjectionTy
<'tcx
>,
159 cause
: ObligationCause
<'tcx
>,
161 debug
!("normalize_projection_type(projection_ty={:?})", projection_ty
);
163 debug_assert
!(!projection_ty
.has_escaping_bound_vars());
165 // FIXME(#20304) -- cache
167 let mut selcx
= SelectionContext
::new(infcx
);
168 let mut obligations
= vec
![];
169 let normalized_ty
= project
::normalize_projection_type(
177 self.register_predicate_obligations(infcx
, obligations
);
179 debug
!("normalize_projection_type: result={:?}", normalized_ty
);
184 fn register_predicate_obligation(
186 infcx
: &InferCtxt
<'_
, 'tcx
>,
187 obligation
: PredicateObligation
<'tcx
>,
189 // this helps to reduce duplicate errors, as well as making
190 // debug output much nicer to read and so on.
191 let obligation
= infcx
.resolve_vars_if_possible(&obligation
);
193 debug
!("register_predicate_obligation(obligation={:?})", obligation
);
195 assert
!(!infcx
.is_in_snapshot() || self.usable_in_snapshot
);
198 .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] }
);
201 fn select_all_or_error(
203 infcx
: &InferCtxt
<'_
, 'tcx
>,
204 ) -> Result
<(), Vec
<FulfillmentError
<'tcx
>>> {
205 self.select_where_possible(infcx
)?
;
207 let errors
: Vec
<_
> = self
209 .to_errors(CodeAmbiguity
)
211 .map(|e
| to_fulfillment_error(e
))
213 if errors
.is_empty() { Ok(()) }
else { Err(errors) }
216 fn select_where_possible(
218 infcx
: &InferCtxt
<'_
, 'tcx
>,
219 ) -> Result
<(), Vec
<FulfillmentError
<'tcx
>>> {
220 let mut selcx
= SelectionContext
::new(infcx
);
221 self.select(&mut selcx
)
224 fn pending_obligations(&self) -> Vec
<PredicateObligation
<'tcx
>> {
225 self.predicates
.map_pending_obligations(|o
| o
.obligation
.clone())
229 struct FulfillProcessor
<'a
, 'b
, 'tcx
> {
230 selcx
: &'a
mut SelectionContext
<'b
, 'tcx
>,
231 register_region_obligations
: bool
,
234 fn mk_pending(os
: Vec
<PredicateObligation
<'tcx
>>) -> Vec
<PendingPredicateObligation
<'tcx
>> {
236 .map(|o
| PendingPredicateObligation { obligation: o, stalled_on: vec![] }
)
240 impl<'a
, 'b
, 'tcx
> ObligationProcessor
for FulfillProcessor
<'a
, 'b
, 'tcx
> {
241 type Obligation
= PendingPredicateObligation
<'tcx
>;
242 type Error
= FulfillmentErrorCode
<'tcx
>;
244 /// Processes a predicate obligation and returns either:
245 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
246 /// - `Unchanged` if we don't have enough info to be sure
247 /// - `Error(e)` if the predicate does not hold
249 /// This is always inlined, despite its size, because it has a single
250 /// callsite and it is called *very* frequently.
252 fn process_obligation(
254 pending_obligation
: &mut Self::Obligation
,
255 ) -> ProcessResult
<Self::Obligation
, Self::Error
> {
256 // If we were stalled on some unresolved variables, first check whether
257 // any of them have been resolved; if not, don't bother doing more work
259 let change
= match pending_obligation
.stalled_on
.len() {
260 // Match arms are in order of frequency, which matters because this
261 // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
263 let infer
= pending_obligation
.stalled_on
[0];
264 ShallowResolver
::new(self.selcx
.infcx()).shallow_resolve_changed(infer
)
267 // In this case we haven't changed, but wish to make a change.
271 // This `for` loop was once a call to `all()`, but this lower-level
272 // form was a perf win. See #64545 for details.
274 for &infer
in &pending_obligation
.stalled_on
{
275 if ShallowResolver
::new(self.selcx
.infcx()).shallow_resolve_changed(infer
) {
286 "process_predicate: pending obligation {:?} still stalled on {:?}",
287 self.selcx
.infcx().resolve_vars_if_possible(&pending_obligation
.obligation
),
288 pending_obligation
.stalled_on
290 return ProcessResult
::Unchanged
;
293 // This part of the code is much colder.
295 pending_obligation
.stalled_on
.truncate(0);
297 let obligation
= &mut pending_obligation
.obligation
;
299 if obligation
.predicate
.has_infer_types() {
300 obligation
.predicate
=
301 self.selcx
.infcx().resolve_vars_if_possible(&obligation
.predicate
);
304 debug
!("process_obligation: obligation = {:?} cause = {:?}", obligation
, obligation
.cause
);
306 fn infer_ty(ty
: Ty
<'tcx
>) -> ty
::InferTy
{
308 ty
::Infer(infer
) => infer
,
313 match obligation
.predicate
{
314 ty
::Predicate
::Trait(ref data
, _
) => {
315 let trait_obligation
= obligation
.with(data
.clone());
317 if data
.is_global() {
318 // no type variables present, can use evaluation for better caching.
319 // FIXME: consider caching errors too.
320 if self.selcx
.infcx().predicate_must_hold_considering_regions(&obligation
) {
322 "selecting trait `{:?}` at depth {} evaluated to holds",
323 data
, obligation
.recursion_depth
325 return ProcessResult
::Changed(vec
![]);
329 match self.selcx
.select(&trait_obligation
) {
330 Ok(Some(vtable
)) => {
332 "selecting trait `{:?}` at depth {} yielded Ok(Some)",
333 data
, obligation
.recursion_depth
335 ProcessResult
::Changed(mk_pending(vtable
.nested_obligations()))
339 "selecting trait `{:?}` at depth {} yielded Ok(None)",
340 data
, obligation
.recursion_depth
343 // This is a bit subtle: for the most part, the
344 // only reason we can fail to make progress on
345 // trait selection is because we don't have enough
346 // information about the types in the trait. One
347 // exception is that we sometimes haven't decided
348 // what kind of closure a closure is. *But*, in
349 // that case, it turns out, the type of the
350 // closure will also change, because the closure
351 // also includes references to its upvars as part
352 // of its type, and those types are resolved at
355 // FIXME(#32286) logic seems false if no upvars
356 pending_obligation
.stalled_on
=
357 trait_ref_type_vars(self.selcx
, data
.to_poly_trait_ref());
360 "process_predicate: pending obligation {:?} now stalled on {:?}",
361 self.selcx
.infcx().resolve_vars_if_possible(obligation
),
362 pending_obligation
.stalled_on
365 ProcessResult
::Unchanged
367 Err(selection_err
) => {
369 "selecting trait `{:?}` at depth {} yielded Err",
370 data
, obligation
.recursion_depth
373 ProcessResult
::Error(CodeSelectionError(selection_err
))
378 ty
::Predicate
::RegionOutlives(ref binder
) => {
379 match self.selcx
.infcx().region_outlives_predicate(&obligation
.cause
, binder
) {
380 Ok(()) => ProcessResult
::Changed(vec
![]),
381 Err(_
) => ProcessResult
::Error(CodeSelectionError(Unimplemented
)),
385 ty
::Predicate
::TypeOutlives(ref binder
) => {
386 // Check if there are higher-ranked vars.
387 match binder
.no_bound_vars() {
388 // If there are, inspect the underlying type further.
390 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
391 let binder
= binder
.map_bound_ref(|pred
| pred
.0);
393 // Check if the type has any bound vars.
394 match binder
.no_bound_vars() {
395 // If so, this obligation is an error (for now). Eventually we should be
396 // able to support additional cases here, like `for<'a> &'a str: 'a`.
397 // NOTE: this is duplicate-implemented between here and fulfillment.
398 None
=> ProcessResult
::Error(CodeSelectionError(Unimplemented
)),
399 // Otherwise, we have something of the form
400 // `for<'a> T: 'a where 'a not in T`, which we can treat as
403 let r_static
= self.selcx
.tcx().lifetimes
.re_static
;
404 if self.register_region_obligations
{
405 self.selcx
.infcx().register_region_obligation_with_cause(
411 ProcessResult
::Changed(vec
![])
415 // If there aren't, register the obligation.
416 Some(ty
::OutlivesPredicate(t_a
, r_b
)) => {
417 if self.register_region_obligations
{
418 self.selcx
.infcx().register_region_obligation_with_cause(
424 ProcessResult
::Changed(vec
![])
429 ty
::Predicate
::Projection(ref data
) => {
430 let project_obligation
= obligation
.with(data
.clone());
431 match project
::poly_project_and_unify_type(self.selcx
, &project_obligation
) {
433 let tcx
= self.selcx
.tcx();
434 pending_obligation
.stalled_on
=
435 trait_ref_type_vars(self.selcx
, data
.to_poly_trait_ref(tcx
));
436 ProcessResult
::Unchanged
438 Ok(Some(os
)) => ProcessResult
::Changed(mk_pending(os
)),
439 Err(e
) => ProcessResult
::Error(CodeProjectionError(e
)),
443 ty
::Predicate
::ObjectSafe(trait_def_id
) => {
444 if !self.selcx
.tcx().is_object_safe(trait_def_id
) {
445 ProcessResult
::Error(CodeSelectionError(Unimplemented
))
447 ProcessResult
::Changed(vec
![])
451 ty
::Predicate
::ClosureKind(closure_def_id
, closure_substs
, kind
) => {
452 match self.selcx
.infcx().closure_kind(closure_def_id
, closure_substs
) {
453 Some(closure_kind
) => {
454 if closure_kind
.extends(kind
) {
455 ProcessResult
::Changed(vec
![])
457 ProcessResult
::Error(CodeSelectionError(Unimplemented
))
460 None
=> ProcessResult
::Unchanged
,
464 ty
::Predicate
::WellFormed(ty
) => {
465 match wf
::obligations(
467 obligation
.param_env
,
468 obligation
.cause
.body_id
,
470 obligation
.cause
.span
,
473 pending_obligation
.stalled_on
= vec
![infer_ty(ty
)];
474 ProcessResult
::Unchanged
476 Some(os
) => ProcessResult
::Changed(mk_pending(os
)),
480 ty
::Predicate
::Subtype(ref subtype
) => {
481 match self.selcx
.infcx().subtype_predicate(
483 obligation
.param_env
,
487 // None means that both are unresolved.
488 pending_obligation
.stalled_on
= vec
![
489 infer_ty(subtype
.skip_binder().a
),
490 infer_ty(subtype
.skip_binder().b
),
492 ProcessResult
::Unchanged
494 Some(Ok(ok
)) => ProcessResult
::Changed(mk_pending(ok
.obligations
)),
496 let expected_found
= ExpectedFound
::new(
497 subtype
.skip_binder().a_is_expected
,
498 subtype
.skip_binder().a
,
499 subtype
.skip_binder().b
,
501 ProcessResult
::Error(FulfillmentErrorCode
::CodeSubtypeError(
509 ty
::Predicate
::ConstEvaluatable(def_id
, substs
) => {
510 if obligation
.param_env
.has_local_value() {
511 ProcessResult
::Unchanged
513 if !substs
.has_local_value() {
514 match self.selcx
.tcx().const_eval_resolve(
515 obligation
.param_env
,
519 Some(obligation
.cause
.span
),
521 Ok(_
) => ProcessResult
::Changed(vec
![]),
523 ProcessResult
::Error(CodeSelectionError(ConstEvalFailure(err
)))
527 pending_obligation
.stalled_on
=
528 substs
.types().map(|ty
| infer_ty(ty
)).collect();
529 ProcessResult
::Unchanged
536 fn process_backedge
<'c
, I
>(
539 _marker
: PhantomData
<&'c PendingPredicateObligation
<'tcx
>>,
541 I
: Clone
+ Iterator
<Item
= &'c PendingPredicateObligation
<'tcx
>>,
543 if self.selcx
.coinductive_match(cycle
.clone().map(|s
| s
.obligation
.predicate
)) {
544 debug
!("process_child_obligations: coinductive match");
546 let cycle
: Vec
<_
> = cycle
.map(|c
| c
.obligation
.clone()).collect();
547 self.selcx
.infcx().report_overflow_error_cycle(&cycle
);
552 /// Returns the set of type variables contained in a trait ref
553 fn trait_ref_type_vars
<'a
, 'tcx
>(
554 selcx
: &mut SelectionContext
<'a
, 'tcx
>,
555 t
: ty
::PolyTraitRef
<'tcx
>,
556 ) -> Vec
<ty
::InferTy
> {
557 t
.skip_binder() // ok b/c this check doesn't care about regions
559 .map(|t
| selcx
.infcx().resolve_vars_if_possible(&t
))
560 .filter(|t
| t
.has_infer_types())
561 .flat_map(|t
| t
.walk())
562 .filter_map(|t
| match t
.kind
{
563 ty
::Infer(infer
) => Some(infer
),
569 fn to_fulfillment_error
<'tcx
>(
570 error
: Error
<PendingPredicateObligation
<'tcx
>, FulfillmentErrorCode
<'tcx
>>,
571 ) -> FulfillmentError
<'tcx
> {
572 let obligation
= error
.backtrace
.into_iter().next().unwrap().obligation
;
573 FulfillmentError
::new(obligation
, error
.error
)