]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/fulfill.rs
Rollup merge of #67543 - JohnTitor:regression-tests, r=Centril
[rust.git] / src / librustc / traits / fulfill.rs
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;
8
9 use super::engine::{TraitEngine, TraitEngineExt};
10 use super::project;
11 use super::select::SelectionContext;
12 use super::CodeAmbiguity;
13 use super::CodeProjectionError;
14 use super::CodeSelectionError;
15 use super::{ConstEvalFailure, Unimplemented};
16 use super::{FulfillmentError, FulfillmentErrorCode};
17 use super::{ObligationCause, PredicateObligation};
18
19 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
20     type Predicate = ty::Predicate<'tcx>;
21
22     fn as_predicate(&self) -> &Self::Predicate {
23         &self.obligation.predicate
24     }
25 }
26
27 /// The fulfillment context is used to drive trait resolution. It
28 /// consists of a list of obligations that must be (eventually)
29 /// satisfied. The job is to track which are satisfied, which yielded
30 /// errors, and which are still pending. At any point, users can call
31 /// `select_where_possible`, and the fulfillment context will try to do
32 /// selection, retaining only those obligations that remain
33 /// ambiguous. This may be helpful in pushing type inference
34 /// along. Once all type inference constraints have been generated, the
35 /// method `select_all_or_error` can be used to report any remaining
36 /// ambiguous cases as errors.
37 pub struct FulfillmentContext<'tcx> {
38     // A list of all obligations that have been registered with this
39     // fulfillment context.
40     predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
41     // Should this fulfillment context register type-lives-for-region
42     // obligations on its parent infcx? In some cases, region
43     // obligations are either already known to hold (normalization) or
44     // hopefully verifed elsewhere (type-impls-bound), and therefore
45     // should not be checked.
46     //
47     // Note that if we are normalizing a type that we already
48     // know is well-formed, there should be no harm setting this
49     // to true - all the region variables should be determinable
50     // using the RFC 447 rules, which don't depend on
51     // type-lives-for-region constraints, and because the type
52     // is well-formed, the constraints should hold.
53     register_region_obligations: bool,
54     // Is it OK to register obligations into this infcx inside
55     // an infcx snapshot?
56     //
57     // The "primary fulfillment" in many cases in typeck lives
58     // outside of any snapshot, so any use of it inside a snapshot
59     // will lead to trouble and therefore is checked against, but
60     // other fulfillment contexts sometimes do live inside of
61     // a snapshot (they don't *straddle* a snapshot, so there
62     // is no trouble there).
63     usable_in_snapshot: bool,
64 }
65
66 #[derive(Clone, Debug)]
67 pub struct PendingPredicateObligation<'tcx> {
68     pub obligation: PredicateObligation<'tcx>,
69     pub stalled_on: Vec<ty::InferTy>,
70 }
71
72 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
73 #[cfg(target_arch = "x86_64")]
74 static_assert_size!(PendingPredicateObligation<'_>, 136);
75
76 impl<'a, 'tcx> FulfillmentContext<'tcx> {
77     /// Creates a new fulfillment context.
78     pub fn new() -> FulfillmentContext<'tcx> {
79         FulfillmentContext {
80             predicates: ObligationForest::new(),
81             register_region_obligations: true,
82             usable_in_snapshot: false,
83         }
84     }
85
86     pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
87         FulfillmentContext {
88             predicates: ObligationForest::new(),
89             register_region_obligations: true,
90             usable_in_snapshot: true,
91         }
92     }
93
94     pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
95         FulfillmentContext {
96             predicates: ObligationForest::new(),
97             register_region_obligations: false,
98             usable_in_snapshot: false,
99         }
100     }
101
102     /// Attempts to select obligations using `selcx`.
103     fn select(
104         &mut self,
105         selcx: &mut SelectionContext<'a, 'tcx>,
106     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
107         debug!("select(obligation-forest-size={})", self.predicates.len());
108
109         let mut errors = Vec::new();
110
111         loop {
112             debug!("select: starting another iteration");
113
114             // Process pending obligations.
115             let outcome = self.predicates.process_obligations(
116                 &mut FulfillProcessor {
117                     selcx,
118                     register_region_obligations: self.register_region_obligations,
119                 },
120                 DoCompleted::No,
121             );
122             debug!("select: outcome={:#?}", outcome);
123
124             // FIXME: if we kept the original cache key, we could mark projection
125             // obligations as complete for the projection cache here.
126
127             errors.extend(outcome.errors.into_iter().map(|e| to_fulfillment_error(e)));
128
129             // If nothing new was added, no need to keep looping.
130             if outcome.stalled {
131                 break;
132             }
133         }
134
135         debug!(
136             "select({} predicates remaining, {} errors) done",
137             self.predicates.len(),
138             errors.len()
139         );
140
141         if errors.is_empty() { Ok(()) } else { Err(errors) }
142     }
143 }
144
145 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
146     /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
147     /// creating a fresh type variable `$0` as well as a projection
148     /// predicate `<SomeType as SomeTrait>::X == $0`. When the
149     /// inference engine runs, it will attempt to find an impl of
150     /// `SomeTrait` or a where-clause that lets us unify `$0` with
151     /// something concrete. If this fails, we'll unify `$0` with
152     /// `projection_ty` again.
153     fn normalize_projection_type(
154         &mut self,
155         infcx: &InferCtxt<'_, 'tcx>,
156         param_env: ty::ParamEnv<'tcx>,
157         projection_ty: ty::ProjectionTy<'tcx>,
158         cause: ObligationCause<'tcx>,
159     ) -> Ty<'tcx> {
160         debug!("normalize_projection_type(projection_ty={:?})", projection_ty);
161
162         debug_assert!(!projection_ty.has_escaping_bound_vars());
163
164         // FIXME(#20304) -- cache
165
166         let mut selcx = SelectionContext::new(infcx);
167         let mut obligations = vec![];
168         let normalized_ty = project::normalize_projection_type(
169             &mut selcx,
170             param_env,
171             projection_ty,
172             cause,
173             0,
174             &mut obligations,
175         );
176         self.register_predicate_obligations(infcx, obligations);
177
178         debug!("normalize_projection_type: result={:?}", normalized_ty);
179
180         normalized_ty
181     }
182
183     fn register_predicate_obligation(
184         &mut self,
185         infcx: &InferCtxt<'_, 'tcx>,
186         obligation: PredicateObligation<'tcx>,
187     ) {
188         // this helps to reduce duplicate errors, as well as making
189         // debug output much nicer to read and so on.
190         let obligation = infcx.resolve_vars_if_possible(&obligation);
191
192         debug!("register_predicate_obligation(obligation={:?})", obligation);
193
194         assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
195
196         self.predicates
197             .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
198     }
199
200     fn select_all_or_error(
201         &mut self,
202         infcx: &InferCtxt<'_, 'tcx>,
203     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
204         self.select_where_possible(infcx)?;
205
206         let errors: Vec<_> = self
207             .predicates
208             .to_errors(CodeAmbiguity)
209             .into_iter()
210             .map(|e| to_fulfillment_error(e))
211             .collect();
212         if errors.is_empty() { Ok(()) } else { Err(errors) }
213     }
214
215     fn select_where_possible(
216         &mut self,
217         infcx: &InferCtxt<'_, 'tcx>,
218     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
219         let mut selcx = SelectionContext::new(infcx);
220         self.select(&mut selcx)
221     }
222
223     fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
224         self.predicates.map_pending_obligations(|o| o.obligation.clone())
225     }
226 }
227
228 struct FulfillProcessor<'a, 'b, 'tcx> {
229     selcx: &'a mut SelectionContext<'b, 'tcx>,
230     register_region_obligations: bool,
231 }
232
233 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
234     os.into_iter()
235         .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
236         .collect()
237 }
238
239 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
240     type Obligation = PendingPredicateObligation<'tcx>;
241     type Error = FulfillmentErrorCode<'tcx>;
242
243     /// Processes a predicate obligation and returns either:
244     /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
245     /// - `Unchanged` if we don't have enough info to be sure
246     /// - `Error(e)` if the predicate does not hold
247     ///
248     /// This is always inlined, despite its size, because it has a single
249     /// callsite and it is called *very* frequently.
250     #[inline(always)]
251     fn process_obligation(
252         &mut self,
253         pending_obligation: &mut Self::Obligation,
254     ) -> ProcessResult<Self::Obligation, Self::Error> {
255         // If we were stalled on some unresolved variables, first check whether
256         // any of them have been resolved; if not, don't bother doing more work
257         // yet.
258         let change = match pending_obligation.stalled_on.len() {
259             // Match arms are in order of frequency, which matters because this
260             // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
261             1 => {
262                 let infer = pending_obligation.stalled_on[0];
263                 ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer)
264             }
265             0 => {
266                 // In this case we haven't changed, but wish to make a change.
267                 true
268             }
269             _ => {
270                 // This `for` loop was once a call to `all()`, but this lower-level
271                 // form was a perf win. See #64545 for details.
272                 (|| {
273                     for &infer in &pending_obligation.stalled_on {
274                         if ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer) {
275                             return true;
276                         }
277                     }
278                     false
279                 })()
280             }
281         };
282
283         if !change {
284             debug!(
285                 "process_predicate: pending obligation {:?} still stalled on {:?}",
286                 self.selcx.infcx().resolve_vars_if_possible(&pending_obligation.obligation),
287                 pending_obligation.stalled_on
288             );
289             return ProcessResult::Unchanged;
290         }
291
292         // This part of the code is much colder.
293
294         pending_obligation.stalled_on.truncate(0);
295
296         let obligation = &mut pending_obligation.obligation;
297
298         if obligation.predicate.has_infer_types() {
299             obligation.predicate =
300                 self.selcx.infcx().resolve_vars_if_possible(&obligation.predicate);
301         }
302
303         debug!("process_obligation: obligation = {:?} cause = {:?}", obligation, obligation.cause);
304
305         fn infer_ty(ty: Ty<'tcx>) -> ty::InferTy {
306             match ty.kind {
307                 ty::Infer(infer) => infer,
308                 _ => panic!(),
309             }
310         }
311
312         match obligation.predicate {
313             ty::Predicate::Trait(ref data) => {
314                 let trait_obligation = obligation.with(data.clone());
315
316                 if data.is_global() {
317                     // no type variables present, can use evaluation for better caching.
318                     // FIXME: consider caching errors too.
319                     if self.selcx.infcx().predicate_must_hold_considering_regions(&obligation) {
320                         debug!(
321                             "selecting trait `{:?}` at depth {} evaluated to holds",
322                             data, obligation.recursion_depth
323                         );
324                         return ProcessResult::Changed(vec![]);
325                     }
326                 }
327
328                 match self.selcx.select(&trait_obligation) {
329                     Ok(Some(vtable)) => {
330                         debug!(
331                             "selecting trait `{:?}` at depth {} yielded Ok(Some)",
332                             data, obligation.recursion_depth
333                         );
334                         ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
335                     }
336                     Ok(None) => {
337                         debug!(
338                             "selecting trait `{:?}` at depth {} yielded Ok(None)",
339                             data, obligation.recursion_depth
340                         );
341
342                         // This is a bit subtle: for the most part, the
343                         // only reason we can fail to make progress on
344                         // trait selection is because we don't have enough
345                         // information about the types in the trait. One
346                         // exception is that we sometimes haven't decided
347                         // what kind of closure a closure is. *But*, in
348                         // that case, it turns out, the type of the
349                         // closure will also change, because the closure
350                         // also includes references to its upvars as part
351                         // of its type, and those types are resolved at
352                         // the same time.
353                         //
354                         // FIXME(#32286) logic seems false if no upvars
355                         pending_obligation.stalled_on =
356                             trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
357
358                         debug!(
359                             "process_predicate: pending obligation {:?} now stalled on {:?}",
360                             self.selcx.infcx().resolve_vars_if_possible(obligation),
361                             pending_obligation.stalled_on
362                         );
363
364                         ProcessResult::Unchanged
365                     }
366                     Err(selection_err) => {
367                         info!(
368                             "selecting trait `{:?}` at depth {} yielded Err",
369                             data, obligation.recursion_depth
370                         );
371
372                         ProcessResult::Error(CodeSelectionError(selection_err))
373                     }
374                 }
375             }
376
377             ty::Predicate::RegionOutlives(ref binder) => {
378                 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
379                     Ok(()) => ProcessResult::Changed(vec![]),
380                     Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
381                 }
382             }
383
384             ty::Predicate::TypeOutlives(ref binder) => {
385                 // Check if there are higher-ranked vars.
386                 match binder.no_bound_vars() {
387                     // If there are, inspect the underlying type further.
388                     None => {
389                         // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
390                         let binder = binder.map_bound_ref(|pred| pred.0);
391
392                         // Check if the type has any bound vars.
393                         match binder.no_bound_vars() {
394                             // If so, this obligation is an error (for now). Eventually we should be
395                             // able to support additional cases here, like `for<'a> &'a str: 'a`.
396                             // NOTE: this is duplicate-implemented between here and fulfillment.
397                             None => ProcessResult::Error(CodeSelectionError(Unimplemented)),
398                             // Otherwise, we have something of the form
399                             // `for<'a> T: 'a where 'a not in T`, which we can treat as
400                             // `T: 'static`.
401                             Some(t_a) => {
402                                 let r_static = self.selcx.tcx().lifetimes.re_static;
403                                 if self.register_region_obligations {
404                                     self.selcx.infcx().register_region_obligation_with_cause(
405                                         t_a,
406                                         r_static,
407                                         &obligation.cause,
408                                     );
409                                 }
410                                 ProcessResult::Changed(vec![])
411                             }
412                         }
413                     }
414                     // If there aren't, register the obligation.
415                     Some(ty::OutlivesPredicate(t_a, r_b)) => {
416                         if self.register_region_obligations {
417                             self.selcx.infcx().register_region_obligation_with_cause(
418                                 t_a,
419                                 r_b,
420                                 &obligation.cause,
421                             );
422                         }
423                         ProcessResult::Changed(vec![])
424                     }
425                 }
426             }
427
428             ty::Predicate::Projection(ref data) => {
429                 let project_obligation = obligation.with(data.clone());
430                 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
431                     Ok(None) => {
432                         let tcx = self.selcx.tcx();
433                         pending_obligation.stalled_on =
434                             trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
435                         ProcessResult::Unchanged
436                     }
437                     Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
438                     Err(e) => ProcessResult::Error(CodeProjectionError(e)),
439                 }
440             }
441
442             ty::Predicate::ObjectSafe(trait_def_id) => {
443                 if !self.selcx.tcx().is_object_safe(trait_def_id) {
444                     ProcessResult::Error(CodeSelectionError(Unimplemented))
445                 } else {
446                     ProcessResult::Changed(vec![])
447                 }
448             }
449
450             ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
451                 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
452                     Some(closure_kind) => {
453                         if closure_kind.extends(kind) {
454                             ProcessResult::Changed(vec![])
455                         } else {
456                             ProcessResult::Error(CodeSelectionError(Unimplemented))
457                         }
458                     }
459                     None => ProcessResult::Unchanged,
460                 }
461             }
462
463             ty::Predicate::WellFormed(ty) => {
464                 match ty::wf::obligations(
465                     self.selcx.infcx(),
466                     obligation.param_env,
467                     obligation.cause.body_id,
468                     ty,
469                     obligation.cause.span,
470                 ) {
471                     None => {
472                         pending_obligation.stalled_on = vec![infer_ty(ty)];
473                         ProcessResult::Unchanged
474                     }
475                     Some(os) => ProcessResult::Changed(mk_pending(os)),
476                 }
477             }
478
479             ty::Predicate::Subtype(ref subtype) => {
480                 match self.selcx.infcx().subtype_predicate(
481                     &obligation.cause,
482                     obligation.param_env,
483                     subtype,
484                 ) {
485                     None => {
486                         // None means that both are unresolved.
487                         pending_obligation.stalled_on = vec![
488                             infer_ty(subtype.skip_binder().a),
489                             infer_ty(subtype.skip_binder().b),
490                         ];
491                         ProcessResult::Unchanged
492                     }
493                     Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
494                     Some(Err(err)) => {
495                         let expected_found = ExpectedFound::new(
496                             subtype.skip_binder().a_is_expected,
497                             subtype.skip_binder().a,
498                             subtype.skip_binder().b,
499                         );
500                         ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
501                             expected_found,
502                             err,
503                         ))
504                     }
505                 }
506             }
507
508             ty::Predicate::ConstEvaluatable(def_id, substs) => {
509                 if obligation.param_env.has_local_value() {
510                     ProcessResult::Unchanged
511                 } else {
512                     if !substs.has_local_value() {
513                         match self.selcx.tcx().const_eval_resolve(
514                             obligation.param_env,
515                             def_id,
516                             substs,
517                             Some(obligation.cause.span),
518                         ) {
519                             Ok(_) => ProcessResult::Changed(vec![]),
520                             Err(err) => {
521                                 ProcessResult::Error(CodeSelectionError(ConstEvalFailure(err)))
522                             }
523                         }
524                     } else {
525                         pending_obligation.stalled_on =
526                             substs.types().map(|ty| infer_ty(ty)).collect();
527                         ProcessResult::Unchanged
528                     }
529                 }
530             }
531         }
532     }
533
534     fn process_backedge<'c, I>(
535         &mut self,
536         cycle: I,
537         _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
538     ) where
539         I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
540     {
541         if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
542             debug!("process_child_obligations: coinductive match");
543         } else {
544             let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
545             self.selcx.infcx().report_overflow_error_cycle(&cycle);
546         }
547     }
548 }
549
550 /// Returns the set of type variables contained in a trait ref
551 fn trait_ref_type_vars<'a, 'tcx>(
552     selcx: &mut SelectionContext<'a, 'tcx>,
553     t: ty::PolyTraitRef<'tcx>,
554 ) -> Vec<ty::InferTy> {
555     t.skip_binder() // ok b/c this check doesn't care about regions
556         .input_types()
557         .map(|t| selcx.infcx().resolve_vars_if_possible(&t))
558         .filter(|t| t.has_infer_types())
559         .flat_map(|t| t.walk())
560         .filter_map(|t| match t.kind {
561             ty::Infer(infer) => Some(infer),
562             _ => None,
563         })
564         .collect()
565 }
566
567 fn to_fulfillment_error<'tcx>(
568     error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
569 ) -> FulfillmentError<'tcx> {
570     let obligation = error.backtrace.into_iter().next().unwrap().obligation;
571     FulfillmentError::new(obligation, error.error)
572 }