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