]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/fulfill.rs
Rollup merge of #67966 - popzxc:core-std-matches, 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::wf;
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};
19
20 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
21     type Predicate = ty::Predicate<'tcx>;
22
23     fn as_predicate(&self) -> &Self::Predicate {
24         &self.obligation.predicate
25     }
26 }
27
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.
47     //
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
56     // an infcx snapshot?
57     //
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,
65 }
66
67 #[derive(Clone, Debug)]
68 pub struct PendingPredicateObligation<'tcx> {
69     pub obligation: PredicateObligation<'tcx>,
70     pub stalled_on: Vec<ty::InferTy>,
71 }
72
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);
76
77 impl<'a, 'tcx> FulfillmentContext<'tcx> {
78     /// Creates a new fulfillment context.
79     pub fn new() -> FulfillmentContext<'tcx> {
80         FulfillmentContext {
81             predicates: ObligationForest::new(),
82             register_region_obligations: true,
83             usable_in_snapshot: false,
84         }
85     }
86
87     pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
88         FulfillmentContext {
89             predicates: ObligationForest::new(),
90             register_region_obligations: true,
91             usable_in_snapshot: true,
92         }
93     }
94
95     pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
96         FulfillmentContext {
97             predicates: ObligationForest::new(),
98             register_region_obligations: false,
99             usable_in_snapshot: false,
100         }
101     }
102
103     /// Attempts to select obligations using `selcx`.
104     fn select(
105         &mut self,
106         selcx: &mut SelectionContext<'a, 'tcx>,
107     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
108         debug!("select(obligation-forest-size={})", self.predicates.len());
109
110         let mut errors = Vec::new();
111
112         loop {
113             debug!("select: starting another iteration");
114
115             // Process pending obligations.
116             let outcome = self.predicates.process_obligations(
117                 &mut FulfillProcessor {
118                     selcx,
119                     register_region_obligations: self.register_region_obligations,
120                 },
121                 DoCompleted::No,
122             );
123             debug!("select: outcome={:#?}", outcome);
124
125             // FIXME: if we kept the original cache key, we could mark projection
126             // obligations as complete for the projection cache here.
127
128             errors.extend(outcome.errors.into_iter().map(|e| to_fulfillment_error(e)));
129
130             // If nothing new was added, no need to keep looping.
131             if outcome.stalled {
132                 break;
133             }
134         }
135
136         debug!(
137             "select({} predicates remaining, {} errors) done",
138             self.predicates.len(),
139             errors.len()
140         );
141
142         if errors.is_empty() { Ok(()) } else { Err(errors) }
143     }
144 }
145
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(
155         &mut self,
156         infcx: &InferCtxt<'_, 'tcx>,
157         param_env: ty::ParamEnv<'tcx>,
158         projection_ty: ty::ProjectionTy<'tcx>,
159         cause: ObligationCause<'tcx>,
160     ) -> Ty<'tcx> {
161         debug!("normalize_projection_type(projection_ty={:?})", projection_ty);
162
163         debug_assert!(!projection_ty.has_escaping_bound_vars());
164
165         // FIXME(#20304) -- cache
166
167         let mut selcx = SelectionContext::new(infcx);
168         let mut obligations = vec![];
169         let normalized_ty = project::normalize_projection_type(
170             &mut selcx,
171             param_env,
172             projection_ty,
173             cause,
174             0,
175             &mut obligations,
176         );
177         self.register_predicate_obligations(infcx, obligations);
178
179         debug!("normalize_projection_type: result={:?}", normalized_ty);
180
181         normalized_ty
182     }
183
184     fn register_predicate_obligation(
185         &mut self,
186         infcx: &InferCtxt<'_, 'tcx>,
187         obligation: PredicateObligation<'tcx>,
188     ) {
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);
192
193         debug!("register_predicate_obligation(obligation={:?})", obligation);
194
195         assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
196
197         self.predicates
198             .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
199     }
200
201     fn select_all_or_error(
202         &mut self,
203         infcx: &InferCtxt<'_, 'tcx>,
204     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
205         self.select_where_possible(infcx)?;
206
207         let errors: Vec<_> = self
208             .predicates
209             .to_errors(CodeAmbiguity)
210             .into_iter()
211             .map(|e| to_fulfillment_error(e))
212             .collect();
213         if errors.is_empty() { Ok(()) } else { Err(errors) }
214     }
215
216     fn select_where_possible(
217         &mut self,
218         infcx: &InferCtxt<'_, 'tcx>,
219     ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
220         let mut selcx = SelectionContext::new(infcx);
221         self.select(&mut selcx)
222     }
223
224     fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
225         self.predicates.map_pending_obligations(|o| o.obligation.clone())
226     }
227 }
228
229 struct FulfillProcessor<'a, 'b, 'tcx> {
230     selcx: &'a mut SelectionContext<'b, 'tcx>,
231     register_region_obligations: bool,
232 }
233
234 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
235     os.into_iter()
236         .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
237         .collect()
238 }
239
240 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
241     type Obligation = PendingPredicateObligation<'tcx>;
242     type Error = FulfillmentErrorCode<'tcx>;
243
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
248     ///
249     /// This is always inlined, despite its size, because it has a single
250     /// callsite and it is called *very* frequently.
251     #[inline(always)]
252     fn process_obligation(
253         &mut self,
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
258         // yet.
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.
262             1 => {
263                 let infer = pending_obligation.stalled_on[0];
264                 ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer)
265             }
266             0 => {
267                 // In this case we haven't changed, but wish to make a change.
268                 true
269             }
270             _ => {
271                 // This `for` loop was once a call to `all()`, but this lower-level
272                 // form was a perf win. See #64545 for details.
273                 (|| {
274                     for &infer in &pending_obligation.stalled_on {
275                         if ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer) {
276                             return true;
277                         }
278                     }
279                     false
280                 })()
281             }
282         };
283
284         if !change {
285             debug!(
286                 "process_predicate: pending obligation {:?} still stalled on {:?}",
287                 self.selcx.infcx().resolve_vars_if_possible(&pending_obligation.obligation),
288                 pending_obligation.stalled_on
289             );
290             return ProcessResult::Unchanged;
291         }
292
293         // This part of the code is much colder.
294
295         pending_obligation.stalled_on.truncate(0);
296
297         let obligation = &mut pending_obligation.obligation;
298
299         if obligation.predicate.has_infer_types() {
300             obligation.predicate =
301                 self.selcx.infcx().resolve_vars_if_possible(&obligation.predicate);
302         }
303
304         debug!("process_obligation: obligation = {:?} cause = {:?}", obligation, obligation.cause);
305
306         fn infer_ty(ty: Ty<'tcx>) -> ty::InferTy {
307             match ty.kind {
308                 ty::Infer(infer) => infer,
309                 _ => panic!(),
310             }
311         }
312
313         match obligation.predicate {
314             ty::Predicate::Trait(ref data) => {
315                 let trait_obligation = obligation.with(data.clone());
316
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) {
321                         debug!(
322                             "selecting trait `{:?}` at depth {} evaluated to holds",
323                             data, obligation.recursion_depth
324                         );
325                         return ProcessResult::Changed(vec![]);
326                     }
327                 }
328
329                 match self.selcx.select(&trait_obligation) {
330                     Ok(Some(vtable)) => {
331                         debug!(
332                             "selecting trait `{:?}` at depth {} yielded Ok(Some)",
333                             data, obligation.recursion_depth
334                         );
335                         ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
336                     }
337                     Ok(None) => {
338                         debug!(
339                             "selecting trait `{:?}` at depth {} yielded Ok(None)",
340                             data, obligation.recursion_depth
341                         );
342
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
353                         // the same time.
354                         //
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());
358
359                         debug!(
360                             "process_predicate: pending obligation {:?} now stalled on {:?}",
361                             self.selcx.infcx().resolve_vars_if_possible(obligation),
362                             pending_obligation.stalled_on
363                         );
364
365                         ProcessResult::Unchanged
366                     }
367                     Err(selection_err) => {
368                         info!(
369                             "selecting trait `{:?}` at depth {} yielded Err",
370                             data, obligation.recursion_depth
371                         );
372
373                         ProcessResult::Error(CodeSelectionError(selection_err))
374                     }
375                 }
376             }
377
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)),
382                 }
383             }
384
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.
389                     None => {
390                         // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
391                         let binder = binder.map_bound_ref(|pred| pred.0);
392
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
401                             // `T: 'static`.
402                             Some(t_a) => {
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(
406                                         t_a,
407                                         r_static,
408                                         &obligation.cause,
409                                     );
410                                 }
411                                 ProcessResult::Changed(vec![])
412                             }
413                         }
414                     }
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(
419                                 t_a,
420                                 r_b,
421                                 &obligation.cause,
422                             );
423                         }
424                         ProcessResult::Changed(vec![])
425                     }
426                 }
427             }
428
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) {
432                     Ok(None) => {
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
437                     }
438                     Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
439                     Err(e) => ProcessResult::Error(CodeProjectionError(e)),
440                 }
441             }
442
443             ty::Predicate::ObjectSafe(trait_def_id) => {
444                 if !self.selcx.tcx().is_object_safe(trait_def_id) {
445                     ProcessResult::Error(CodeSelectionError(Unimplemented))
446                 } else {
447                     ProcessResult::Changed(vec![])
448                 }
449             }
450
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![])
456                         } else {
457                             ProcessResult::Error(CodeSelectionError(Unimplemented))
458                         }
459                     }
460                     None => ProcessResult::Unchanged,
461                 }
462             }
463
464             ty::Predicate::WellFormed(ty) => {
465                 match wf::obligations(
466                     self.selcx.infcx(),
467                     obligation.param_env,
468                     obligation.cause.body_id,
469                     ty,
470                     obligation.cause.span,
471                 ) {
472                     None => {
473                         pending_obligation.stalled_on = vec![infer_ty(ty)];
474                         ProcessResult::Unchanged
475                     }
476                     Some(os) => ProcessResult::Changed(mk_pending(os)),
477                 }
478             }
479
480             ty::Predicate::Subtype(ref subtype) => {
481                 match self.selcx.infcx().subtype_predicate(
482                     &obligation.cause,
483                     obligation.param_env,
484                     subtype,
485                 ) {
486                     None => {
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),
491                         ];
492                         ProcessResult::Unchanged
493                     }
494                     Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
495                     Some(Err(err)) => {
496                         let expected_found = ExpectedFound::new(
497                             subtype.skip_binder().a_is_expected,
498                             subtype.skip_binder().a,
499                             subtype.skip_binder().b,
500                         );
501                         ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
502                             expected_found,
503                             err,
504                         ))
505                     }
506                 }
507             }
508
509             ty::Predicate::ConstEvaluatable(def_id, substs) => {
510                 if obligation.param_env.has_local_value() {
511                     ProcessResult::Unchanged
512                 } else {
513                     if !substs.has_local_value() {
514                         match self.selcx.tcx().const_eval_resolve(
515                             obligation.param_env,
516                             def_id,
517                             substs,
518                             Some(obligation.cause.span),
519                         ) {
520                             Ok(_) => ProcessResult::Changed(vec![]),
521                             Err(err) => {
522                                 ProcessResult::Error(CodeSelectionError(ConstEvalFailure(err)))
523                             }
524                         }
525                     } else {
526                         pending_obligation.stalled_on =
527                             substs.types().map(|ty| infer_ty(ty)).collect();
528                         ProcessResult::Unchanged
529                     }
530                 }
531             }
532         }
533     }
534
535     fn process_backedge<'c, I>(
536         &mut self,
537         cycle: I,
538         _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
539     ) where
540         I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
541     {
542         if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
543             debug!("process_child_obligations: coinductive match");
544         } else {
545             let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
546             self.selcx.infcx().report_overflow_error_cycle(&cycle);
547         }
548     }
549 }
550
551 /// Returns the set of type variables contained in a trait ref
552 fn trait_ref_type_vars<'a, 'tcx>(
553     selcx: &mut SelectionContext<'a, 'tcx>,
554     t: ty::PolyTraitRef<'tcx>,
555 ) -> Vec<ty::InferTy> {
556     t.skip_binder() // ok b/c this check doesn't care about regions
557         .input_types()
558         .map(|t| selcx.infcx().resolve_vars_if_possible(&t))
559         .filter(|t| t.has_infer_types())
560         .flat_map(|t| t.walk())
561         .filter_map(|t| match t.kind {
562             ty::Infer(infer) => Some(infer),
563             _ => None,
564         })
565         .collect()
566 }
567
568 fn to_fulfillment_error<'tcx>(
569     error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
570 ) -> FulfillmentError<'tcx> {
571     let obligation = error.backtrace.into_iter().next().unwrap().obligation;
572     FulfillmentError::new(obligation, error.error)
573 }