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