]>
Commit | Line | Data |
---|---|---|
60c5eb7d XL |
1 | //! Support code for rustdoc and external tools. |
2 | //! You really don't want to be using this unless you need to. | |
94b46f34 XL |
3 | |
4 | use super::*; | |
5 | ||
f2b60f7d | 6 | use crate::errors::UnableToConstructConstantValue; |
9fa01778 XL |
7 | use crate::infer::region_constraints::{Constraint, RegionConstraintData}; |
8 | use crate::infer::InferCtxt; | |
5e7ed085 | 9 | use crate::traits::project::ProjectAndUnifyResult; |
923072b8 FG |
10 | use rustc_middle::mir::interpret::ErrorHandled; |
11 | use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable}; | |
064997fb | 12 | use rustc_middle::ty::visit::TypeVisitable; |
487cf647 | 13 | use rustc_middle::ty::{ImplPolarity, Region, RegionVid}; |
94b46f34 | 14 | |
487cf647 | 15 | use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; |
60c5eb7d XL |
16 | |
17 | use std::collections::hash_map::Entry; | |
18 | use std::collections::VecDeque; | |
cdc7bbd5 | 19 | use std::iter; |
60c5eb7d | 20 | |
94b46f34 XL |
21 | // FIXME(twk): this is obviously not nice to duplicate like that |
22 | #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)] | |
23 | pub enum RegionTarget<'tcx> { | |
24 | Region(Region<'tcx>), | |
25 | RegionVid(RegionVid), | |
26 | } | |
27 | ||
28 | #[derive(Default, Debug, Clone)] | |
29 | pub struct RegionDeps<'tcx> { | |
487cf647 FG |
30 | larger: FxIndexSet<RegionTarget<'tcx>>, |
31 | smaller: FxIndexSet<RegionTarget<'tcx>>, | |
94b46f34 XL |
32 | } |
33 | ||
34 | pub enum AutoTraitResult<A> { | |
35 | ExplicitImpl, | |
36 | PositiveImpl(A), | |
37 | NegativeImpl, | |
38 | } | |
39 | ||
1b1a35ee | 40 | #[allow(dead_code)] |
94b46f34 XL |
41 | impl<A> AutoTraitResult<A> { |
42 | fn is_auto(&self) -> bool { | |
5869c6ff | 43 | matches!(self, AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl) |
94b46f34 XL |
44 | } |
45 | } | |
46 | ||
47 | pub struct AutoTraitInfo<'cx> { | |
48 | pub full_user_env: ty::ParamEnv<'cx>, | |
49 | pub region_data: RegionConstraintData<'cx>, | |
94b46f34 XL |
50 | pub vid_to_region: FxHashMap<ty::RegionVid, ty::Region<'cx>>, |
51 | } | |
52 | ||
dc9dc135 XL |
53 | pub struct AutoTraitFinder<'tcx> { |
54 | tcx: TyCtxt<'tcx>, | |
94b46f34 XL |
55 | } |
56 | ||
dc9dc135 XL |
57 | impl<'tcx> AutoTraitFinder<'tcx> { |
58 | pub fn new(tcx: TyCtxt<'tcx>) -> Self { | |
94b46f34 XL |
59 | AutoTraitFinder { tcx } |
60 | } | |
61 | ||
9fa01778 | 62 | /// Makes a best effort to determine whether and under which conditions an auto trait is |
94b46f34 XL |
63 | /// implemented for a type. For example, if you have |
64 | /// | |
65 | /// ``` | |
66 | /// struct Foo<T> { data: Box<T> } | |
67 | /// ``` | |
0bf4aa26 | 68 | /// |
2b03887a FG |
69 | /// then this might return that `Foo<T>: Send` if `T: Send` (encoded in the AutoTraitResult |
70 | /// type). The analysis attempts to account for custom impls as well as other complex cases. | |
71 | /// This result is intended for use by rustdoc and other such consumers. | |
0bf4aa26 | 72 | /// |
94b46f34 XL |
73 | /// (Note that due to the coinductive nature of Send, the full and correct result is actually |
74 | /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field | |
2b03887a | 75 | /// types are all Send. So, in our example, we might have that `Foo<T>: Send` if `Box<T>: Send`. |
94b46f34 | 76 | /// But this is often not the best way to present to the user.) |
0bf4aa26 | 77 | /// |
94b46f34 XL |
78 | /// Warning: The API should be considered highly unstable, and it may be refactored or removed |
79 | /// in the future. | |
80 | pub fn find_auto_trait_generics<A>( | |
81 | &self, | |
48663c56 XL |
82 | ty: Ty<'tcx>, |
83 | orig_env: ty::ParamEnv<'tcx>, | |
94b46f34 | 84 | trait_did: DefId, |
6a06907d | 85 | mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A, |
94b46f34 XL |
86 | ) -> AutoTraitResult<A> { |
87 | let tcx = self.tcx; | |
94b46f34 | 88 | |
487cf647 | 89 | let trait_ref = tcx.mk_trait_ref(trait_did, [ty]); |
94b46f34 | 90 | |
2b03887a FG |
91 | let infcx = tcx.infer_ctxt().build(); |
92 | let mut selcx = SelectionContext::new(&infcx); | |
487cf647 FG |
93 | for polarity in [true, false] { |
94 | let result = selcx.select(&Obligation::new( | |
95 | tcx, | |
96 | ObligationCause::dummy(), | |
97 | orig_env, | |
98 | ty::Binder::dummy(ty::TraitPredicate { | |
99 | trait_ref, | |
100 | constness: ty::BoundConstness::NotConst, | |
101 | polarity: if polarity { | |
102 | ImplPolarity::Positive | |
103 | } else { | |
104 | ImplPolarity::Negative | |
105 | }, | |
106 | }), | |
107 | )); | |
2b03887a FG |
108 | if let Ok(Some(ImplSource::UserDefined(_))) = result { |
109 | debug!( | |
110 | "find_auto_trait_generics({:?}): \ | |
111 | manual impl found, bailing out", | |
112 | trait_ref | |
113 | ); | |
114 | // If an explicit impl exists, it always takes priority over an auto impl | |
115 | return AutoTraitResult::ExplicitImpl; | |
5e7ed085 | 116 | } |
94b46f34 XL |
117 | } |
118 | ||
2b03887a FG |
119 | let infcx = tcx.infer_ctxt().build(); |
120 | let mut fresh_preds = FxHashSet::default(); | |
121 | ||
122 | // Due to the way projections are handled by SelectionContext, we need to run | |
123 | // evaluate_predicates twice: once on the original param env, and once on the result of | |
124 | // the first evaluate_predicates call. | |
125 | // | |
126 | // The problem is this: most of rustc, including SelectionContext and traits::project, | |
127 | // are designed to work with a concrete usage of a type (e.g., Vec<u8> | |
128 | // fn<T>() { Vec<T> }. This information will generally never change - given | |
129 | // the 'T' in fn<T>() { ... }, we'll never know anything else about 'T'. | |
130 | // If we're unable to prove that 'T' implements a particular trait, we're done - | |
131 | // there's nothing left to do but error out. | |
132 | // | |
133 | // However, synthesizing an auto trait impl works differently. Here, we start out with | |
134 | // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing | |
135 | // with - and progressively discover the conditions we need to fulfill for it to | |
136 | // implement a certain auto trait. This ends up breaking two assumptions made by trait | |
137 | // selection and projection: | |
138 | // | |
139 | // * We can always cache the result of a particular trait selection for the lifetime of | |
140 | // an InfCtxt | |
141 | // * Given a projection bound such as '<T as SomeTrait>::SomeItem = K', if 'T: | |
142 | // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K' | |
143 | // | |
144 | // We fix the first assumption by manually clearing out all of the InferCtxt's caches | |
145 | // in between calls to SelectionContext.select. This allows us to keep all of the | |
146 | // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift | |
147 | // them between calls. | |
148 | // | |
149 | // We fix the second assumption by reprocessing the result of our first call to | |
150 | // evaluate_predicates. Using the example of '<T as SomeTrait>::SomeItem = K', our first | |
151 | // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass, | |
152 | // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing | |
153 | // SelectionContext to return it back to us. | |
154 | ||
155 | let Some((new_env, user_env)) = self.evaluate_predicates( | |
156 | &infcx, | |
157 | trait_did, | |
158 | ty, | |
159 | orig_env, | |
160 | orig_env, | |
161 | &mut fresh_preds, | |
2b03887a FG |
162 | ) else { |
163 | return AutoTraitResult::NegativeImpl; | |
164 | }; | |
165 | ||
166 | let (full_env, full_user_env) = self | |
9c376795 | 167 | .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds) |
2b03887a FG |
168 | .unwrap_or_else(|| { |
169 | panic!("Failed to fully process: {:?} {:?} {:?}", ty, trait_did, orig_env) | |
170 | }); | |
94b46f34 | 171 | |
2b03887a FG |
172 | debug!( |
173 | "find_auto_trait_generics({:?}): fulfilling \ | |
174 | with {:?}", | |
175 | trait_ref, full_env | |
176 | ); | |
177 | infcx.clear_caches(); | |
178 | ||
179 | // At this point, we already have all of the bounds we need. FulfillmentContext is used | |
180 | // to store all of the necessary region/lifetime bounds in the InferContext, as well as | |
181 | // an additional sanity check. | |
182 | let errors = | |
183 | super::fully_solve_bound(&infcx, ObligationCause::dummy(), full_env, ty, trait_did); | |
184 | if !errors.is_empty() { | |
185 | panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors); | |
186 | } | |
94b46f34 | 187 | |
2b03887a | 188 | infcx.process_registered_region_obligations(&Default::default(), full_env); |
94b46f34 | 189 | |
2b03887a FG |
190 | let region_data = |
191 | infcx.inner.borrow_mut().unwrap_region_constraints().region_constraint_data().clone(); | |
94b46f34 | 192 | |
2b03887a | 193 | let vid_to_region = self.map_vid_to_region(®ion_data); |
94b46f34 | 194 | |
2b03887a | 195 | let info = AutoTraitInfo { full_user_env, region_data, vid_to_region }; |
94b46f34 | 196 | |
2b03887a | 197 | AutoTraitResult::PositiveImpl(auto_trait_callback(info)) |
94b46f34 XL |
198 | } |
199 | } | |
200 | ||
a2a8927a | 201 | impl<'tcx> AutoTraitFinder<'tcx> { |
60c5eb7d XL |
202 | /// The core logic responsible for computing the bounds for our synthesized impl. |
203 | /// | |
204 | /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like | |
205 | /// `FulfillmentContext`, we recursively select the nested obligations of predicates we | |
206 | /// encounter. However, whenever we encounter an `UnimplementedError` involving a type | |
207 | /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular | |
208 | /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met. | |
209 | /// | |
210 | /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key | |
211 | /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete | |
212 | /// user code. According, it considers all possible ways that a `Predicate` could be met, which | |
213 | /// isn't always what we want for a synthesized impl. For example, given the predicate `T: | |
214 | /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T: | |
215 | /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`, | |
216 | /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up. | |
217 | /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl | |
218 | /// like this: | |
04454e1e FG |
219 | /// ```ignore (illustrative) |
220 | /// impl<T> Send for Foo<T> where T: IntoIterator | |
221 | /// ``` | |
60c5eb7d XL |
222 | /// While it might be technically true that Foo implements Send where `T: IntoIterator`, |
223 | /// the bound is overly restrictive - it's really only necessary that `T: Iterator`. | |
224 | /// | |
225 | /// For this reason, `evaluate_predicates` handles predicates with type variables specially. | |
226 | /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately | |
227 | /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later | |
228 | /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator` | |
229 | /// needs to hold. | |
230 | /// | |
231 | /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever | |
232 | /// constructed once for a given type. As part of the construction process, the `ParamEnv` will | |
233 | /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo<T: Copy>`, the | |
234 | /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our | |
235 | /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate_predicates`, or | |
236 | /// else `SelectionContext` will choke on the missing predicates. However, this should never | |
237 | /// show up in the final synthesized generics: we don't want our generated docs page to contain | |
238 | /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a | |
239 | /// separate `user_env`, which only holds the predicates that will actually be displayed to the | |
240 | /// user. | |
dc9dc135 | 241 | fn evaluate_predicates( |
94b46f34 | 242 | &self, |
2b03887a | 243 | infcx: &InferCtxt<'tcx>, |
94b46f34 | 244 | trait_did: DefId, |
dc9dc135 XL |
245 | ty: Ty<'tcx>, |
246 | param_env: ty::ParamEnv<'tcx>, | |
247 | user_env: ty::ParamEnv<'tcx>, | |
248 | fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>, | |
dc9dc135 | 249 | ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> { |
94b46f34 XL |
250 | let tcx = infcx.tcx; |
251 | ||
5e7ed085 | 252 | // Don't try to process any nested obligations involving predicates |
3dfed10e XL |
253 | // that are already in the `ParamEnv` (modulo regions): we already |
254 | // know that they must hold. | |
255 | for predicate in param_env.caller_bounds() { | |
256 | fresh_preds.insert(self.clean_pred(infcx, predicate)); | |
257 | } | |
258 | ||
5e7ed085 | 259 | let mut select = SelectionContext::new(&infcx); |
94b46f34 | 260 | |
0bf4aa26 | 261 | let mut already_visited = FxHashSet::default(); |
94b46f34 | 262 | let mut predicates = VecDeque::new(); |
cdc7bbd5 | 263 | predicates.push_back(ty::Binder::dummy(ty::TraitPredicate { |
487cf647 FG |
264 | trait_ref: infcx.tcx.mk_trait_ref(trait_did, [ty]), |
265 | ||
94222f64 | 266 | constness: ty::BoundConstness::NotConst, |
3c0e092e XL |
267 | // Auto traits are positive |
268 | polarity: ty::ImplPolarity::Positive, | |
94b46f34 XL |
269 | })); |
270 | ||
f035d41b | 271 | let computed_preds = param_env.caller_bounds().iter(); |
487cf647 | 272 | let mut user_computed_preds: FxIndexSet<_> = user_env.caller_bounds().iter().collect(); |
94b46f34 | 273 | |
48663c56 | 274 | let mut new_env = param_env; |
ba9703b0 | 275 | let dummy_cause = ObligationCause::dummy(); |
94b46f34 XL |
276 | |
277 | while let Some(pred) = predicates.pop_front() { | |
278 | infcx.clear_caches(); | |
279 | ||
48663c56 | 280 | if !already_visited.insert(pred) { |
94b46f34 XL |
281 | continue; |
282 | } | |
283 | ||
60c5eb7d | 284 | // Call `infcx.resolve_vars_if_possible` to see if we can |
69743fb6 | 285 | // get rid of any inference variables. |
487cf647 FG |
286 | let obligation = infcx.resolve_vars_if_possible(Obligation::new( |
287 | tcx, | |
288 | dummy_cause.clone(), | |
289 | new_env, | |
290 | pred, | |
291 | )); | |
69743fb6 | 292 | let result = select.select(&obligation); |
94b46f34 | 293 | |
5869c6ff XL |
294 | match result { |
295 | Ok(Some(ref impl_source)) => { | |
60c5eb7d | 296 | // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`), |
a1dfa0c6 | 297 | // we immediately bail out, since it's impossible for us to continue. |
ba9703b0 | 298 | |
1b1a35ee XL |
299 | if let ImplSource::UserDefined(ImplSourceUserDefinedData { |
300 | impl_def_id, .. | |
f035d41b XL |
301 | }) = impl_source |
302 | { | |
ba9703b0 XL |
303 | // Blame 'tidy' for the weird bracket placement. |
304 | if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative { | |
305 | debug!( | |
306 | "evaluate_nested_obligations: found explicit negative impl\ | |
dfeec247 | 307 | {:?}, bailing out", |
ba9703b0 XL |
308 | impl_def_id |
309 | ); | |
310 | return None; | |
dfeec247 | 311 | } |
a1dfa0c6 XL |
312 | } |
313 | ||
f2b60f7d | 314 | let obligations = impl_source.borrow_nested_obligations().iter().cloned(); |
94b46f34 XL |
315 | |
316 | if !self.evaluate_nested_obligations( | |
317 | ty, | |
318 | obligations, | |
319 | &mut user_computed_preds, | |
320 | fresh_preds, | |
321 | &mut predicates, | |
322 | &mut select, | |
94b46f34 XL |
323 | ) { |
324 | return None; | |
325 | } | |
326 | } | |
5869c6ff XL |
327 | Ok(None) => {} |
328 | Err(SelectionError::Unimplemented) => { | |
69743fb6 | 329 | if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) { |
94b46f34 | 330 | already_visited.remove(&pred); |
94222f64 | 331 | self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx)); |
94b46f34 XL |
332 | predicates.push_back(pred); |
333 | } else { | |
334 | debug!( | |
60c5eb7d | 335 | "evaluate_nested_obligations: `Unimplemented` found, bailing: \ |
94b46f34 XL |
336 | {:?} {:?} {:?}", |
337 | ty, | |
338 | pred, | |
339 | pred.skip_binder().trait_ref.substs | |
340 | ); | |
341 | return None; | |
342 | } | |
343 | } | |
344 | _ => panic!("Unexpected error for '{:?}': {:?}", ty, result), | |
345 | }; | |
346 | ||
ba9703b0 XL |
347 | let normalized_preds = elaborate_predicates( |
348 | tcx, | |
349 | computed_preds.clone().chain(user_computed_preds.iter().cloned()), | |
350 | ) | |
351 | .map(|o| o.predicate); | |
a2a8927a XL |
352 | new_env = ty::ParamEnv::new( |
353 | tcx.mk_predicates(normalized_preds), | |
354 | param_env.reveal(), | |
355 | param_env.constness(), | |
356 | ); | |
94b46f34 XL |
357 | } |
358 | ||
359 | let final_user_env = ty::ParamEnv::new( | |
360 | tcx.mk_predicates(user_computed_preds.into_iter()), | |
f035d41b | 361 | user_env.reveal(), |
a2a8927a | 362 | user_env.constness(), |
94b46f34 XL |
363 | ); |
364 | debug!( | |
48663c56 | 365 | "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \ |
94b46f34 | 366 | '{:?}'", |
48663c56 | 367 | ty, trait_did, new_env, final_user_env |
94b46f34 XL |
368 | ); |
369 | ||
ba9703b0 | 370 | Some((new_env, final_user_env)) |
94b46f34 XL |
371 | } |
372 | ||
60c5eb7d XL |
373 | /// This method is designed to work around the following issue: |
374 | /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`, | |
375 | /// progressively building a `ParamEnv` based on the results we get. | |
376 | /// However, our usage of `SelectionContext` differs from its normal use within the compiler, | |
377 | /// in that we capture and re-reprocess predicates from `Unimplemented` errors. | |
378 | /// | |
379 | /// This can lead to a corner case when dealing with region parameters. | |
380 | /// During our selection loop in `evaluate_predicates`, we might end up with | |
381 | /// two trait predicates that differ only in their region parameters: | |
382 | /// one containing a HRTB lifetime parameter, and one containing a 'normal' | |
383 | /// lifetime parameter. For example: | |
04454e1e FG |
384 | /// ```ignore (illustrative) |
385 | /// T as MyTrait<'a> | |
386 | /// T as MyTrait<'static> | |
387 | /// ``` | |
60c5eb7d XL |
388 | /// If we put both of these predicates in our computed `ParamEnv`, we'll |
389 | /// confuse `SelectionContext`, since it will (correctly) view both as being applicable. | |
390 | /// | |
391 | /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB | |
392 | /// Our end goal is to generate a user-visible description of the conditions | |
393 | /// under which a type implements an auto trait. A trait predicate involving | |
394 | /// a HRTB means that the type needs to work with any choice of lifetime, | |
395 | /// not just one specific lifetime (e.g., `'static`). | |
3dfed10e | 396 | fn add_user_pred( |
0bf4aa26 | 397 | &self, |
487cf647 | 398 | user_computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>, |
3dfed10e | 399 | new_pred: ty::Predicate<'tcx>, |
0bf4aa26 | 400 | ) { |
b7449926 XL |
401 | let mut should_add_new = true; |
402 | user_computed_preds.retain(|&old_pred| { | |
487cf647 FG |
403 | if let ( |
404 | ty::PredicateKind::Clause(ty::Clause::Trait(new_trait)), | |
405 | ty::PredicateKind::Clause(ty::Clause::Trait(old_trait)), | |
406 | ) = (new_pred.kind().skip_binder(), old_pred.kind().skip_binder()) | |
ba9703b0 XL |
407 | { |
408 | if new_trait.def_id() == old_trait.def_id() { | |
3dfed10e XL |
409 | let new_substs = new_trait.trait_ref.substs; |
410 | let old_substs = old_trait.trait_ref.substs; | |
ba9703b0 XL |
411 | |
412 | if !new_substs.types().eq(old_substs.types()) { | |
413 | // We can't compare lifetimes if the types are different, | |
414 | // so skip checking `old_pred`. | |
415 | return true; | |
416 | } | |
b7449926 | 417 | |
cdc7bbd5 XL |
418 | for (new_region, old_region) in |
419 | iter::zip(new_substs.regions(), old_substs.regions()) | |
420 | { | |
5099ac24 | 421 | match (*new_region, *old_region) { |
ba9703b0 XL |
422 | // If both predicates have an `ReLateBound` (a HRTB) in the |
423 | // same spot, we do nothing. | |
5099ac24 | 424 | (ty::ReLateBound(_, _), ty::ReLateBound(_, _)) => {} |
ba9703b0 | 425 | |
5099ac24 | 426 | (ty::ReLateBound(_, _), _) | (_, ty::ReVar(_)) => { |
ba9703b0 XL |
427 | // One of these is true: |
428 | // The new predicate has a HRTB in a spot where the old | |
429 | // predicate does not (if they both had a HRTB, the previous | |
430 | // match arm would have executed). A HRBT is a 'stricter' | |
431 | // bound than anything else, so we want to keep the newer | |
432 | // predicate (with the HRBT) in place of the old predicate. | |
433 | // | |
434 | // OR | |
435 | // | |
436 | // The old predicate has a region variable where the new | |
437 | // predicate has some other kind of region. An region | |
438 | // variable isn't something we can actually display to a user, | |
439 | // so we choose their new predicate (which doesn't have a region | |
440 | // variable). | |
441 | // | |
442 | // In both cases, we want to remove the old predicate, | |
443 | // from `user_computed_preds`, and replace it with the new | |
444 | // one. Having both the old and the new | |
445 | // predicate in a `ParamEnv` would confuse `SelectionContext`. | |
446 | // | |
447 | // We're currently in the predicate passed to 'retain', | |
448 | // so we return `false` to remove the old predicate from | |
449 | // `user_computed_preds`. | |
450 | return false; | |
b7449926 | 451 | } |
5099ac24 | 452 | (_, ty::ReLateBound(_, _)) | (ty::ReVar(_), _) => { |
ba9703b0 XL |
453 | // This is the opposite situation as the previous arm. |
454 | // One of these is true: | |
455 | // | |
456 | // The old predicate has a HRTB lifetime in a place where the | |
457 | // new predicate does not. | |
458 | // | |
459 | // OR | |
460 | // | |
461 | // The new predicate has a region variable where the old | |
462 | // predicate has some other type of region. | |
463 | // | |
464 | // We want to leave the old | |
465 | // predicate in `user_computed_preds`, and skip adding | |
466 | // new_pred to `user_computed_params`. | |
467 | should_add_new = false | |
468 | } | |
469 | _ => {} | |
b7449926 XL |
470 | } |
471 | } | |
0bf4aa26 | 472 | } |
b7449926 | 473 | } |
ba9703b0 | 474 | true |
b7449926 XL |
475 | }); |
476 | ||
477 | if should_add_new { | |
478 | user_computed_preds.insert(new_pred); | |
479 | } | |
480 | } | |
481 | ||
60c5eb7d XL |
482 | /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s |
483 | /// to each other, we match `ty::RegionVid`s to `ty::Region`s. | |
48663c56 | 484 | fn map_vid_to_region<'cx>( |
94b46f34 XL |
485 | &self, |
486 | regions: &RegionConstraintData<'cx>, | |
487 | ) -> FxHashMap<ty::RegionVid, ty::Region<'cx>> { | |
0bf4aa26 XL |
488 | let mut vid_map: FxHashMap<RegionTarget<'cx>, RegionDeps<'cx>> = FxHashMap::default(); |
489 | let mut finished_map = FxHashMap::default(); | |
94b46f34 XL |
490 | |
491 | for constraint in regions.constraints.keys() { | |
492 | match constraint { | |
493 | &Constraint::VarSubVar(r1, r2) => { | |
494 | { | |
0bf4aa26 | 495 | let deps1 = vid_map.entry(RegionTarget::RegionVid(r1)).or_default(); |
94b46f34 XL |
496 | deps1.larger.insert(RegionTarget::RegionVid(r2)); |
497 | } | |
498 | ||
0bf4aa26 | 499 | let deps2 = vid_map.entry(RegionTarget::RegionVid(r2)).or_default(); |
94b46f34 XL |
500 | deps2.smaller.insert(RegionTarget::RegionVid(r1)); |
501 | } | |
502 | &Constraint::RegSubVar(region, vid) => { | |
503 | { | |
0bf4aa26 | 504 | let deps1 = vid_map.entry(RegionTarget::Region(region)).or_default(); |
94b46f34 XL |
505 | deps1.larger.insert(RegionTarget::RegionVid(vid)); |
506 | } | |
507 | ||
0bf4aa26 | 508 | let deps2 = vid_map.entry(RegionTarget::RegionVid(vid)).or_default(); |
94b46f34 XL |
509 | deps2.smaller.insert(RegionTarget::Region(region)); |
510 | } | |
511 | &Constraint::VarSubReg(vid, region) => { | |
512 | finished_map.insert(vid, region); | |
513 | } | |
514 | &Constraint::RegSubReg(r1, r2) => { | |
515 | { | |
0bf4aa26 | 516 | let deps1 = vid_map.entry(RegionTarget::Region(r1)).or_default(); |
94b46f34 XL |
517 | deps1.larger.insert(RegionTarget::Region(r2)); |
518 | } | |
519 | ||
0bf4aa26 | 520 | let deps2 = vid_map.entry(RegionTarget::Region(r2)).or_default(); |
94b46f34 XL |
521 | deps2.smaller.insert(RegionTarget::Region(r1)); |
522 | } | |
523 | } | |
524 | } | |
525 | ||
526 | while !vid_map.is_empty() { | |
dfeec247 | 527 | let target = *vid_map.keys().next().expect("Keys somehow empty"); |
94b46f34 XL |
528 | let deps = vid_map.remove(&target).expect("Entry somehow missing"); |
529 | ||
530 | for smaller in deps.smaller.iter() { | |
531 | for larger in deps.larger.iter() { | |
532 | match (smaller, larger) { | |
533 | (&RegionTarget::Region(_), &RegionTarget::Region(_)) => { | |
534 | if let Entry::Occupied(v) = vid_map.entry(*smaller) { | |
535 | let smaller_deps = v.into_mut(); | |
536 | smaller_deps.larger.insert(*larger); | |
537 | smaller_deps.larger.remove(&target); | |
538 | } | |
539 | ||
540 | if let Entry::Occupied(v) = vid_map.entry(*larger) { | |
541 | let larger_deps = v.into_mut(); | |
542 | larger_deps.smaller.insert(*smaller); | |
543 | larger_deps.smaller.remove(&target); | |
544 | } | |
545 | } | |
546 | (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => { | |
547 | finished_map.insert(v1, r1); | |
548 | } | |
549 | (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => { | |
60c5eb7d | 550 | // Do nothing; we don't care about regions that are smaller than vids. |
94b46f34 XL |
551 | } |
552 | (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => { | |
553 | if let Entry::Occupied(v) = vid_map.entry(*smaller) { | |
554 | let smaller_deps = v.into_mut(); | |
555 | smaller_deps.larger.insert(*larger); | |
556 | smaller_deps.larger.remove(&target); | |
557 | } | |
558 | ||
559 | if let Entry::Occupied(v) = vid_map.entry(*larger) { | |
560 | let larger_deps = v.into_mut(); | |
561 | larger_deps.smaller.insert(*smaller); | |
562 | larger_deps.smaller.remove(&target); | |
563 | } | |
564 | } | |
565 | } | |
566 | } | |
567 | } | |
568 | } | |
569 | finished_map | |
570 | } | |
571 | ||
532ac7d7 | 572 | fn is_param_no_infer(&self, substs: SubstsRef<'_>) -> bool { |
ba9703b0 | 573 | self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types()) |
69743fb6 | 574 | } |
94b46f34 | 575 | |
69743fb6 | 576 | pub fn is_of_param(&self, ty: Ty<'_>) -> bool { |
1b1a35ee | 577 | match ty.kind() { |
b7449926 | 578 | ty::Param(_) => true, |
9c376795 | 579 | ty::Alias(ty::Projection, p) => self.is_of_param(p.self_ty()), |
94b46f34 | 580 | _ => false, |
ba9703b0 | 581 | } |
94b46f34 XL |
582 | } |
583 | ||
69743fb6 | 584 | fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool { |
f2b60f7d | 585 | if let Some(ty) = p.term().skip_binder().ty() { |
9c376795 | 586 | matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_ty) |
5099ac24 FG |
587 | } else { |
588 | false | |
589 | } | |
69743fb6 XL |
590 | } |
591 | ||
dc9dc135 | 592 | fn evaluate_nested_obligations( |
94b46f34 | 593 | &self, |
48663c56 | 594 | ty: Ty<'_>, |
dc9dc135 | 595 | nested: impl Iterator<Item = Obligation<'tcx, ty::Predicate<'tcx>>>, |
487cf647 | 596 | computed_preds: &mut FxIndexSet<ty::Predicate<'tcx>>, |
dc9dc135 XL |
597 | fresh_preds: &mut FxHashSet<ty::Predicate<'tcx>>, |
598 | predicates: &mut VecDeque<ty::PolyTraitPredicate<'tcx>>, | |
487cf647 | 599 | selcx: &mut SelectionContext<'_, 'tcx>, |
94b46f34 | 600 | ) -> bool { |
ba9703b0 | 601 | let dummy_cause = ObligationCause::dummy(); |
94b46f34 | 602 | |
3dfed10e XL |
603 | for obligation in nested { |
604 | let is_new_pred = | |
487cf647 | 605 | fresh_preds.insert(self.clean_pred(selcx.infcx, obligation.predicate)); |
94b46f34 | 606 | |
69743fb6 | 607 | // Resolve any inference variables that we can, to help selection succeed |
487cf647 | 608 | let predicate = selcx.infcx.resolve_vars_if_possible(obligation.predicate); |
69743fb6 XL |
609 | |
610 | // We only add a predicate as a user-displayable bound if | |
611 | // it involves a generic parameter, and doesn't contain | |
612 | // any inference variables. | |
613 | // | |
614 | // Displaying a bound involving a concrete type (instead of a generic | |
615 | // parameter) would be pointless, since it's always true | |
616 | // (e.g. u8: Copy) | |
617 | // Displaying an inference variable is impossible, since they're | |
618 | // an internal compiler detail without a defined visual representation | |
619 | // | |
620 | // We check this by calling is_of_param on the relevant types | |
621 | // from the various possible predicates | |
3dfed10e | 622 | |
5869c6ff | 623 | let bound_predicate = predicate.kind(); |
29967ef6 | 624 | match bound_predicate.skip_binder() { |
487cf647 | 625 | ty::PredicateKind::Clause(ty::Clause::Trait(p)) => { |
5869c6ff XL |
626 | // Add this to `predicates` so that we end up calling `select` |
627 | // with it. If this predicate ends up being unimplemented, | |
628 | // then `evaluate_predicates` will handle adding it the `ParamEnv` | |
629 | // if possible. | |
29967ef6 | 630 | predicates.push_back(bound_predicate.rebind(p)); |
94b46f34 | 631 | } |
487cf647 | 632 | ty::PredicateKind::Clause(ty::Clause::Projection(p)) => { |
29967ef6 | 633 | let p = bound_predicate.rebind(p); |
dfeec247 XL |
634 | debug!( |
635 | "evaluate_nested_obligations: examining projection predicate {:?}", | |
636 | predicate | |
637 | ); | |
69743fb6 XL |
638 | |
639 | // As described above, we only want to display | |
640 | // bounds which include a generic parameter but don't include | |
641 | // an inference variable. | |
642 | // Additionally, we check if we've seen this predicate before, | |
643 | // to avoid rendering duplicate bounds to the user. | |
644 | if self.is_param_no_infer(p.skip_binder().projection_ty.substs) | |
5099ac24 | 645 | && !p.term().skip_binder().has_infer_types() |
dfeec247 XL |
646 | && is_new_pred |
647 | { | |
648 | debug!( | |
5e7ed085 | 649 | "evaluate_nested_obligations: adding projection predicate \ |
dfeec247 XL |
650 | to computed_preds: {:?}", |
651 | predicate | |
652 | ); | |
653 | ||
5e7ed085 | 654 | // Under unusual circumstances, we can end up with a self-referential |
dfeec247 XL |
655 | // projection predicate. For example: |
656 | // <T as MyType>::Value == <T as MyType>::Value | |
657 | // Not only is displaying this to the user pointless, | |
658 | // having it in the ParamEnv will cause an issue if we try to call | |
659 | // poly_project_and_unify_type on the predicate, since this kind of | |
660 | // predicate will normally never end up in a ParamEnv. | |
661 | // | |
662 | // For these reasons, we ignore these weird predicates, | |
663 | // ensuring that we're able to properly synthesize an auto trait impl | |
664 | if self.is_self_referential_projection(p) { | |
665 | debug!( | |
666 | "evaluate_nested_obligations: encountered a projection | |
667 | predicate equating a type with itself! Skipping" | |
668 | ); | |
669 | } else { | |
670 | self.add_user_pred(computed_preds, predicate); | |
671 | } | |
69743fb6 XL |
672 | } |
673 | ||
dc9dc135 XL |
674 | // There are three possible cases when we project a predicate: |
675 | // | |
676 | // 1. We encounter an error. This means that it's impossible for | |
677 | // our current type to implement the auto trait - there's bound | |
678 | // that we could add to our ParamEnv that would 'fix' this kind | |
679 | // of error, as it's not caused by an unimplemented type. | |
680 | // | |
60c5eb7d | 681 | // 2. We successfully project the predicate (Ok(Some(_))), generating |
dc9dc135 XL |
682 | // some subobligations. We then process these subobligations |
683 | // like any other generated sub-obligations. | |
684 | // | |
74b04a01 | 685 | // 3. We receive an 'ambiguous' result (Ok(None)) |
dc9dc135 XL |
686 | // If we were actually trying to compile a crate, |
687 | // we would need to re-process this obligation later. | |
688 | // However, all we care about is finding out what bounds | |
689 | // are needed for our type to implement a particular auto trait. | |
690 | // We've already added this obligation to our computed ParamEnv | |
691 | // above (if it was necessary). Therefore, we don't need | |
692 | // to do any further processing of the obligation. | |
693 | // | |
694 | // Note that we *must* try to project *all* projection predicates | |
695 | // we encounter, even ones without inference variable. | |
696 | // This ensures that we detect any projection errors, | |
697 | // which indicate that our type can *never* implement the given | |
698 | // auto trait. In that case, we will generate an explicit negative | |
699 | // impl (e.g. 'impl !Send for MyType'). However, we don't | |
700 | // try to process any of the generated subobligations - | |
701 | // they contain no new information, since we already know | |
702 | // that our type implements the projected-through trait, | |
703 | // and can lead to weird region issues. | |
704 | // | |
705 | // Normally, we'll generate a negative impl as a result of encountering | |
706 | // a type with an explicit negative impl of an auto trait | |
707 | // (for example, raw pointers have !Send and !Sync impls) | |
708 | // However, through some **interesting** manipulations of the type | |
709 | // system, it's actually possible to write a type that never | |
710 | // implements an auto trait due to a projection error, not a normal | |
711 | // negative impl error. To properly handle this case, we need | |
712 | // to ensure that we catch any potential projection errors, | |
713 | // and turn them into an explicit negative impl for our type. | |
dfeec247 | 714 | debug!("Projecting and unifying projection predicate {:?}", predicate); |
dc9dc135 | 715 | |
487cf647 FG |
716 | match project::poly_project_and_unify_type(selcx, &obligation.with(self.tcx, p)) |
717 | { | |
5e7ed085 | 718 | ProjectAndUnifyResult::MismatchedProjectionTypes(e) => { |
dc9dc135 XL |
719 | debug!( |
720 | "evaluate_nested_obligations: Unable to unify predicate \ | |
721 | '{:?}' '{:?}', bailing out", | |
722 | ty, e | |
723 | ); | |
724 | return false; | |
725 | } | |
5e7ed085 | 726 | ProjectAndUnifyResult::Recursive => { |
f9652781 XL |
727 | debug!("evaluate_nested_obligations: recursive projection predicate"); |
728 | return false; | |
729 | } | |
5e7ed085 | 730 | ProjectAndUnifyResult::Holds(v) => { |
dc9dc135 XL |
731 | // We only care about sub-obligations |
732 | // when we started out trying to unify | |
733 | // some inference variables. See the comment above | |
5e7ed085 | 734 | // for more information |
5099ac24 | 735 | if p.term().skip_binder().has_infer_types() { |
94b46f34 XL |
736 | if !self.evaluate_nested_obligations( |
737 | ty, | |
ba9703b0 | 738 | v.into_iter(), |
94b46f34 XL |
739 | computed_preds, |
740 | fresh_preds, | |
741 | predicates, | |
487cf647 | 742 | selcx, |
94b46f34 XL |
743 | ) { |
744 | return false; | |
745 | } | |
746 | } | |
dc9dc135 | 747 | } |
5e7ed085 | 748 | ProjectAndUnifyResult::FailedNormalization => { |
f9652781 | 749 | // It's ok not to make progress when have no inference variables - |
5e7ed085 | 750 | // in that case, we were only performing unification to check if an |
60c5eb7d | 751 | // error occurred (which would indicate that it's impossible for our |
dc9dc135 XL |
752 | // type to implement the auto trait). |
753 | // However, we should always make progress (either by generating | |
754 | // subobligations or getting an error) when we started off with | |
755 | // inference variables | |
5099ac24 | 756 | if p.term().skip_binder().has_infer_types() { |
94b46f34 XL |
757 | panic!("Unexpected result when selecting {:?} {:?}", ty, obligation) |
758 | } | |
759 | } | |
760 | } | |
761 | } | |
487cf647 | 762 | ty::PredicateKind::Clause(ty::Clause::RegionOutlives(binder)) => { |
29967ef6 | 763 | let binder = bound_predicate.rebind(binder); |
487cf647 | 764 | selcx.infcx.region_outlives_predicate(&dummy_cause, binder) |
94b46f34 | 765 | } |
487cf647 | 766 | ty::PredicateKind::Clause(ty::Clause::TypeOutlives(binder)) => { |
29967ef6 | 767 | let binder = bound_predicate.rebind(binder); |
94b46f34 | 768 | match ( |
a1dfa0c6 XL |
769 | binder.no_bound_vars(), |
770 | binder.map_bound_ref(|pred| pred.0).no_bound_vars(), | |
94b46f34 XL |
771 | ) { |
772 | (None, Some(t_a)) => { | |
487cf647 | 773 | selcx.infcx.register_region_obligation_with_cause( |
0bf4aa26 | 774 | t_a, |
487cf647 | 775 | selcx.infcx.tcx.lifetimes.re_static, |
0bf4aa26 | 776 | &dummy_cause, |
94b46f34 XL |
777 | ); |
778 | } | |
779 | (Some(ty::OutlivesPredicate(t_a, r_b)), _) => { | |
487cf647 | 780 | selcx.infcx.register_region_obligation_with_cause( |
0bf4aa26 XL |
781 | t_a, |
782 | r_b, | |
783 | &dummy_cause, | |
94b46f34 XL |
784 | ); |
785 | } | |
786 | _ => {} | |
787 | }; | |
788 | } | |
5869c6ff | 789 | ty::PredicateKind::ConstEquate(c1, c2) => { |
5099ac24 | 790 | let evaluate = |c: ty::Const<'tcx>| { |
923072b8 | 791 | if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() { |
487cf647 | 792 | match selcx.infcx.const_eval_resolve( |
3dfed10e | 793 | obligation.param_env, |
cdc7bbd5 | 794 | unevaluated, |
3dfed10e XL |
795 | Some(obligation.cause.span), |
796 | ) { | |
487cf647 | 797 | Ok(Some(valtree)) => Ok(selcx.tcx().mk_const(valtree, c.ty())), |
923072b8 FG |
798 | Ok(None) => { |
799 | let tcx = self.tcx; | |
800 | let def_id = unevaluated.def.did; | |
f2b60f7d FG |
801 | let reported = |
802 | tcx.sess.emit_err(UnableToConstructConstantValue { | |
803 | span: tcx.def_span(def_id), | |
2b03887a | 804 | unevaluated: unevaluated, |
f2b60f7d | 805 | }); |
923072b8 FG |
806 | Err(ErrorHandled::Reported(reported)) |
807 | } | |
3dfed10e XL |
808 | Err(err) => Err(err), |
809 | } | |
810 | } else { | |
811 | Ok(c) | |
812 | } | |
813 | }; | |
814 | ||
815 | match (evaluate(c1), evaluate(c2)) { | |
816 | (Ok(c1), Ok(c2)) => { | |
487cf647 | 817 | match selcx.infcx.at(&obligation.cause, obligation.param_env).eq(c1, c2) |
3dfed10e XL |
818 | { |
819 | Ok(_) => (), | |
820 | Err(_) => return false, | |
821 | } | |
822 | } | |
823 | _ => return false, | |
824 | } | |
825 | } | |
a2a8927a XL |
826 | // There's not really much we can do with these predicates - |
827 | // we start out with a `ParamEnv` with no inference variables, | |
828 | // and these don't correspond to adding any new bounds to | |
829 | // the `ParamEnv`. | |
830 | ty::PredicateKind::WellFormed(..) | |
831 | | ty::PredicateKind::ObjectSafe(..) | |
832 | | ty::PredicateKind::ClosureKind(..) | |
833 | | ty::PredicateKind::Subtype(..) | |
834 | | ty::PredicateKind::ConstEvaluatable(..) | |
835 | | ty::PredicateKind::Coerce(..) | |
836 | | ty::PredicateKind::TypeWellFormedFromEnv(..) => {} | |
487cf647 | 837 | ty::PredicateKind::Ambiguous => return false, |
94b46f34 XL |
838 | }; |
839 | } | |
ba9703b0 | 840 | true |
94b46f34 XL |
841 | } |
842 | ||
dc9dc135 | 843 | pub fn clean_pred( |
94b46f34 | 844 | &self, |
2b03887a | 845 | infcx: &InferCtxt<'tcx>, |
dc9dc135 XL |
846 | p: ty::Predicate<'tcx>, |
847 | ) -> ty::Predicate<'tcx> { | |
94b46f34 XL |
848 | infcx.freshen(p) |
849 | } | |
850 | } | |
851 | ||
487cf647 | 852 | /// Replaces all ReVars in a type with ty::Region's, using the provided map |
dc9dc135 | 853 | pub struct RegionReplacer<'a, 'tcx> { |
94b46f34 | 854 | vid_to_region: &'a FxHashMap<ty::RegionVid, ty::Region<'tcx>>, |
dc9dc135 | 855 | tcx: TyCtxt<'tcx>, |
94b46f34 XL |
856 | } |
857 | ||
dc9dc135 XL |
858 | impl<'a, 'tcx> TypeFolder<'tcx> for RegionReplacer<'a, 'tcx> { |
859 | fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { | |
94b46f34 XL |
860 | self.tcx |
861 | } | |
862 | ||
863 | fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { | |
5099ac24 FG |
864 | (match *r { |
865 | ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(), | |
94b46f34 | 866 | _ => None, |
dfeec247 XL |
867 | }) |
868 | .unwrap_or_else(|| r.super_fold_with(self)) | |
94b46f34 XL |
869 | } |
870 | } |