]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_trait_selection/src/traits/fulfill.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / traits / fulfill.rs
CommitLineData
ba9703b0 1use crate::infer::{InferCtxt, TyOrConstInferVar};
dfeec247 2use rustc_data_structures::obligation_forest::ProcessResult;
29967ef6 3use rustc_data_structures::obligation_forest::{Error, ForestObligation, Outcome};
a1dfa0c6 4use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
353b0b11 5use rustc_infer::infer::DefineOpaqueTypes;
a2a8927a 6use rustc_infer::traits::ProjectionCacheKey;
487cf647 7use rustc_infer::traits::{SelectionError, TraitEngine, TraitObligation};
f9f354fc 8use rustc_middle::mir::interpret::ErrorHandled;
064997fb 9use rustc_middle::ty::abstract_const::NotConstEvaluatable;
17df50a5 10use rustc_middle::ty::error::{ExpectedFound, TypeError};
6a06907d 11use rustc_middle::ty::subst::SubstsRef;
9ffffee4 12use rustc_middle::ty::{self, Binder, Const, TypeVisitableExt};
a7813a04 13use std::marker::PhantomData;
1a4d82fc 14
1b1a35ee 15use super::const_evaluatable;
5e7ed085 16use super::project::{self, ProjectAndUnifyResult};
dfeec247
XL
17use super::select::SelectionContext;
18use super::wf;
1a4d82fc
JJ
19use super::CodeAmbiguity;
20use super::CodeProjectionError;
21use super::CodeSelectionError;
a2a8927a 22use super::EvaluationResult;
487cf647 23use super::PredicateObligation;
cdc7bbd5 24use super::Unimplemented;
8bb4bdeb 25use super::{FulfillmentError, FulfillmentErrorCode};
a7813a04 26
3dfed10e 27use crate::traits::project::PolyProjectionObligation;
a2a8927a 28use crate::traits::project::ProjectionCacheKeyExt as _;
2b03887a 29use crate::traits::query::evaluate_obligation::InferCtxtExt;
ba9703b0 30
a7813a04 31impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
74b04a01
XL
32 /// Note that we include both the `ParamEnv` and the `Predicate`,
33 /// as the `ParamEnv` can influence whether fulfillment succeeds
34 /// or fails.
35 type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>;
a7813a04 36
74b04a01
XL
37 fn as_cache_key(&self) -> Self::CacheKey {
38 self.obligation.param_env.and(self.obligation.predicate)
dfeec247 39 }
a7813a04 40}
1a4d82fc 41
9fa01778 42/// The fulfillment context is used to drive trait resolution. It
1a4d82fc
JJ
43/// consists of a list of obligations that must be (eventually)
44/// satisfied. The job is to track which are satisfied, which yielded
45/// errors, and which are still pending. At any point, users can call
3b2f2976 46/// `select_where_possible`, and the fulfillment context will try to do
1a4d82fc
JJ
47/// selection, retaining only those obligations that remain
48/// ambiguous. This may be helpful in pushing type inference
49/// along. Once all type inference constraints have been generated, the
50/// method `select_all_or_error` can be used to report any remaining
51/// ambiguous cases as errors.
52pub struct FulfillmentContext<'tcx> {
1a4d82fc
JJ
53 // A list of all obligations that have been registered with this
54 // fulfillment context.
a7813a04 55 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
c295e0f8 56
0731742a
XL
57 // Is it OK to register obligations into this infcx inside
58 // an infcx snapshot?
59 //
60 // The "primary fulfillment" in many cases in typeck lives
61 // outside of any snapshot, so any use of it inside a snapshot
62 // will lead to trouble and therefore is checked against, but
63 // other fulfillment contexts sometimes do live inside of
64 // a snapshot (they don't *straddle* a snapshot, so there
65 // is no trouble there).
dfeec247 66 usable_in_snapshot: bool,
1a4d82fc
JJ
67}
68
7453a54e
SL
69#[derive(Clone, Debug)]
70pub struct PendingPredicateObligation<'tcx> {
71 pub obligation: PredicateObligation<'tcx>,
f9f354fc
XL
72 // This is far more often read than modified, meaning that we
73 // should mostly optimize for reading speed, while modifying is not as relevant.
74 //
75 // For whatever reason using a boxed slice is slower than using a `Vec` here.
ba9703b0 76 pub stalled_on: Vec<TyOrConstInferVar<'tcx>>,
7453a54e
SL
77}
78
e1599b0c 79// `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
6a06907d 80#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
a2a8927a 81static_assert_size!(PendingPredicateObligation<'_>, 72);
e1599b0c 82
dc9dc135 83impl<'a, 'tcx> FulfillmentContext<'tcx> {
62682a34 84 /// Creates a new fulfillment context.
487cf647 85 pub(super) fn new() -> FulfillmentContext<'tcx> {
9ffffee4 86 FulfillmentContext { predicates: ObligationForest::new(), usable_in_snapshot: false }
0731742a
XL
87 }
88
487cf647 89 pub(super) fn new_in_snapshot() -> FulfillmentContext<'tcx> {
9ffffee4 90 FulfillmentContext { predicates: ObligationForest::new(), usable_in_snapshot: true }
ff7c6d11
XL
91 }
92
8faf50e0 93 /// Attempts to select obligations using `selcx`.
2b03887a 94 fn select(&mut self, selcx: SelectionContext<'a, 'tcx>) -> Vec<FulfillmentError<'tcx>> {
29967ef6
XL
95 let span = debug_span!("select", obligation_forest_size = ?self.predicates.len());
96 let _enter = span.enter();
0531ce1d 97
923072b8 98 // Process pending obligations.
064997fb
FG
99 let outcome: Outcome<_, _> =
100 self.predicates.process_obligations(&mut FulfillProcessor { selcx });
0531ce1d 101
923072b8
FG
102 // FIXME: if we kept the original cache key, we could mark projection
103 // obligations as complete for the projection cache here.
0531ce1d 104
064997fb
FG
105 let errors: Vec<FulfillmentError<'tcx>> =
106 outcome.errors.into_iter().map(to_fulfillment_error).collect();
0531ce1d 107
dfeec247
XL
108 debug!(
109 "select({} predicates remaining, {} errors) done",
110 self.predicates.len(),
111 errors.len()
112 );
0531ce1d 113
3c0e092e 114 errors
0531ce1d
XL
115 }
116}
117
118impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
dc9dc135
XL
119 fn register_predicate_obligation(
120 &mut self,
2b03887a 121 infcx: &InferCtxt<'tcx>,
dc9dc135
XL
122 obligation: PredicateObligation<'tcx>,
123 ) {
1a4d82fc
JJ
124 // this helps to reduce duplicate errors, as well as making
125 // debug output much nicer to read and so on.
fc512014 126 let obligation = infcx.resolve_vars_if_possible(obligation);
1a4d82fc 127
29967ef6 128 debug!(?obligation, "register_predicate_obligation");
3157f602 129
0731742a 130 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
3157f602 131
dfeec247
XL
132 self.predicates
133 .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
a7813a04
XL
134 }
135
353b0b11
FG
136 fn collect_remaining_errors(
137 &mut self,
138 _infcx: &InferCtxt<'tcx>,
139 ) -> Vec<FulfillmentError<'tcx>> {
140 self.predicates
141 .to_errors(CodeAmbiguity { overflow: false })
142 .into_iter()
143 .map(to_fulfillment_error)
144 .collect()
1a4d82fc
JJ
145 }
146
2b03887a
FG
147 fn select_where_possible(&mut self, infcx: &InferCtxt<'tcx>) -> Vec<FulfillmentError<'tcx>> {
148 let selcx = SelectionContext::new(infcx);
149 self.select(selcx)
1a4d82fc
JJ
150 }
151
9ffffee4
FG
152 fn drain_unstalled_obligations(
153 &mut self,
154 infcx: &InferCtxt<'tcx>,
155 ) -> Vec<PredicateObligation<'tcx>> {
156 let mut processor = DrainProcessor { removed_predicates: Vec::new(), infcx };
157 let outcome: Outcome<_, _> = self.predicates.process_obligations(&mut processor);
158 assert!(outcome.errors.is_empty());
159 return processor.removed_predicates;
160
161 struct DrainProcessor<'a, 'tcx> {
162 infcx: &'a InferCtxt<'tcx>,
163 removed_predicates: Vec<PredicateObligation<'tcx>>,
164 }
165
166 impl<'tcx> ObligationProcessor for DrainProcessor<'_, 'tcx> {
167 type Obligation = PendingPredicateObligation<'tcx>;
168 type Error = !;
169 type OUT = Outcome<Self::Obligation, Self::Error>;
170
171 fn needs_process_obligation(&self, pending_obligation: &Self::Obligation) -> bool {
172 pending_obligation
173 .stalled_on
174 .iter()
175 .any(|&var| self.infcx.ty_or_const_infer_var_changed(var))
176 }
177
178 fn process_obligation(
179 &mut self,
180 pending_obligation: &mut PendingPredicateObligation<'tcx>,
181 ) -> ProcessResult<PendingPredicateObligation<'tcx>, !> {
182 assert!(self.needs_process_obligation(pending_obligation));
183 self.removed_predicates.push(pending_obligation.obligation.clone());
184 ProcessResult::Changed(vec![])
185 }
186
187 fn process_backedge<'c, I>(
188 &mut self,
189 cycle: I,
190 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
191 ) -> Result<(), !>
192 where
193 I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
194 {
195 self.removed_predicates.extend(cycle.map(|c| c.obligation.clone()));
196 Ok(())
197 }
198 }
1a4d82fc 199 }
c295e0f8 200
9ffffee4
FG
201 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
202 self.predicates.map_pending_obligations(|o| o.obligation.clone())
c295e0f8 203 }
1a4d82fc
JJ
204}
205
2b03887a
FG
206struct FulfillProcessor<'a, 'tcx> {
207 selcx: SelectionContext<'a, 'tcx>,
54a0048b
SL
208}
209
a2a8927a 210fn mk_pending(os: Vec<PredicateObligation<'_>>) -> Vec<PendingPredicateObligation<'_>> {
dfeec247
XL
211 os.into_iter()
212 .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
213 .collect()
94b46f34
XL
214}
215
2b03887a 216impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> {
a7813a04
XL
217 type Obligation = PendingPredicateObligation<'tcx>;
218 type Error = FulfillmentErrorCode<'tcx>;
2b03887a 219 type OUT = Outcome<Self::Obligation, Self::Error>;
7453a54e 220
353b0b11
FG
221 /// Compared to `needs_process_obligation` this and its callees
222 /// contain some optimizations that come at the price of false negatives.
223 ///
224 /// They
225 /// - reduce branching by covering only the most common case
226 /// - take a read-only view of the unification tables which allows skipping undo_log
227 /// construction.
228 /// - bail out on value-cache misses in ena to avoid pointer chasing
229 /// - hoist RefCell locking out of the loop
230 #[inline]
231 fn skippable_obligations<'b>(
232 &'b self,
233 it: impl Iterator<Item = &'b Self::Obligation>,
234 ) -> usize {
235 let is_unchanged = self.selcx.infcx.is_ty_infer_var_definitely_unchanged();
236
237 it.take_while(|o| match o.stalled_on.as_slice() {
238 [o] => is_unchanged(*o),
239 _ => false,
240 })
241 .count()
242 }
243
923072b8 244 /// Identifies whether a predicate obligation needs processing.
94b46f34 245 ///
9ffffee4
FG
246 /// This is always inlined because it has a single callsite and it is
247 /// called *very* frequently. Be careful modifying this code! Several
248 /// compile-time benchmarks are very sensitive to even small changes.
94b46f34 249 #[inline(always)]
923072b8 250 fn needs_process_obligation(&self, pending_obligation: &Self::Obligation) -> bool {
e74abb32
XL
251 // If we were stalled on some unresolved variables, first check whether
252 // any of them have been resolved; if not, don't bother doing more work
253 // yet.
9ffffee4
FG
254 let stalled_on = &pending_obligation.stalled_on;
255 match stalled_on.len() {
256 // This case is the hottest most of the time, being hit up to 99%
257 // of the time. `keccak` and `cranelift-codegen-0.82.1` are
258 // benchmarks that particularly stress this path.
259 1 => self.selcx.infcx.ty_or_const_infer_var_changed(stalled_on[0]),
260
261 // In this case we haven't changed, but wish to make a change. Note
262 // that this is a special case, and is not equivalent to the `_`
263 // case below, which would return `false` for an empty `stalled_on`
264 // vector.
265 //
266 // This case is usually hit only 1% of the time or less, though it
267 // reaches 20% in `wasmparser-0.101.0`.
268 0 => true,
269
270 // This case is usually hit only 1% of the time or less, though it
271 // reaches 95% in `mime-0.3.16`, 64% in `wast-54.0.0`, and 12% in
272 // `inflate-0.4.5`.
273 //
274 // The obvious way of writing this, with a call to `any()` and no
275 // closure, is currently slower than this version.
276 _ => (|| {
277 for &infer_var in stalled_on {
278 if self.selcx.infcx.ty_or_const_infer_var_changed(infer_var) {
279 return true;
e74abb32 280 }
9ffffee4
FG
281 }
282 false
283 })(),
1b1a35ee
XL
284 }
285 }
e74abb32 286
923072b8
FG
287 /// Processes a predicate obligation and returns either:
288 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
289 /// - `Unchanged` if we don't have enough info to be sure
290 /// - `Error(e)` if the predicate does not hold
291 ///
292 /// This is called much less often than `needs_process_obligation`, so we
293 /// never inline it.
1b1a35ee 294 #[inline(never)]
064997fb 295 #[instrument(level = "debug", skip(self, pending_obligation))]
923072b8 296 fn process_obligation(
1b1a35ee
XL
297 &mut self,
298 pending_obligation: &mut PendingPredicateObligation<'tcx>,
299 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
e74abb32
XL
300 pending_obligation.stalled_on.truncate(0);
301
94b46f34 302 let obligation = &mut pending_obligation.obligation;
7453a54e 303
064997fb 304 debug!(?obligation, "pre-resolve");
5e7ed085 305
2b03887a 306 if obligation.predicate.has_non_region_infer() {
487cf647 307 obligation.predicate = self.selcx.infcx.resolve_vars_if_possible(obligation.predicate);
7453a54e 308 }
1a4d82fc 309
923072b8
FG
310 let obligation = &pending_obligation.obligation;
311
487cf647 312 let infcx = self.selcx.infcx;
f9f354fc 313
5e7ed085
FG
314 if obligation.predicate.has_projections() {
315 let mut obligations = Vec::new();
316 let predicate = crate::traits::project::try_normalize_with_depth_to(
2b03887a 317 &mut self.selcx,
5e7ed085
FG
318 obligation.param_env,
319 obligation.cause.clone(),
320 obligation.recursion_depth + 1,
321 obligation.predicate,
322 &mut obligations,
323 );
324 if predicate != obligation.predicate {
487cf647 325 obligations.push(obligation.with(infcx.tcx, predicate));
5e7ed085
FG
326 return ProcessResult::Changed(mk_pending(obligations));
327 }
328 }
5869c6ff
XL
329 let binder = obligation.predicate.kind();
330 match binder.no_bound_vars() {
331 None => match binder.skip_binder() {
3dfed10e
XL
332 // Evaluation will discard candidates using the leak check.
333 // This means we need to pass it the bound version of our
334 // predicate.
487cf647
FG
335 ty::PredicateKind::Clause(ty::Clause::Trait(trait_ref)) => {
336 let trait_obligation = obligation.with(infcx.tcx, binder.rebind(trait_ref));
3dfed10e
XL
337
338 self.process_trait_obligation(
339 obligation,
340 trait_obligation,
341 &mut pending_obligation.stalled_on,
342 )
3b2f2976 343 }
487cf647
FG
344 ty::PredicateKind::Clause(ty::Clause::Projection(data)) => {
345 let project_obligation = obligation.with(infcx.tcx, binder.rebind(data));
7453a54e 346
3dfed10e 347 self.process_projection_obligation(
136023e0 348 obligation,
3dfed10e
XL
349 project_obligation,
350 &mut pending_obligation.stalled_on,
351 )
352 }
487cf647
FG
353 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(_))
354 | ty::PredicateKind::Clause(ty::Clause::TypeOutlives(_))
9ffffee4 355 | ty::PredicateKind::Clause(ty::Clause::ConstArgHasType(..))
5869c6ff
XL
356 | ty::PredicateKind::WellFormed(_)
357 | ty::PredicateKind::ObjectSafe(_)
358 | ty::PredicateKind::ClosureKind(..)
359 | ty::PredicateKind::Subtype(_)
94222f64 360 | ty::PredicateKind::Coerce(_)
5869c6ff
XL
361 | ty::PredicateKind::ConstEvaluatable(..)
362 | ty::PredicateKind::ConstEquate(..) => {
c295e0f8 363 let pred =
9ffffee4 364 ty::Binder::dummy(infcx.instantiate_binder_with_placeholders(binder));
487cf647 365 ProcessResult::Changed(mk_pending(vec![obligation.with(infcx.tcx, pred)]))
3dfed10e 366 }
487cf647 367 ty::PredicateKind::Ambiguous => ProcessResult::Unchanged,
5869c6ff 368 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
1b1a35ee
XL
369 bug!("TypeWellFormedFromEnv is only used for Chalk")
370 }
353b0b11
FG
371 ty::PredicateKind::AliasRelate(..) => {
372 bug!("AliasRelate is only used for new solver")
9ffffee4 373 }
3dfed10e 374 },
5869c6ff 375 Some(pred) => match pred {
487cf647
FG
376 ty::PredicateKind::Clause(ty::Clause::Trait(data)) => {
377 let trait_obligation = obligation.with(infcx.tcx, Binder::dummy(data));
3dfed10e
XL
378
379 self.process_trait_obligation(
380 obligation,
381 trait_obligation,
382 &mut pending_obligation.stalled_on,
383 )
384 }
94b46f34 385
487cf647 386 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(data)) => {
2b03887a 387 if infcx.considering_regions {
064997fb 388 infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data));
94b46f34 389 }
064997fb
FG
390
391 ProcessResult::Changed(vec![])
3dfed10e 392 }
5bcae85e 393
487cf647
FG
394 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
395 t_a,
396 r_b,
397 ))) => {
064997fb
FG
398 if infcx.considering_regions {
399 infcx.register_region_obligation_with_cause(t_a, r_b, &obligation.cause);
94b46f34 400 }
3dfed10e 401 ProcessResult::Changed(vec![])
1a4d82fc 402 }
1a4d82fc 403
487cf647
FG
404 ty::PredicateKind::Clause(ty::Clause::Projection(ref data)) => {
405 let project_obligation = obligation.with(infcx.tcx, Binder::dummy(*data));
3dfed10e
XL
406
407 self.process_projection_obligation(
136023e0 408 obligation,
3dfed10e
XL
409 project_obligation,
410 &mut pending_obligation.stalled_on,
411 )
94b46f34 412 }
1a4d82fc 413
5869c6ff 414 ty::PredicateKind::ObjectSafe(trait_def_id) => {
9ffffee4 415 if !self.selcx.tcx().check_is_object_safe(trait_def_id) {
3dfed10e
XL
416 ProcessResult::Error(CodeSelectionError(Unimplemented))
417 } else {
94b46f34 418 ProcessResult::Changed(vec![])
ff7c6d11 419 }
c1a9b12d 420 }
1a4d82fc 421
5869c6ff 422 ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
487cf647 423 match self.selcx.infcx.closure_kind(closure_substs) {
3dfed10e
XL
424 Some(closure_kind) => {
425 if closure_kind.extends(kind) {
426 ProcessResult::Changed(vec![])
427 } else {
428 ProcessResult::Error(CodeSelectionError(Unimplemented))
429 }
430 }
431 None => ProcessResult::Unchanged,
94b46f34 432 }
1a4d82fc 433 }
1a4d82fc 434
5869c6ff 435 ty::PredicateKind::WellFormed(arg) => {
3dfed10e 436 match wf::obligations(
487cf647 437 self.selcx.infcx,
3dfed10e
XL
438 obligation.param_env,
439 obligation.cause.body_id,
29967ef6 440 obligation.recursion_depth + 1,
3dfed10e
XL
441 arg,
442 obligation.cause.span,
443 ) {
444 None => {
445 pending_obligation.stalled_on =
446 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
447 ProcessResult::Unchanged
94b46f34 448 }
3dfed10e 449 Some(os) => ProcessResult::Changed(mk_pending(os)),
94b46f34 450 }
a7813a04 451 }
a7813a04 452
5869c6ff 453 ty::PredicateKind::Subtype(subtype) => {
487cf647 454 match self.selcx.infcx.subtype_predicate(
3dfed10e
XL
455 &obligation.cause,
456 obligation.param_env,
457 Binder::dummy(subtype),
458 ) {
f2b60f7d 459 Err((a, b)) => {
3dfed10e 460 // None means that both are unresolved.
f2b60f7d
FG
461 pending_obligation.stalled_on =
462 vec![TyOrConstInferVar::Ty(a), TyOrConstInferVar::Ty(b)];
3dfed10e
XL
463 ProcessResult::Unchanged
464 }
f2b60f7d
FG
465 Ok(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
466 Ok(Err(err)) => {
3dfed10e
XL
467 let expected_found =
468 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
469 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
470 expected_found,
471 err,
472 ))
473 }
94b46f34 474 }
e9174d1e 475 }
cc61c64b 476
94222f64 477 ty::PredicateKind::Coerce(coerce) => {
487cf647 478 match self.selcx.infcx.coerce_predicate(
94222f64
XL
479 &obligation.cause,
480 obligation.param_env,
481 Binder::dummy(coerce),
482 ) {
f2b60f7d 483 Err((a, b)) => {
94222f64 484 // None means that both are unresolved.
f2b60f7d
FG
485 pending_obligation.stalled_on =
486 vec![TyOrConstInferVar::Ty(a), TyOrConstInferVar::Ty(b)];
94222f64
XL
487 ProcessResult::Unchanged
488 }
f2b60f7d
FG
489 Ok(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
490 Ok(Err(err)) => {
94222f64
XL
491 let expected_found = ExpectedFound::new(false, coerce.a, coerce.b);
492 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
493 expected_found,
494 err,
495 ))
496 }
497 }
498 }
499
500 ty::PredicateKind::ConstEvaluatable(uv) => {
1b1a35ee 501 match const_evaluatable::is_const_evaluatable(
487cf647 502 self.selcx.infcx,
94222f64 503 uv,
1b1a35ee
XL
504 obligation.param_env,
505 obligation.cause.span,
3dfed10e 506 ) {
1b1a35ee 507 Ok(()) => ProcessResult::Changed(vec![]),
cdc7bbd5 508 Err(NotConstEvaluatable::MentionsInfer) => {
6a06907d
XL
509 pending_obligation.stalled_on.clear();
510 pending_obligation.stalled_on.extend(
2b03887a 511 uv.walk().filter_map(TyOrConstInferVar::maybe_from_generic_arg),
6a06907d 512 );
1b1a35ee
XL
513 ProcessResult::Unchanged
514 }
cdc7bbd5
XL
515 Err(
516 e @ NotConstEvaluatable::MentionsParam
517 | e @ NotConstEvaluatable::Error(_),
518 ) => ProcessResult::Error(CodeSelectionError(
519 SelectionError::NotConstEvaluatable(e),
520 )),
94b46f34 521 }
cc61c64b 522 }
ea8adc8c 523
5869c6ff 524 ty::PredicateKind::ConstEquate(c1, c2) => {
487cf647 525 let tcx = self.selcx.tcx();
2b03887a 526 assert!(
487cf647 527 tcx.features().generic_const_exprs,
2b03887a
FG
528 "`ConstEquate` without a feature gate: {c1:?} {c2:?}",
529 );
2b03887a
FG
530 // FIXME: we probably should only try to unify abstract constants
531 // if the constants depend on generic parameters.
532 //
533 // Let's just see where this breaks :shrug:
2b03887a 534 {
487cf647
FG
535 let c1 = tcx.expand_abstract_consts(c1);
536 let c2 = tcx.expand_abstract_consts(c2);
537 debug!("equating consts:\nc1= {:?}\nc2= {:?}", c1, c2);
538
539 use rustc_hir::def::DefKind;
540 use ty::ConstKind::Unevaluated;
541 match (c1.kind(), c2.kind()) {
542 (Unevaluated(a), Unevaluated(b))
543 if a.def.did == b.def.did
544 && tcx.def_kind(a.def.did) == DefKind::AssocConst =>
545 {
546 if let Ok(new_obligations) = infcx
547 .at(&obligation.cause, obligation.param_env)
548 .trace(c1, c2)
353b0b11 549 .eq(DefineOpaqueTypes::No, a.substs, b.substs)
487cf647
FG
550 {
551 return ProcessResult::Changed(mk_pending(
552 new_obligations.into_obligations(),
553 ));
554 }
555 }
556 (_, Unevaluated(_)) | (Unevaluated(_), _) => (),
557 (_, _) => {
353b0b11
FG
558 if let Ok(new_obligations) = infcx
559 .at(&obligation.cause, obligation.param_env)
560 .eq(DefineOpaqueTypes::No, c1, c2)
487cf647
FG
561 {
562 return ProcessResult::Changed(mk_pending(
563 new_obligations.into_obligations(),
564 ));
565 }
566 }
1b1a35ee
XL
567 }
568 }
3dfed10e
XL
569
570 let stalled_on = &mut pending_obligation.stalled_on;
571
5099ac24 572 let mut evaluate = |c: Const<'tcx>| {
923072b8 573 if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() {
487cf647 574 match self.selcx.infcx.try_const_eval_resolve(
3dfed10e 575 obligation.param_env,
cdc7bbd5 576 unevaluated,
923072b8 577 c.ty(),
3dfed10e
XL
578 Some(obligation.cause.span),
579 ) {
923072b8
FG
580 Ok(val) => Ok(val),
581 Err(e) => match e {
582 ErrorHandled::TooGeneric => {
583 stalled_on.extend(
584 unevaluated.substs.iter().filter_map(
585 TyOrConstInferVar::maybe_from_generic_arg,
586 ),
587 );
588 Err(ErrorHandled::TooGeneric)
589 }
590 _ => Err(e),
591 },
f9f354fc 592 }
3dfed10e
XL
593 } else {
594 Ok(c)
f9f354fc 595 }
3dfed10e
XL
596 };
597
598 match (evaluate(c1), evaluate(c2)) {
599 (Ok(c1), Ok(c2)) => {
353b0b11
FG
600 match self.selcx.infcx.at(&obligation.cause, obligation.param_env).eq(
601 DefineOpaqueTypes::No,
602 c1,
603 c2,
604 ) {
487cf647
FG
605 Ok(inf_ok) => {
606 ProcessResult::Changed(mk_pending(inf_ok.into_obligations()))
607 }
3dfed10e
XL
608 Err(err) => ProcessResult::Error(
609 FulfillmentErrorCode::CodeConstEquateError(
610 ExpectedFound::new(true, c1, c2),
611 err,
612 ),
613 ),
f9f354fc
XL
614 }
615 }
5e7ed085
FG
616 (Err(ErrorHandled::Reported(reported)), _)
617 | (_, Err(ErrorHandled::Reported(reported))) => ProcessResult::Error(
cdc7bbd5 618 CodeSelectionError(SelectionError::NotConstEvaluatable(
5e7ed085 619 NotConstEvaluatable::Error(reported),
cdc7bbd5
XL
620 )),
621 ),
3dfed10e 622 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
2b03887a 623 if c1.has_non_region_infer() || c2.has_non_region_infer() {
17df50a5
XL
624 ProcessResult::Unchanged
625 } else {
626 // Two different constants using generic parameters ~> error.
627 let expected_found = ExpectedFound::new(true, c1, c2);
628 ProcessResult::Error(FulfillmentErrorCode::CodeConstEquateError(
629 expected_found,
630 TypeError::ConstMismatch(expected_found),
631 ))
632 }
3dfed10e 633 }
f9f354fc
XL
634 }
635 }
487cf647 636 ty::PredicateKind::Ambiguous => ProcessResult::Unchanged,
5869c6ff 637 ty::PredicateKind::TypeWellFormedFromEnv(..) => {
1b1a35ee
XL
638 bug!("TypeWellFormedFromEnv is only used for Chalk")
639 }
353b0b11
FG
640 ty::PredicateKind::AliasRelate(..) => {
641 bug!("AliasRelate is only used for new solver")
9ffffee4
FG
642 }
643 ty::PredicateKind::Clause(ty::Clause::ConstArgHasType(ct, ty)) => {
353b0b11
FG
644 match self.selcx.infcx.at(&obligation.cause, obligation.param_env).eq(
645 DefineOpaqueTypes::No,
646 ct.ty(),
647 ty,
648 ) {
9ffffee4
FG
649 Ok(inf_ok) => ProcessResult::Changed(mk_pending(inf_ok.into_obligations())),
650 Err(_) => ProcessResult::Error(FulfillmentErrorCode::CodeSelectionError(
651 SelectionError::Unimplemented,
652 )),
653 }
654 }
3dfed10e 655 },
ea8adc8c 656 }
1a4d82fc 657 }
94b46f34 658
f2b60f7d 659 #[inline(never)]
923072b8
FG
660 fn process_backedge<'c, I>(
661 &mut self,
662 cycle: I,
663 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
2b03887a
FG
664 ) -> Result<(), FulfillmentErrorCode<'tcx>>
665 where
923072b8
FG
666 I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
667 {
668 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
669 debug!("process_child_obligations: coinductive match");
2b03887a 670 Ok(())
923072b8
FG
671 } else {
672 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
2b03887a 673 Err(FulfillmentErrorCode::CodeCycle(cycle))
923072b8
FG
674 }
675 }
676}
677
2b03887a 678impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> {
29967ef6 679 #[instrument(level = "debug", skip(self, obligation, stalled_on))]
3dfed10e
XL
680 fn process_trait_obligation(
681 &mut self,
682 obligation: &PredicateObligation<'tcx>,
683 trait_obligation: TraitObligation<'tcx>,
684 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
685 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
487cf647 686 let infcx = self.selcx.infcx;
5099ac24 687 if obligation.predicate.is_global() {
3dfed10e
XL
688 // no type variables present, can use evaluation for better caching.
689 // FIXME: consider caching errors too.
a2a8927a 690 if infcx.predicate_must_hold_considering_regions(obligation) {
3dfed10e 691 debug!(
29967ef6
XL
692 "selecting trait at depth {} evaluated to holds",
693 obligation.recursion_depth
3dfed10e
XL
694 );
695 return ProcessResult::Changed(vec![]);
696 }
697 }
698
699 match self.selcx.select(&trait_obligation) {
700 Ok(Some(impl_source)) => {
29967ef6 701 debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth);
3dfed10e
XL
702 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
703 }
704 Ok(None) => {
29967ef6 705 debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth);
3dfed10e
XL
706
707 // This is a bit subtle: for the most part, the
708 // only reason we can fail to make progress on
709 // trait selection is because we don't have enough
710 // information about the types in the trait.
6a06907d
XL
711 stalled_on.clear();
712 stalled_on.extend(substs_infer_vars(
2b03887a 713 &self.selcx,
6a06907d
XL
714 trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs),
715 ));
3dfed10e
XL
716
717 debug!(
718 "process_predicate: pending obligation {:?} now stalled on {:?}",
fc512014 719 infcx.resolve_vars_if_possible(obligation.clone()),
3dfed10e
XL
720 stalled_on
721 );
722
723 ProcessResult::Unchanged
724 }
725 Err(selection_err) => {
6a06907d 726 debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth);
3dfed10e
XL
727
728 ProcessResult::Error(CodeSelectionError(selection_err))
729 }
730 }
731 }
732
733 fn process_projection_obligation(
734 &mut self,
136023e0 735 obligation: &PredicateObligation<'tcx>,
3dfed10e
XL
736 project_obligation: PolyProjectionObligation<'tcx>,
737 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
738 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
739 let tcx = self.selcx.tcx();
136023e0 740
5099ac24 741 if obligation.predicate.is_global() {
136023e0
XL
742 // no type variables present, can use evaluation for better caching.
743 // FIXME: consider caching errors too.
487cf647 744 if self.selcx.infcx.predicate_must_hold_considering_regions(obligation) {
a2a8927a
XL
745 if let Some(key) = ProjectionCacheKey::from_poly_projection_predicate(
746 &mut self.selcx,
747 project_obligation.predicate,
748 ) {
749 // If `predicate_must_hold_considering_regions` succeeds, then we've
750 // evaluated all sub-obligations. We can therefore mark the 'root'
751 // obligation as complete, and skip evaluating sub-obligations.
752 self.selcx
487cf647 753 .infcx
a2a8927a
XL
754 .inner
755 .borrow_mut()
756 .projection_cache()
757 .complete(key, EvaluationResult::EvaluatedToOk);
758 }
136023e0
XL
759 return ProcessResult::Changed(vec![]);
760 } else {
064997fb 761 debug!("Does NOT hold: {:?}", obligation);
136023e0
XL
762 }
763 }
764
2b03887a 765 match project::poly_project_and_unify_type(&mut self.selcx, &project_obligation) {
5e7ed085
FG
766 ProjectAndUnifyResult::Holds(os) => ProcessResult::Changed(mk_pending(os)),
767 ProjectAndUnifyResult::FailedNormalization => {
6a06907d
XL
768 stalled_on.clear();
769 stalled_on.extend(substs_infer_vars(
2b03887a 770 &self.selcx,
6a06907d
XL
771 project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs),
772 ));
3dfed10e
XL
773 ProcessResult::Unchanged
774 }
775 // Let the caller handle the recursion
5e7ed085 776 ProjectAndUnifyResult::Recursive => ProcessResult::Changed(mk_pending(vec![
487cf647 777 project_obligation.with(tcx, project_obligation.predicate),
3dfed10e 778 ])),
5e7ed085
FG
779 ProjectAndUnifyResult::MismatchedProjectionTypes(e) => {
780 ProcessResult::Error(CodeProjectionError(e))
781 }
3dfed10e
XL
782 }
783 }
784}
785
6a06907d
XL
786/// Returns the set of inference variables contained in `substs`.
787fn substs_infer_vars<'a, 'tcx>(
2b03887a 788 selcx: &SelectionContext<'a, 'tcx>,
cdc7bbd5 789 substs: ty::Binder<'tcx, SubstsRef<'tcx>>,
6a06907d 790) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> {
ba9703b0 791 selcx
487cf647 792 .infcx
6a06907d
XL
793 .resolve_vars_if_possible(substs)
794 .skip_binder() // ok because this check doesn't care about regions
ba9703b0 795 .iter()
2b03887a 796 .filter(|arg| arg.has_non_region_infer())
5099ac24
FG
797 .flat_map(|arg| {
798 let mut walker = arg.walk();
6a06907d 799 while let Some(c) = walker.next() {
2b03887a 800 if !c.has_non_region_infer() {
6a06907d
XL
801 walker.visited.remove(&c);
802 walker.skip_current_subtree();
803 }
804 }
805 walker.visited.into_iter()
806 })
ba9703b0 807 .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
1a4d82fc
JJ
808}
809
7453a54e 810fn to_fulfillment_error<'tcx>(
dfeec247
XL
811 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
812) -> FulfillmentError<'tcx> {
136023e0
XL
813 let mut iter = error.backtrace.into_iter();
814 let obligation = iter.next().unwrap().obligation;
815 // The root obligation is the last item in the backtrace - if there's only
816 // one item, then it's the same as the main obligation
817 let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation);
818 FulfillmentError::new(obligation, error.error, root_obligation)
7453a54e 819}