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