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