]>
Commit | Line | Data |
---|---|---|
ba9703b0 XL |
1 | //! Trait Resolution. See the [rustc dev guide] for more information on how this works. |
2 | //! | |
3 | //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html | |
4 | ||
ba9703b0 | 5 | pub mod auto_trait; |
f9f354fc | 6 | mod chalk_fulfill; |
ba9703b0 XL |
7 | pub mod codegen; |
8 | mod coherence; | |
5869c6ff | 9 | pub mod const_evaluatable; |
ba9703b0 XL |
10 | mod engine; |
11 | pub mod error_reporting; | |
12 | mod fulfill; | |
13 | pub mod misc; | |
14 | mod object_safety; | |
15 | mod on_unimplemented; | |
16 | mod project; | |
17 | pub mod query; | |
c295e0f8 | 18 | pub(crate) mod relationships; |
ba9703b0 XL |
19 | mod select; |
20 | mod specialize; | |
21 | mod structural_match; | |
22 | mod util; | |
23 | pub mod wf; | |
24 | ||
25 | use crate::infer::outlives::env::OutlivesEnvironment; | |
26 | use crate::infer::{InferCtxt, RegionckMode, TyCtxtInferExt}; | |
27 | use crate::traits::error_reporting::InferCtxtExt as _; | |
28 | use crate::traits::query::evaluate_obligation::InferCtxtExt as _; | |
5e7ed085 | 29 | use rustc_errors::ErrorGuaranteed; |
ba9703b0 XL |
30 | use rustc_hir as hir; |
31 | use rustc_hir::def_id::DefId; | |
94222f64 | 32 | use rustc_hir::lang_items::LangItem; |
ba9703b0 XL |
33 | use rustc_middle::ty::fold::TypeFoldable; |
34 | use rustc_middle::ty::subst::{InternalSubsts, SubstsRef}; | |
f9f354fc | 35 | use rustc_middle::ty::{ |
a2a8927a | 36 | self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry, COMMON_VTABLE_ENTRIES, |
f9f354fc | 37 | }; |
94222f64 XL |
38 | use rustc_span::{sym, Span}; |
39 | use smallvec::SmallVec; | |
ba9703b0 XL |
40 | |
41 | use std::fmt::Debug; | |
94222f64 | 42 | use std::ops::ControlFlow; |
ba9703b0 XL |
43 | |
44 | pub use self::FulfillmentErrorCode::*; | |
f035d41b | 45 | pub use self::ImplSource::*; |
ba9703b0 XL |
46 | pub use self::ObligationCauseCode::*; |
47 | pub use self::SelectionError::*; | |
ba9703b0 XL |
48 | |
49 | pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls}; | |
50 | pub use self::coherence::{OrphanCheckErr, OverlapResult}; | |
51 | pub use self::engine::TraitEngineExt; | |
52 | pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation}; | |
53 | pub use self::object_safety::astconv_object_safety_violations; | |
54 | pub use self::object_safety::is_vtable_safe_method; | |
55 | pub use self::object_safety::MethodViolationCode; | |
56 | pub use self::object_safety::ObjectSafetyViolation; | |
57 | pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote}; | |
f9652781 | 58 | pub use self::project::{normalize, normalize_projection_type, normalize_to}; |
ba9703b0 XL |
59 | pub use self::select::{EvaluationCache, SelectionCache, SelectionContext}; |
60 | pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError}; | |
61 | pub use self::specialize::specialization_graph::FutureCompatOverlapError; | |
62 | pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind; | |
63 | pub use self::specialize::{specialization_graph, translate_substs, OverlapError}; | |
64 | pub use self::structural_match::search_for_structural_match_violation; | |
ba9703b0 | 65 | pub use self::structural_match::NonStructuralMatchTy; |
c295e0f8 | 66 | pub use self::util::{ |
3c0e092e XL |
67 | elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span, |
68 | elaborate_trait_ref, elaborate_trait_refs, | |
c295e0f8 | 69 | }; |
ba9703b0 XL |
70 | pub use self::util::{expand_trait_aliases, TraitAliasExpander}; |
71 | pub use self::util::{ | |
72 | get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices, | |
73 | }; | |
74 | pub use self::util::{ | |
6a06907d XL |
75 | supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type, |
76 | SupertraitDefIds, Supertraits, | |
ba9703b0 XL |
77 | }; |
78 | ||
f9f354fc XL |
79 | pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext; |
80 | ||
ba9703b0 XL |
81 | pub use rustc_infer::traits::*; |
82 | ||
83 | /// Whether to skip the leak check, as part of a future compatibility warning step. | |
3c0e092e XL |
84 | /// |
85 | /// The "default" for skip-leak-check corresponds to the current | |
86 | /// behavior (do not skip the leak check) -- not the behavior we are | |
87 | /// transitioning into. | |
88 | #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] | |
ba9703b0 XL |
89 | pub enum SkipLeakCheck { |
90 | Yes, | |
3c0e092e | 91 | #[default] |
ba9703b0 XL |
92 | No, |
93 | } | |
94 | ||
95 | impl SkipLeakCheck { | |
96 | fn is_yes(self) -> bool { | |
97 | self == SkipLeakCheck::Yes | |
98 | } | |
99 | } | |
100 | ||
ba9703b0 XL |
101 | /// The mode that trait queries run in. |
102 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
103 | pub enum TraitQueryMode { | |
fc512014 XL |
104 | /// Standard/un-canonicalized queries get accurate |
105 | /// spans etc. passed in and hence can do reasonable | |
106 | /// error reporting on their own. | |
ba9703b0 | 107 | Standard, |
fc512014 XL |
108 | /// Canonicalized queries get dummy spans and hence |
109 | /// must generally propagate errors to | |
110 | /// pre-canonicalization callsites. | |
ba9703b0 XL |
111 | Canonical, |
112 | } | |
113 | ||
114 | /// Creates predicate obligations from the generic bounds. | |
115 | pub fn predicates_for_generics<'tcx>( | |
116 | cause: ObligationCause<'tcx>, | |
117 | param_env: ty::ParamEnv<'tcx>, | |
118 | generic_bounds: ty::InstantiatedPredicates<'tcx>, | |
119 | ) -> impl Iterator<Item = PredicateObligation<'tcx>> { | |
120 | util::predicates_for_generics(cause, 0, param_env, generic_bounds) | |
121 | } | |
122 | ||
123 | /// Determines whether the type `ty` is known to meet `bound` and | |
124 | /// returns true if so. Returns false if `ty` either does not meet | |
125 | /// `bound` or is not known to meet bound (note that this is | |
126 | /// conservative towards *no impl*, which is the opposite of the | |
127 | /// `evaluate` methods). | |
128 | pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>( | |
129 | infcx: &InferCtxt<'a, 'tcx>, | |
130 | param_env: ty::ParamEnv<'tcx>, | |
131 | ty: Ty<'tcx>, | |
132 | def_id: DefId, | |
133 | span: Span, | |
134 | ) -> bool { | |
135 | debug!( | |
136 | "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})", | |
137 | ty, | |
138 | infcx.tcx.def_path_str(def_id) | |
139 | ); | |
140 | ||
c295e0f8 XL |
141 | let trait_ref = |
142 | ty::Binder::dummy(ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) }); | |
ba9703b0 XL |
143 | let obligation = Obligation { |
144 | param_env, | |
145 | cause: ObligationCause::misc(span, hir::CRATE_HIR_ID), | |
146 | recursion_depth: 0, | |
f9f354fc | 147 | predicate: trait_ref.without_const().to_predicate(infcx.tcx), |
ba9703b0 XL |
148 | }; |
149 | ||
150 | let result = infcx.predicate_must_hold_modulo_regions(&obligation); | |
151 | debug!( | |
152 | "type_known_to_meet_ty={:?} bound={} => {:?}", | |
153 | ty, | |
154 | infcx.tcx.def_path_str(def_id), | |
155 | result | |
156 | ); | |
157 | ||
158 | if result && ty.has_infer_types_or_consts() { | |
159 | // Because of inference "guessing", selection can sometimes claim | |
160 | // to succeed while the success requires a guess. To ensure | |
161 | // this function's result remains infallible, we must confirm | |
162 | // that guess. While imperfect, I believe this is sound. | |
163 | ||
164 | // The handling of regions in this area of the code is terrible, | |
165 | // see issue #29149. We should be able to improve on this with | |
166 | // NLL. | |
167 | let mut fulfill_cx = FulfillmentContext::new_ignoring_regions(); | |
168 | ||
169 | // We can use a dummy node-id here because we won't pay any mind | |
170 | // to region obligations that arise (there shouldn't really be any | |
171 | // anyhow). | |
172 | let cause = ObligationCause::misc(span, hir::CRATE_HIR_ID); | |
173 | ||
174 | fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause); | |
175 | ||
176 | // Note: we only assume something is `Copy` if we can | |
177 | // *definitively* show that it implements `Copy`. Otherwise, | |
178 | // assume it is move; linear is always ok. | |
3c0e092e XL |
179 | match fulfill_cx.select_all_or_error(infcx).as_slice() { |
180 | [] => { | |
ba9703b0 XL |
181 | debug!( |
182 | "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success", | |
183 | ty, | |
184 | infcx.tcx.def_path_str(def_id) | |
185 | ); | |
186 | true | |
187 | } | |
3c0e092e | 188 | errors => { |
ba9703b0 | 189 | debug!( |
3c0e092e XL |
190 | ?ty, |
191 | bound = %infcx.tcx.def_path_str(def_id), | |
192 | ?errors, | |
193 | "type_known_to_meet_bound_modulo_regions" | |
ba9703b0 XL |
194 | ); |
195 | false | |
196 | } | |
197 | } | |
198 | } else { | |
199 | result | |
200 | } | |
201 | } | |
202 | ||
203 | fn do_normalize_predicates<'tcx>( | |
204 | tcx: TyCtxt<'tcx>, | |
205 | region_context: DefId, | |
206 | cause: ObligationCause<'tcx>, | |
207 | elaborated_env: ty::ParamEnv<'tcx>, | |
208 | predicates: Vec<ty::Predicate<'tcx>>, | |
5e7ed085 | 209 | ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> { |
ba9703b0 XL |
210 | debug!( |
211 | "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})", | |
212 | predicates, region_context, cause, | |
213 | ); | |
214 | let span = cause.span; | |
215 | tcx.infer_ctxt().enter(|infcx| { | |
216 | // FIXME. We should really... do something with these region | |
217 | // obligations. But this call just continues the older | |
218 | // behavior (i.e., doesn't cause any new bugs), and it would | |
219 | // take some further refactoring to actually solve them. In | |
220 | // particular, we would have to handle implied bounds | |
221 | // properly, and that code is currently largely confined to | |
222 | // regionck (though I made some efforts to extract it | |
223 | // out). -nmatsakis | |
224 | // | |
225 | // @arielby: In any case, these obligations are checked | |
226 | // by wfcheck anyway, so I'm not sure we have to check | |
227 | // them here too, and we will remove this function when | |
228 | // we move over to lazy normalization *anyway*. | |
229 | let fulfill_cx = FulfillmentContext::new_ignoring_regions(); | |
230 | let predicates = | |
fc512014 | 231 | match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, predicates) { |
ba9703b0 XL |
232 | Ok(predicates) => predicates, |
233 | Err(errors) => { | |
5e7ed085 FG |
234 | let reported = infcx.report_fulfillment_errors(&errors, None, false); |
235 | return Err(reported); | |
ba9703b0 XL |
236 | } |
237 | }; | |
238 | ||
239 | debug!("do_normalize_predictes: normalized predicates = {:?}", predicates); | |
240 | ||
ba9703b0 XL |
241 | // We can use the `elaborated_env` here; the region code only |
242 | // cares about declarations like `'a: 'b`. | |
243 | let outlives_env = OutlivesEnvironment::new(elaborated_env); | |
244 | ||
245 | infcx.resolve_regions_and_report_errors( | |
246 | region_context, | |
ba9703b0 XL |
247 | &outlives_env, |
248 | RegionckMode::default(), | |
249 | ); | |
250 | ||
fc512014 | 251 | let predicates = match infcx.fully_resolve(predicates) { |
ba9703b0 XL |
252 | Ok(predicates) => predicates, |
253 | Err(fixup_err) => { | |
254 | // If we encounter a fixup error, it means that some type | |
255 | // variable wound up unconstrained. I actually don't know | |
256 | // if this can happen, and I certainly don't expect it to | |
257 | // happen often, but if it did happen it probably | |
258 | // represents a legitimate failure due to some kind of | |
259 | // unconstrained variable, and it seems better not to ICE, | |
260 | // all things considered. | |
5e7ed085 FG |
261 | let reported = tcx.sess.span_err(span, &fixup_err.to_string()); |
262 | return Err(reported); | |
ba9703b0 XL |
263 | } |
264 | }; | |
265 | if predicates.needs_infer() { | |
5e7ed085 FG |
266 | let reported = tcx |
267 | .sess | |
268 | .delay_span_bug(span, "encountered inference variables after `fully_resolve`"); | |
269 | Err(reported) | |
ba9703b0 XL |
270 | } else { |
271 | Ok(predicates) | |
272 | } | |
273 | }) | |
274 | } | |
275 | ||
276 | // FIXME: this is gonna need to be removed ... | |
277 | /// Normalizes the parameter environment, reporting errors if they occur. | |
278 | pub fn normalize_param_env_or_error<'tcx>( | |
279 | tcx: TyCtxt<'tcx>, | |
280 | region_context: DefId, | |
281 | unnormalized_env: ty::ParamEnv<'tcx>, | |
282 | cause: ObligationCause<'tcx>, | |
283 | ) -> ty::ParamEnv<'tcx> { | |
284 | // I'm not wild about reporting errors here; I'd prefer to | |
285 | // have the errors get reported at a defined place (e.g., | |
286 | // during typeck). Instead I have all parameter | |
287 | // environments, in effect, going through this function | |
288 | // and hence potentially reporting errors. This ensures of | |
289 | // course that we never forget to normalize (the | |
290 | // alternative seemed like it would involve a lot of | |
291 | // manual invocations of this fn -- and then we'd have to | |
292 | // deal with the errors at each of those sites). | |
293 | // | |
294 | // In any case, in practice, typeck constructs all the | |
295 | // parameter environments once for every fn as it goes, | |
5099ac24 | 296 | // and errors will get reported then; so outside of type inference we |
ba9703b0 XL |
297 | // can be sure that no errors should occur. |
298 | ||
299 | debug!( | |
300 | "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})", | |
301 | region_context, unnormalized_env, cause | |
302 | ); | |
303 | ||
304 | let mut predicates: Vec<_> = | |
f035d41b | 305 | util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter()) |
ba9703b0 XL |
306 | .map(|obligation| obligation.predicate) |
307 | .collect(); | |
308 | ||
309 | debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates); | |
310 | ||
a2a8927a XL |
311 | let elaborated_env = ty::ParamEnv::new( |
312 | tcx.intern_predicates(&predicates), | |
313 | unnormalized_env.reveal(), | |
314 | unnormalized_env.constness(), | |
315 | ); | |
ba9703b0 XL |
316 | |
317 | // HACK: we are trying to normalize the param-env inside *itself*. The problem is that | |
318 | // normalization expects its param-env to be already normalized, which means we have | |
319 | // a circularity. | |
320 | // | |
321 | // The way we handle this is by normalizing the param-env inside an unnormalized version | |
322 | // of the param-env, which means that if the param-env contains unnormalized projections, | |
323 | // we'll have some normalization failures. This is unfortunate. | |
324 | // | |
325 | // Lazy normalization would basically handle this by treating just the | |
326 | // normalizing-a-trait-ref-requires-itself cycles as evaluation failures. | |
327 | // | |
328 | // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated | |
329 | // types, so to make the situation less bad, we normalize all the predicates *but* | |
330 | // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and | |
331 | // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment. | |
332 | // | |
333 | // This works fairly well because trait matching does not actually care about param-env | |
334 | // TypeOutlives predicates - these are normally used by regionck. | |
335 | let outlives_predicates: Vec<_> = predicates | |
5869c6ff XL |
336 | .drain_filter(|predicate| { |
337 | matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..)) | |
ba9703b0 XL |
338 | }) |
339 | .collect(); | |
340 | ||
341 | debug!( | |
342 | "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})", | |
343 | predicates, outlives_predicates | |
344 | ); | |
5e7ed085 | 345 | let Ok(non_outlives_predicates) = do_normalize_predicates( |
ba9703b0 XL |
346 | tcx, |
347 | region_context, | |
348 | cause.clone(), | |
349 | elaborated_env, | |
350 | predicates, | |
5e7ed085 | 351 | ) else { |
ba9703b0 | 352 | // An unnormalized env is better than nothing. |
5e7ed085 FG |
353 | debug!("normalize_param_env_or_error: errored resolving non-outlives predicates"); |
354 | return elaborated_env; | |
ba9703b0 XL |
355 | }; |
356 | ||
357 | debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates); | |
358 | ||
359 | // Not sure whether it is better to include the unnormalized TypeOutlives predicates | |
360 | // here. I believe they should not matter, because we are ignoring TypeOutlives param-env | |
361 | // predicates here anyway. Keeping them here anyway because it seems safer. | |
362 | let outlives_env: Vec<_> = | |
363 | non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect(); | |
a2a8927a XL |
364 | let outlives_env = ty::ParamEnv::new( |
365 | tcx.intern_predicates(&outlives_env), | |
366 | unnormalized_env.reveal(), | |
367 | unnormalized_env.constness(), | |
368 | ); | |
5e7ed085 | 369 | let Ok(outlives_predicates) = do_normalize_predicates( |
ba9703b0 XL |
370 | tcx, |
371 | region_context, | |
372 | cause, | |
373 | outlives_env, | |
374 | outlives_predicates, | |
5e7ed085 | 375 | ) else { |
ba9703b0 | 376 | // An unnormalized env is better than nothing. |
5e7ed085 FG |
377 | debug!("normalize_param_env_or_error: errored resolving outlives predicates"); |
378 | return elaborated_env; | |
ba9703b0 XL |
379 | }; |
380 | debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates); | |
381 | ||
382 | let mut predicates = non_outlives_predicates; | |
383 | predicates.extend(outlives_predicates); | |
384 | debug!("normalize_param_env_or_error: final predicates={:?}", predicates); | |
a2a8927a XL |
385 | ty::ParamEnv::new( |
386 | tcx.intern_predicates(&predicates), | |
387 | unnormalized_env.reveal(), | |
388 | unnormalized_env.constness(), | |
389 | ) | |
ba9703b0 XL |
390 | } |
391 | ||
392 | pub fn fully_normalize<'a, 'tcx, T>( | |
393 | infcx: &InferCtxt<'a, 'tcx>, | |
394 | mut fulfill_cx: FulfillmentContext<'tcx>, | |
395 | cause: ObligationCause<'tcx>, | |
396 | param_env: ty::ParamEnv<'tcx>, | |
fc512014 | 397 | value: T, |
ba9703b0 XL |
398 | ) -> Result<T, Vec<FulfillmentError<'tcx>>> |
399 | where | |
400 | T: TypeFoldable<'tcx>, | |
401 | { | |
402 | debug!("fully_normalize_with_fulfillcx(value={:?})", value); | |
403 | let selcx = &mut SelectionContext::new(infcx); | |
404 | let Normalized { value: normalized_value, obligations } = | |
405 | project::normalize(selcx, param_env, cause, value); | |
406 | debug!( | |
407 | "fully_normalize: normalized_value={:?} obligations={:?}", | |
408 | normalized_value, obligations | |
409 | ); | |
410 | for obligation in obligations { | |
411 | fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation); | |
412 | } | |
413 | ||
414 | debug!("fully_normalize: select_all_or_error start"); | |
3c0e092e XL |
415 | let errors = fulfill_cx.select_all_or_error(infcx); |
416 | if !errors.is_empty() { | |
417 | return Err(errors); | |
418 | } | |
ba9703b0 | 419 | debug!("fully_normalize: select_all_or_error complete"); |
fc512014 | 420 | let resolved_value = infcx.resolve_vars_if_possible(normalized_value); |
ba9703b0 XL |
421 | debug!("fully_normalize: resolved_value={:?}", resolved_value); |
422 | Ok(resolved_value) | |
423 | } | |
424 | ||
3dfed10e XL |
425 | /// Normalizes the predicates and checks whether they hold in an empty environment. If this |
426 | /// returns true, then either normalize encountered an error or one of the predicates did not | |
427 | /// hold. Used when creating vtables to check for unsatisfiable methods. | |
428 | pub fn impossible_predicates<'tcx>( | |
ba9703b0 XL |
429 | tcx: TyCtxt<'tcx>, |
430 | predicates: Vec<ty::Predicate<'tcx>>, | |
431 | ) -> bool { | |
3dfed10e | 432 | debug!("impossible_predicates(predicates={:?})", predicates); |
ba9703b0 XL |
433 | |
434 | let result = tcx.infer_ctxt().enter(|infcx| { | |
435 | let param_env = ty::ParamEnv::reveal_all(); | |
436 | let mut selcx = SelectionContext::new(&infcx); | |
437 | let mut fulfill_cx = FulfillmentContext::new(); | |
438 | let cause = ObligationCause::dummy(); | |
439 | let Normalized { value: predicates, obligations } = | |
fc512014 | 440 | normalize(&mut selcx, param_env, cause.clone(), predicates); |
ba9703b0 XL |
441 | for obligation in obligations { |
442 | fulfill_cx.register_predicate_obligation(&infcx, obligation); | |
443 | } | |
444 | for predicate in predicates { | |
445 | let obligation = Obligation::new(cause.clone(), param_env, predicate); | |
446 | fulfill_cx.register_predicate_obligation(&infcx, obligation); | |
447 | } | |
448 | ||
3c0e092e XL |
449 | let errors = fulfill_cx.select_all_or_error(&infcx); |
450 | ||
451 | !errors.is_empty() | |
ba9703b0 | 452 | }); |
fc512014 | 453 | debug!("impossible_predicates = {:?}", result); |
ba9703b0 XL |
454 | result |
455 | } | |
456 | ||
3dfed10e | 457 | fn subst_and_check_impossible_predicates<'tcx>( |
ba9703b0 XL |
458 | tcx: TyCtxt<'tcx>, |
459 | key: (DefId, SubstsRef<'tcx>), | |
460 | ) -> bool { | |
3dfed10e | 461 | debug!("subst_and_check_impossible_predicates(key={:?})", key); |
ba9703b0 | 462 | |
3dfed10e | 463 | let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates; |
5099ac24 | 464 | predicates.retain(|predicate| !predicate.needs_subst()); |
3dfed10e | 465 | let result = impossible_predicates(tcx, predicates); |
ba9703b0 | 466 | |
3dfed10e | 467 | debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result); |
ba9703b0 XL |
468 | result |
469 | } | |
470 | ||
94222f64 XL |
471 | #[derive(Clone, Debug)] |
472 | enum VtblSegment<'tcx> { | |
473 | MetadataDSA, | |
474 | TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool }, | |
475 | } | |
476 | ||
477 | /// Prepare the segments for a vtable | |
478 | fn prepare_vtable_segments<'tcx, T>( | |
479 | tcx: TyCtxt<'tcx>, | |
480 | trait_ref: ty::PolyTraitRef<'tcx>, | |
481 | mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>, | |
482 | ) -> Option<T> { | |
483 | // The following constraints holds for the final arrangement. | |
484 | // 1. The whole virtual table of the first direct super trait is included as the | |
485 | // the prefix. If this trait doesn't have any super traits, then this step | |
486 | // consists of the dsa metadata. | |
487 | // 2. Then comes the proper pointer metadata(vptr) and all own methods for all | |
488 | // other super traits except those already included as part of the first | |
489 | // direct super trait virtual table. | |
490 | // 3. finally, the own methods of this trait. | |
491 | ||
492 | // This has the advantage that trait upcasting to the first direct super trait on each level | |
493 | // is zero cost, and to another trait includes only replacing the pointer with one level indirection, | |
494 | // while not using too much extra memory. | |
495 | ||
496 | // For a single inheritance relationship like this, | |
497 | // D --> C --> B --> A | |
498 | // The resulting vtable will consists of these segments: | |
499 | // DSA, A, B, C, D | |
500 | ||
501 | // For a multiple inheritance relationship like this, | |
502 | // D --> C --> A | |
503 | // \-> B | |
504 | // The resulting vtable will consists of these segments: | |
505 | // DSA, A, B, B-vptr, C, D | |
506 | ||
507 | // For a diamond inheritance relationship like this, | |
508 | // D --> B --> A | |
509 | // \-> C -/ | |
510 | // The resulting vtable will consists of these segments: | |
511 | // DSA, A, B, C, C-vptr, D | |
512 | ||
513 | // For a more complex inheritance relationship like this: | |
514 | // O --> G --> C --> A | |
515 | // \ \ \-> B | |
516 | // | |-> F --> D | |
517 | // | \-> E | |
518 | // |-> N --> J --> H | |
519 | // \ \-> I | |
520 | // |-> M --> K | |
521 | // \-> L | |
522 | // The resulting vtable will consists of these segments: | |
523 | // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G, | |
524 | // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr, | |
525 | // N, N-vptr, O | |
526 | ||
527 | // emit dsa segment first. | |
528 | if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) { | |
529 | return Some(v); | |
530 | } | |
531 | ||
532 | let mut emit_vptr_on_new_entry = false; | |
533 | let mut visited = util::PredicateSet::new(tcx); | |
534 | let predicate = trait_ref.without_const().to_predicate(tcx); | |
535 | let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> = | |
536 | smallvec![(trait_ref, emit_vptr_on_new_entry, None)]; | |
537 | visited.insert(predicate); | |
538 | ||
539 | // the main traversal loop: | |
540 | // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes | |
5e7ed085 FG |
541 | // that each node is emitted after all its descendents have been emitted. |
542 | // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set. | |
94222f64 XL |
543 | // this is done on the fly. |
544 | // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it | |
545 | // stops after it finds a node that has a next-sibling node. | |
546 | // This next-sibling node will used as the starting point of next slice. | |
547 | ||
548 | // Example: | |
549 | // For a diamond inheritance relationship like this, | |
550 | // D#1 --> B#0 --> A#0 | |
551 | // \-> C#1 -/ | |
552 | ||
553 | // Starting point 0 stack [D] | |
554 | // Loop run #0: Stack after diving in is [D B A], A is "childless" | |
555 | // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one. | |
5e7ed085 | 556 | // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here. |
94222f64 XL |
557 | // Loop run #0: Stack after exiting out is [D C], C is the next starting point. |
558 | // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted). | |
5e7ed085 | 559 | // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node. |
94222f64 XL |
560 | // Loop run #1: Stack after exiting out is []. Now the function exits. |
561 | ||
562 | loop { | |
563 | // dive deeper into the stack, recording the path | |
564 | 'diving_in: loop { | |
565 | if let Some((inner_most_trait_ref, _, _)) = stack.last() { | |
566 | let inner_most_trait_ref = *inner_most_trait_ref; | |
567 | let mut direct_super_traits_iter = tcx | |
568 | .super_predicates_of(inner_most_trait_ref.def_id()) | |
569 | .predicates | |
570 | .into_iter() | |
571 | .filter_map(move |(pred, _)| { | |
a2a8927a | 572 | pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred() |
94222f64 XL |
573 | }); |
574 | ||
575 | 'diving_in_skip_visited_traits: loop { | |
576 | if let Some(next_super_trait) = direct_super_traits_iter.next() { | |
577 | if visited.insert(next_super_trait.to_predicate(tcx)) { | |
a2a8927a XL |
578 | // We're throwing away potential constness of super traits here. |
579 | // FIXME: handle ~const super traits | |
580 | let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref); | |
94222f64 | 581 | stack.push(( |
a2a8927a | 582 | next_super_trait, |
94222f64 XL |
583 | emit_vptr_on_new_entry, |
584 | Some(direct_super_traits_iter), | |
585 | )); | |
586 | break 'diving_in_skip_visited_traits; | |
587 | } else { | |
588 | continue 'diving_in_skip_visited_traits; | |
589 | } | |
590 | } else { | |
591 | break 'diving_in; | |
592 | } | |
593 | } | |
594 | } | |
595 | } | |
596 | ||
597 | // Other than the left-most path, vptr should be emitted for each trait. | |
598 | emit_vptr_on_new_entry = true; | |
599 | ||
600 | // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level. | |
601 | 'exiting_out: loop { | |
602 | if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() { | |
603 | if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries { | |
604 | trait_ref: *inner_most_trait_ref, | |
605 | emit_vptr: *emit_vptr, | |
606 | }) { | |
607 | return Some(v); | |
608 | } | |
609 | ||
610 | 'exiting_out_skip_visited_traits: loop { | |
611 | if let Some(siblings) = siblings_opt { | |
612 | if let Some(next_inner_most_trait_ref) = siblings.next() { | |
613 | if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) { | |
a2a8927a XL |
614 | // We're throwing away potential constness of super traits here. |
615 | // FIXME: handle ~const super traits | |
616 | let next_inner_most_trait_ref = | |
617 | next_inner_most_trait_ref.map_bound(|t| t.trait_ref); | |
618 | *inner_most_trait_ref = next_inner_most_trait_ref; | |
94222f64 XL |
619 | *emit_vptr = emit_vptr_on_new_entry; |
620 | break 'exiting_out; | |
621 | } else { | |
622 | continue 'exiting_out_skip_visited_traits; | |
623 | } | |
624 | } | |
625 | } | |
626 | stack.pop(); | |
627 | continue 'exiting_out; | |
628 | } | |
629 | } | |
630 | // all done | |
631 | return None; | |
632 | } | |
633 | } | |
634 | } | |
635 | ||
636 | fn dump_vtable_entries<'tcx>( | |
637 | tcx: TyCtxt<'tcx>, | |
638 | sp: Span, | |
639 | trait_ref: ty::PolyTraitRef<'tcx>, | |
640 | entries: &[VtblEntry<'tcx>], | |
641 | ) { | |
c295e0f8 | 642 | let msg = format!("vtable entries for `{}`: {:#?}", trait_ref, entries); |
94222f64 XL |
643 | tcx.sess.struct_span_err(sp, &msg).emit(); |
644 | } | |
645 | ||
c295e0f8 XL |
646 | fn own_existential_vtable_entries<'tcx>( |
647 | tcx: TyCtxt<'tcx>, | |
648 | trait_ref: ty::PolyExistentialTraitRef<'tcx>, | |
649 | ) -> &'tcx [DefId] { | |
650 | let trait_methods = tcx | |
651 | .associated_items(trait_ref.def_id()) | |
652 | .in_definition_order() | |
653 | .filter(|item| item.kind == ty::AssocKind::Fn); | |
654 | // Now list each method's DefId (for within its trait). | |
655 | let own_entries = trait_methods.filter_map(move |trait_method| { | |
656 | debug!("own_existential_vtable_entry: trait_method={:?}", trait_method); | |
657 | let def_id = trait_method.def_id; | |
658 | ||
659 | // Some methods cannot be called on an object; skip those. | |
660 | if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) { | |
661 | debug!("own_existential_vtable_entry: not vtable safe"); | |
662 | return None; | |
663 | } | |
664 | ||
665 | Some(def_id) | |
666 | }); | |
667 | ||
668 | tcx.arena.alloc_from_iter(own_entries.into_iter()) | |
669 | } | |
670 | ||
ba9703b0 XL |
671 | /// Given a trait `trait_ref`, iterates the vtable entries |
672 | /// that come from `trait_ref`, including its supertraits. | |
136023e0 | 673 | fn vtable_entries<'tcx>( |
ba9703b0 XL |
674 | tcx: TyCtxt<'tcx>, |
675 | trait_ref: ty::PolyTraitRef<'tcx>, | |
136023e0 XL |
676 | ) -> &'tcx [VtblEntry<'tcx>] { |
677 | debug!("vtable_entries({:?})", trait_ref); | |
678 | ||
94222f64 | 679 | let mut entries = vec![]; |
ba9703b0 | 680 | |
94222f64 XL |
681 | let vtable_segment_callback = |segment| -> ControlFlow<()> { |
682 | match segment { | |
683 | VtblSegment::MetadataDSA => { | |
684 | entries.extend(COMMON_VTABLE_ENTRIES); | |
685 | } | |
686 | VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { | |
c295e0f8 XL |
687 | let existential_trait_ref = trait_ref |
688 | .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)); | |
689 | ||
690 | // Lookup the shape of vtable for the trait. | |
691 | let own_existential_entries = | |
692 | tcx.own_existential_vtable_entries(existential_trait_ref); | |
693 | ||
694 | let own_entries = own_existential_entries.iter().copied().map(|def_id| { | |
695 | debug!("vtable_entries: trait_method={:?}", def_id); | |
94222f64 XL |
696 | |
697 | // The method may have some early-bound lifetimes; add regions for those. | |
698 | let substs = trait_ref.map_bound(|trait_ref| { | |
699 | InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind { | |
700 | GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(), | |
701 | GenericParamDefKind::Type { .. } | |
702 | | GenericParamDefKind::Const { .. } => { | |
703 | trait_ref.substs[param.index as usize] | |
704 | } | |
705 | }) | |
706 | }); | |
707 | ||
708 | // The trait type may have higher-ranked lifetimes in it; | |
709 | // erase them if they appear, so that we get the type | |
710 | // at some particular call site. | |
711 | let substs = tcx | |
712 | .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs); | |
713 | ||
714 | // It's possible that the method relies on where-clauses that | |
715 | // do not hold for this particular set of type parameters. | |
716 | // Note that this method could then never be called, so we | |
717 | // do not want to try and codegen it, in that case (see #23435). | |
718 | let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs); | |
719 | if impossible_predicates(tcx, predicates.predicates) { | |
720 | debug!("vtable_entries: predicates do not hold"); | |
721 | return VtblEntry::Vacant; | |
722 | } | |
723 | ||
724 | let instance = ty::Instance::resolve_for_vtable( | |
725 | tcx, | |
726 | ty::ParamEnv::reveal_all(), | |
727 | def_id, | |
728 | substs, | |
729 | ) | |
730 | .expect("resolution failed during building vtable representation"); | |
731 | VtblEntry::Method(instance) | |
136023e0 XL |
732 | }); |
733 | ||
94222f64 XL |
734 | entries.extend(own_entries); |
735 | ||
736 | if emit_vptr { | |
737 | entries.push(VtblEntry::TraitVPtr(trait_ref)); | |
136023e0 | 738 | } |
94222f64 XL |
739 | } |
740 | } | |
ba9703b0 | 741 | |
94222f64 XL |
742 | ControlFlow::Continue(()) |
743 | }; | |
744 | ||
745 | let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback); | |
136023e0 | 746 | |
94222f64 XL |
747 | if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) { |
748 | let sp = tcx.def_span(trait_ref.def_id()); | |
749 | dump_vtable_entries(tcx, sp, trait_ref, &entries); | |
750 | } | |
751 | ||
752 | tcx.arena.alloc_from_iter(entries.into_iter()) | |
ba9703b0 XL |
753 | } |
754 | ||
136023e0 XL |
755 | /// Find slot base for trait methods within vtable entries of another trait |
756 | fn vtable_trait_first_method_offset<'tcx>( | |
f9f354fc XL |
757 | tcx: TyCtxt<'tcx>, |
758 | key: ( | |
136023e0 XL |
759 | ty::PolyTraitRef<'tcx>, // trait_to_be_found |
760 | ty::PolyTraitRef<'tcx>, // trait_owning_vtable | |
f9f354fc | 761 | ), |
136023e0 XL |
762 | ) -> usize { |
763 | let (trait_to_be_found, trait_owning_vtable) = key; | |
764 | ||
3c0e092e XL |
765 | // #90177 |
766 | let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found); | |
767 | ||
94222f64 XL |
768 | let vtable_segment_callback = { |
769 | let mut vtable_base = 0; | |
136023e0 | 770 | |
94222f64 XL |
771 | move |segment| { |
772 | match segment { | |
773 | VtblSegment::MetadataDSA => { | |
774 | vtable_base += COMMON_VTABLE_ENTRIES.len(); | |
775 | } | |
776 | VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { | |
3c0e092e | 777 | if tcx.erase_regions(trait_ref) == trait_to_be_found_erased { |
94222f64 XL |
778 | return ControlFlow::Break(vtable_base); |
779 | } | |
780 | vtable_base += util::count_own_vtable_entries(tcx, trait_ref); | |
781 | if emit_vptr { | |
782 | vtable_base += 1; | |
783 | } | |
784 | } | |
785 | } | |
786 | ControlFlow::Continue(()) | |
787 | } | |
788 | }; | |
789 | ||
790 | if let Some(vtable_base) = | |
791 | prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback) | |
792 | { | |
793 | vtable_base | |
794 | } else { | |
795 | bug!("Failed to find info for expected trait in vtable"); | |
796 | } | |
797 | } | |
798 | ||
799 | /// Find slot offset for trait vptr within vtable entries of another trait | |
a2a8927a | 800 | pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>( |
94222f64 XL |
801 | tcx: TyCtxt<'tcx>, |
802 | key: ( | |
803 | Ty<'tcx>, // trait object type whose trait owning vtable | |
804 | Ty<'tcx>, // trait object for supertrait | |
805 | ), | |
806 | ) -> Option<usize> { | |
807 | let (source, target) = key; | |
808 | assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer()); | |
809 | assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer()); | |
810 | ||
811 | // this has been typecked-before, so diagnostics is not really needed. | |
812 | let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None); | |
813 | ||
814 | let trait_ref = ty::TraitRef { | |
815 | def_id: unsize_trait_did, | |
816 | substs: tcx.mk_substs_trait(source, &[target.into()]), | |
817 | }; | |
818 | let obligation = Obligation::new( | |
819 | ObligationCause::dummy(), | |
820 | ty::ParamEnv::reveal_all(), | |
821 | ty::Binder::dummy(ty::TraitPredicate { | |
822 | trait_ref, | |
823 | constness: ty::BoundConstness::NotConst, | |
3c0e092e | 824 | polarity: ty::ImplPolarity::Positive, |
94222f64 XL |
825 | }), |
826 | ); | |
827 | ||
828 | let implsrc = tcx.infer_ctxt().enter(|infcx| { | |
829 | let mut selcx = SelectionContext::new(&infcx); | |
830 | selcx.select(&obligation).unwrap() | |
831 | }); | |
832 | ||
5e7ed085 FG |
833 | let Some(ImplSource::TraitUpcasting(implsrc_traitcasting)) = implsrc else { |
834 | bug!(); | |
94222f64 | 835 | }; |
136023e0 | 836 | |
94222f64 | 837 | implsrc_traitcasting.vtable_vptr_slot |
f9f354fc XL |
838 | } |
839 | ||
f035d41b | 840 | pub fn provide(providers: &mut ty::query::Providers) { |
ba9703b0 | 841 | object_safety::provide(providers); |
f035d41b | 842 | structural_match::provide(providers); |
ba9703b0 XL |
843 | *providers = ty::query::Providers { |
844 | specialization_graph_of: specialize::specialization_graph_provider, | |
845 | specializes: specialize::specializes, | |
846 | codegen_fulfill_obligation: codegen::codegen_fulfill_obligation, | |
c295e0f8 | 847 | own_existential_vtable_entries, |
136023e0 | 848 | vtable_entries, |
94222f64 | 849 | vtable_trait_upcasting_coercion_new_vptr_slot, |
3dfed10e | 850 | subst_and_check_impossible_predicates, |
c295e0f8 | 851 | thir_abstract_const: |tcx, def_id| { |
1b1a35ee XL |
852 | let def_id = def_id.expect_local(); |
853 | if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) { | |
c295e0f8 | 854 | tcx.thir_abstract_const_of_const_arg(def) |
1b1a35ee | 855 | } else { |
c295e0f8 | 856 | const_evaluatable::thir_abstract_const(tcx, ty::WithOptConstParam::unknown(def_id)) |
1b1a35ee XL |
857 | } |
858 | }, | |
c295e0f8 XL |
859 | thir_abstract_const_of_const_arg: |tcx, (did, param_did)| { |
860 | const_evaluatable::thir_abstract_const( | |
1b1a35ee XL |
861 | tcx, |
862 | ty::WithOptConstParam { did, const_param_did: Some(param_did) }, | |
863 | ) | |
864 | }, | |
5e7ed085 FG |
865 | try_unify_abstract_consts: |tcx, param_env_and| { |
866 | let (param_env, (a, b)) = param_env_and.into_parts(); | |
867 | const_evaluatable::try_unify_abstract_consts(tcx, (a, b), param_env) | |
868 | }, | |
ba9703b0 XL |
869 | ..*providers |
870 | }; | |
871 | } |