]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/fulfill.rs
Rollup merge of #67354 - VirrageS:blame-wrong-line, r=estebank
[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::InferTy>,
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 infer = pending_obligation.stalled_on[0];
267                 ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer)
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 &infer in &pending_obligation.stalled_on {
278                         if ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer) {
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         fn infer_ty(ty: Ty<'tcx>) -> ty::InferTy {
309             match ty.kind {
310                 ty::Infer(infer) => infer,
311                 _ => panic!(),
312             }
313         }
314
315         match obligation.predicate {
316             ty::Predicate::Trait(ref data) => {
317                 let trait_obligation = obligation.with(data.clone());
318
319                 if data.is_global() {
320                     // no type variables present, can use evaluation for better caching.
321                     // FIXME: consider caching errors too.
322                     if self.selcx.infcx().predicate_must_hold_considering_regions(&obligation) {
323                         debug!("selecting trait `{:?}` at depth {} evaluated to holds",
324                                data, obligation.recursion_depth);
325                         return ProcessResult::Changed(vec![])
326                     }
327                 }
328
329                 match self.selcx.select(&trait_obligation) {
330                     Ok(Some(vtable)) => {
331                         debug!("selecting trait `{:?}` at depth {} yielded Ok(Some)",
332                                data, obligation.recursion_depth);
333                         ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
334                     }
335                     Ok(None) => {
336                         debug!("selecting trait `{:?}` at depth {} yielded Ok(None)",
337                                data, obligation.recursion_depth);
338
339                         // This is a bit subtle: for the most part, the
340                         // only reason we can fail to make progress on
341                         // trait selection is because we don't have enough
342                         // information about the types in the trait. One
343                         // exception is that we sometimes haven't decided
344                         // what kind of closure a closure is. *But*, in
345                         // that case, it turns out, the type of the
346                         // closure will also change, because the closure
347                         // also includes references to its upvars as part
348                         // of its type, and those types are resolved at
349                         // the same time.
350                         //
351                         // FIXME(#32286) logic seems false if no upvars
352                         pending_obligation.stalled_on =
353                             trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
354
355                         debug!("process_predicate: pending obligation {:?} now stalled on {:?}",
356                                self.selcx.infcx().resolve_vars_if_possible(obligation),
357                                pending_obligation.stalled_on);
358
359                         ProcessResult::Unchanged
360                     }
361                     Err(selection_err) => {
362                         info!("selecting trait `{:?}` at depth {} yielded Err",
363                               data, obligation.recursion_depth);
364
365                         ProcessResult::Error(CodeSelectionError(selection_err))
366                     }
367                 }
368             }
369
370             ty::Predicate::RegionOutlives(ref binder) => {
371                 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
372                     Ok(()) => ProcessResult::Changed(vec![]),
373                     Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
374                 }
375             }
376
377             ty::Predicate::TypeOutlives(ref binder) => {
378                 // Check if there are higher-ranked vars.
379                 match binder.no_bound_vars() {
380                     // If there are, inspect the underlying type further.
381                     None => {
382                         // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
383                         let binder = binder.map_bound_ref(|pred| pred.0);
384
385                         // Check if the type has any bound vars.
386                         match binder.no_bound_vars() {
387                             // If so, this obligation is an error (for now). Eventually we should be
388                             // able to support additional cases here, like `for<'a> &'a str: 'a`.
389                             // NOTE: this is duplicate-implemented between here and fulfillment.
390                             None => {
391                                 ProcessResult::Error(CodeSelectionError(Unimplemented))
392                             }
393                             // Otherwise, we have something of the form
394                             // `for<'a> T: 'a where 'a not in T`, which we can treat as
395                             // `T: 'static`.
396                             Some(t_a) => {
397                                 let r_static = self.selcx.tcx().lifetimes.re_static;
398                                 if self.register_region_obligations {
399                                     self.selcx.infcx().register_region_obligation_with_cause(
400                                         t_a,
401                                         r_static,
402                                         &obligation.cause,
403                                     );
404                                 }
405                                 ProcessResult::Changed(vec![])
406                             }
407                         }
408                     }
409                     // If there aren't, register the obligation.
410                     Some(ty::OutlivesPredicate(t_a, r_b)) => {
411                         if self.register_region_obligations {
412                             self.selcx.infcx().register_region_obligation_with_cause(
413                                 t_a,
414                                 r_b,
415                                 &obligation.cause,
416                             );
417                         }
418                         ProcessResult::Changed(vec![])
419                     }
420                 }
421             }
422
423             ty::Predicate::Projection(ref data) => {
424                 let project_obligation = obligation.with(data.clone());
425                 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
426                     Ok(None) => {
427                         let tcx = self.selcx.tcx();
428                         pending_obligation.stalled_on =
429                             trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
430                         ProcessResult::Unchanged
431                     }
432                     Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
433                     Err(e) => ProcessResult::Error(CodeProjectionError(e))
434                 }
435             }
436
437             ty::Predicate::ObjectSafe(trait_def_id) => {
438                 if !self.selcx.tcx().is_object_safe(trait_def_id) {
439                     ProcessResult::Error(CodeSelectionError(Unimplemented))
440                 } else {
441                     ProcessResult::Changed(vec![])
442                 }
443             }
444
445             ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
446                 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
447                     Some(closure_kind) => {
448                         if closure_kind.extends(kind) {
449                             ProcessResult::Changed(vec![])
450                         } else {
451                             ProcessResult::Error(CodeSelectionError(Unimplemented))
452                         }
453                     }
454                     None => {
455                         ProcessResult::Unchanged
456                     }
457                 }
458             }
459
460             ty::Predicate::WellFormed(ty) => {
461                 match ty::wf::obligations(
462                     self.selcx.infcx(),
463                     obligation.param_env,
464                     obligation.cause.body_id,
465                     ty,
466                     obligation.cause.span,
467                 ) {
468                     None => {
469                         pending_obligation.stalled_on = vec![infer_ty(ty)];
470                         ProcessResult::Unchanged
471                     }
472                     Some(os) => ProcessResult::Changed(mk_pending(os))
473                 }
474             }
475
476             ty::Predicate::Subtype(ref subtype) => {
477                 match self.selcx.infcx().subtype_predicate(&obligation.cause,
478                                                            obligation.param_env,
479                                                            subtype) {
480                     None => {
481                         // None means that both are unresolved.
482                         pending_obligation.stalled_on = vec![infer_ty(subtype.skip_binder().a),
483                                                              infer_ty(subtype.skip_binder().b)];
484                         ProcessResult::Unchanged
485                     }
486                     Some(Ok(ok)) => {
487                         ProcessResult::Changed(mk_pending(ok.obligations))
488                     }
489                     Some(Err(err)) => {
490                         let expected_found = ExpectedFound::new(subtype.skip_binder().a_is_expected,
491                                                                 subtype.skip_binder().a,
492                                                                 subtype.skip_binder().b);
493                         ProcessResult::Error(
494                             FulfillmentErrorCode::CodeSubtypeError(expected_found, err))
495                     }
496                 }
497             }
498
499             ty::Predicate::ConstEvaluatable(def_id, substs) => {
500                 if obligation.param_env.has_local_value() {
501                         ProcessResult::Unchanged
502                 } else {
503                     if !substs.has_local_value() {
504                         let instance = ty::Instance::resolve(
505                             self.selcx.tcx(),
506                             obligation.param_env,
507                             def_id,
508                             substs,
509                         );
510                         if let Some(instance) = instance {
511                             let cid = GlobalId {
512                                 instance,
513                                 promoted: None,
514                             };
515                             match self.selcx.tcx().at(obligation.cause.span)
516                                                     .const_eval(obligation.param_env.and(cid)) {
517                                 Ok(_) => ProcessResult::Changed(vec![]),
518                                 Err(err) => ProcessResult::Error(
519                                     CodeSelectionError(ConstEvalFailure(err)))
520                             }
521                         } else {
522                             ProcessResult::Error(CodeSelectionError(
523                                 ConstEvalFailure(ErrorHandled::TooGeneric)
524                             ))
525                         }
526                     } else {
527                         pending_obligation.stalled_on =
528                             substs.types().map(|ty| infer_ty(ty)).collect();
529                         ProcessResult::Unchanged
530                     }
531                 }
532             }
533         }
534     }
535
536     fn process_backedge<'c, I>(&mut self, cycle: I,
537                                _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>)
538         where I: Clone + Iterator<Item=&'c PendingPredicateObligation<'tcx>>,
539     {
540         if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
541             debug!("process_child_obligations: coinductive match");
542         } else {
543             let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
544             self.selcx.infcx().report_overflow_error_cycle(&cycle);
545         }
546     }
547 }
548
549 /// Returns the set of type variables contained in a trait ref
550 fn trait_ref_type_vars<'a, 'tcx>(
551     selcx: &mut SelectionContext<'a, 'tcx>,
552     t: ty::PolyTraitRef<'tcx>,
553 ) -> Vec<ty::InferTy> {
554     t.skip_binder() // ok b/c this check doesn't care about regions
555      .input_types()
556      .map(|t| selcx.infcx().resolve_vars_if_possible(&t))
557      .filter(|t| t.has_infer_types())
558      .flat_map(|t| t.walk())
559      .filter_map(|t| match t.kind { ty::Infer(infer) => Some(infer), _ => None })
560      .collect()
561 }
562
563 fn to_fulfillment_error<'tcx>(
564     error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>)
565     -> FulfillmentError<'tcx>
566 {
567     let obligation = error.backtrace.into_iter().next().unwrap().obligation;
568     FulfillmentError::new(obligation, error.error)
569 }