rustc_trait_selection/traits/mod.rs
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
5pub mod auto_trait;
6pub(crate) mod coherence;
7pub mod const_evaluatable;
8mod dyn_compatibility;
9pub mod effects;
10mod engine;
11mod fulfill;
12pub mod misc;
13pub mod normalize;
14pub mod outlives_bounds;
15pub mod project;
16pub mod query;
17#[allow(hidden_glob_reexports)]
18mod select;
19mod specialize;
20mod structural_normalize;
21#[allow(hidden_glob_reexports)]
22mod util;
23pub mod vtable;
24pub mod wf;
25
26use std::fmt::Debug;
27use std::ops::ControlFlow;
28
29use rustc_errors::ErrorGuaranteed;
30use rustc_hir::def::DefKind;
31pub use rustc_infer::traits::*;
32use rustc_middle::query::Providers;
33use rustc_middle::span_bug;
34use rustc_middle::ty::error::{ExpectedFound, TypeError};
35use rustc_middle::ty::{
36 self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
37 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode, Upcast,
38};
39use rustc_span::def_id::DefId;
40use rustc_span::{DUMMY_SP, Span};
41use tracing::{debug, instrument};
42
43pub use self::coherence::{
44 InCrate, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams,
45 add_placeholder_note, orphan_check_trait_ref, overlapping_impls,
46};
47pub use self::dyn_compatibility::{
48 DynCompatibilityViolation, dyn_compatibility_violations_for_assoc_item,
49 hir_ty_lowering_dyn_compatibility_violations, is_vtable_safe_method,
50};
51pub use self::engine::{ObligationCtxt, TraitEngineExt};
52pub use self::fulfill::{FulfillmentContext, OldSolverError, PendingPredicateObligation};
53pub use self::normalize::NormalizeExt;
54pub use self::project::{normalize_inherent_projection, normalize_projection_term};
55pub use self::select::{
56 EvaluationCache, EvaluationResult, IntercrateAmbiguityCause, OverflowError, SelectionCache,
57 SelectionContext,
58};
59pub use self::specialize::specialization_graph::{
60 FutureCompatOverlapError, FutureCompatOverlapErrorKind,
61};
62pub use self::specialize::{
63 OverlapError, specialization_graph, translate_args, translate_args_with_cause,
64};
65pub use self::structural_normalize::StructurallyNormalizeExt;
66pub use self::util::{
67 BoundVarReplacer, PlaceholderReplacer, elaborate, expand_trait_aliases, impl_item_is_final,
68 sizedness_fast_path, supertrait_def_ids, supertraits, transitive_bounds_that_define_assoc_item,
69 upcast_choices, with_replaced_escaping_bound_vars,
70};
71use crate::error_reporting::InferCtxtErrorExt;
72use crate::infer::outlives::env::OutlivesEnvironment;
73use crate::infer::{InferCtxt, TyCtxtInferExt};
74use crate::regions::InferCtxtRegionExt;
75use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
76
77#[derive(Debug)]
78pub struct FulfillmentError<'tcx> {
79 pub obligation: PredicateObligation<'tcx>,
80 pub code: FulfillmentErrorCode<'tcx>,
81 /// Diagnostics only: the 'root' obligation which resulted in
82 /// the failure to process `obligation`. This is the obligation
83 /// that was initially passed to `register_predicate_obligation`
84 pub root_obligation: PredicateObligation<'tcx>,
85}
86
87impl<'tcx> FulfillmentError<'tcx> {
88 pub fn new(
89 obligation: PredicateObligation<'tcx>,
90 code: FulfillmentErrorCode<'tcx>,
91 root_obligation: PredicateObligation<'tcx>,
92 ) -> FulfillmentError<'tcx> {
93 FulfillmentError { obligation, code, root_obligation }
94 }
95
96 pub fn is_true_error(&self) -> bool {
97 match self.code {
98 FulfillmentErrorCode::Select(_)
99 | FulfillmentErrorCode::Project(_)
100 | FulfillmentErrorCode::Subtype(_, _)
101 | FulfillmentErrorCode::ConstEquate(_, _) => true,
102 FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
103 false
104 }
105 }
106 }
107}
108
109#[derive(Clone)]
110pub enum FulfillmentErrorCode<'tcx> {
111 /// Inherently impossible to fulfill; this trait is implemented if and only
112 /// if it is already implemented.
113 Cycle(PredicateObligations<'tcx>),
114 Select(SelectionError<'tcx>),
115 Project(MismatchedProjectionTypes<'tcx>),
116 Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
117 ConstEquate(ExpectedFound<ty::Const<'tcx>>, TypeError<'tcx>),
118 Ambiguity {
119 /// Overflow is only `Some(suggest_recursion_limit)` when using the next generation
120 /// trait solver `-Znext-solver`. With the old solver overflow is eagerly handled by
121 /// emitting a fatal error instead.
122 overflow: Option<bool>,
123 },
124}
125
126impl<'tcx> Debug for FulfillmentErrorCode<'tcx> {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 match *self {
129 FulfillmentErrorCode::Select(ref e) => write!(f, "{e:?}"),
130 FulfillmentErrorCode::Project(ref e) => write!(f, "{e:?}"),
131 FulfillmentErrorCode::Subtype(ref a, ref b) => {
132 write!(f, "CodeSubtypeError({a:?}, {b:?})")
133 }
134 FulfillmentErrorCode::ConstEquate(ref a, ref b) => {
135 write!(f, "CodeConstEquateError({a:?}, {b:?})")
136 }
137 FulfillmentErrorCode::Ambiguity { overflow: None } => write!(f, "Ambiguity"),
138 FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
139 write!(f, "Overflow({suggest_increasing_limit})")
140 }
141 FulfillmentErrorCode::Cycle(ref cycle) => write!(f, "Cycle({cycle:?})"),
142 }
143 }
144}
145
146/// Whether to skip the leak check, as part of a future compatibility warning step.
147///
148/// The "default" for skip-leak-check corresponds to the current
149/// behavior (do not skip the leak check) -- not the behavior we are
150/// transitioning into.
151#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
152pub enum SkipLeakCheck {
153 Yes,
154 #[default]
155 No,
156}
157
158impl SkipLeakCheck {
159 fn is_yes(self) -> bool {
160 self == SkipLeakCheck::Yes
161 }
162}
163
164/// The mode that trait queries run in.
165#[derive(Copy, Clone, PartialEq, Eq, Debug)]
166pub enum TraitQueryMode {
167 /// Standard/un-canonicalized queries get accurate
168 /// spans etc. passed in and hence can do reasonable
169 /// error reporting on their own.
170 Standard,
171 /// Canonical queries get dummy spans and hence
172 /// must generally propagate errors to
173 /// pre-canonicalization callsites.
174 Canonical,
175}
176
177/// Creates predicate obligations from the generic bounds.
178#[instrument(level = "debug", skip(cause, param_env))]
179pub fn predicates_for_generics<'tcx>(
180 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
181 param_env: ty::ParamEnv<'tcx>,
182 generic_bounds: ty::InstantiatedPredicates<'tcx>,
183) -> impl Iterator<Item = PredicateObligation<'tcx>> {
184 generic_bounds.into_iter().enumerate().map(move |(idx, (clause, span))| Obligation {
185 cause: cause(idx, span),
186 recursion_depth: 0,
187 param_env,
188 predicate: clause.as_predicate(),
189 })
190}
191
192/// Determines whether the type `ty` is known to meet `bound` and
193/// returns true if so. Returns false if `ty` either does not meet
194/// `bound` or is not known to meet bound (note that this is
195/// conservative towards *no impl*, which is the opposite of the
196/// `evaluate` methods).
197pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
198 infcx: &InferCtxt<'tcx>,
199 param_env: ty::ParamEnv<'tcx>,
200 ty: Ty<'tcx>,
201 def_id: DefId,
202) -> bool {
203 let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
204 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
205}
206
207/// FIXME(@lcnr): this function doesn't seem right and shouldn't exist?
208///
209/// Ping me on zulip if you want to use this method and need help with finding
210/// an appropriate replacement.
211#[instrument(level = "debug", skip(infcx, param_env, pred), ret)]
212fn pred_known_to_hold_modulo_regions<'tcx>(
213 infcx: &InferCtxt<'tcx>,
214 param_env: ty::ParamEnv<'tcx>,
215 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
216) -> bool {
217 let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
218
219 let result = infcx.evaluate_obligation_no_overflow(&obligation);
220 debug!(?result);
221
222 if result.must_apply_modulo_regions() {
223 true
224 } else if result.may_apply() && !infcx.next_trait_solver() {
225 // Sometimes obligations are ambiguous because the recursive evaluator
226 // is not smart enough, so we fall back to fulfillment when we're not certain
227 // that an obligation holds or not. Even still, we must make sure that
228 // the we do no inference in the process of checking this obligation.
229 let goal = infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
230 infcx.probe(|_| {
231 let ocx = ObligationCtxt::new(infcx);
232 ocx.register_obligation(obligation);
233
234 let errors = ocx.select_all_or_error();
235 match errors.as_slice() {
236 // Only known to hold if we did no inference.
237 [] => infcx.resolve_vars_if_possible(goal) == goal,
238
239 errors => {
240 debug!(?errors);
241 false
242 }
243 }
244 })
245 } else {
246 false
247 }
248}
249
250#[instrument(level = "debug", skip(tcx, elaborated_env))]
251fn do_normalize_predicates<'tcx>(
252 tcx: TyCtxt<'tcx>,
253 cause: ObligationCause<'tcx>,
254 elaborated_env: ty::ParamEnv<'tcx>,
255 predicates: Vec<ty::Clause<'tcx>>,
256) -> Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> {
257 let span = cause.span;
258
259 // FIXME. We should really... do something with these region
260 // obligations. But this call just continues the older
261 // behavior (i.e., doesn't cause any new bugs), and it would
262 // take some further refactoring to actually solve them. In
263 // particular, we would have to handle implied bounds
264 // properly, and that code is currently largely confined to
265 // regionck (though I made some efforts to extract it
266 // out). -nmatsakis
267 //
268 // @arielby: In any case, these obligations are checked
269 // by wfcheck anyway, so I'm not sure we have to check
270 // them here too, and we will remove this function when
271 // we move over to lazy normalization *anyway*.
272 let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
273 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
274 let predicates = ocx.normalize(&cause, elaborated_env, predicates);
275
276 let errors = ocx.select_all_or_error();
277 if !errors.is_empty() {
278 let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
279 return Err(reported);
280 }
281
282 debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
283
284 // We can use the `elaborated_env` here; the region code only
285 // cares about declarations like `'a: 'b`.
286 // FIXME: It's very weird that we ignore region obligations but apparently
287 // still need to use `resolve_regions` as we need the resolved regions in
288 // the normalized predicates.
289 let errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
290 if !errors.is_empty() {
291 tcx.dcx().span_delayed_bug(
292 span,
293 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
294 );
295 }
296
297 match infcx.fully_resolve(predicates) {
298 Ok(predicates) => Ok(predicates),
299 Err(fixup_err) => {
300 // If we encounter a fixup error, it means that some type
301 // variable wound up unconstrained. I actually don't know
302 // if this can happen, and I certainly don't expect it to
303 // happen often, but if it did happen it probably
304 // represents a legitimate failure due to some kind of
305 // unconstrained variable.
306 //
307 // @lcnr: Let's still ICE here for now. I want a test case
308 // for that.
309 span_bug!(
310 span,
311 "inference variables in normalized parameter environment: {}",
312 fixup_err
313 );
314 }
315 }
316}
317
318// FIXME: this is gonna need to be removed ...
319/// Normalizes the parameter environment, reporting errors if they occur.
320#[instrument(level = "debug", skip(tcx))]
321pub fn normalize_param_env_or_error<'tcx>(
322 tcx: TyCtxt<'tcx>,
323 unnormalized_env: ty::ParamEnv<'tcx>,
324 cause: ObligationCause<'tcx>,
325) -> ty::ParamEnv<'tcx> {
326 // I'm not wild about reporting errors here; I'd prefer to
327 // have the errors get reported at a defined place (e.g.,
328 // during typeck). Instead I have all parameter
329 // environments, in effect, going through this function
330 // and hence potentially reporting errors. This ensures of
331 // course that we never forget to normalize (the
332 // alternative seemed like it would involve a lot of
333 // manual invocations of this fn -- and then we'd have to
334 // deal with the errors at each of those sites).
335 //
336 // In any case, in practice, typeck constructs all the
337 // parameter environments once for every fn as it goes,
338 // and errors will get reported then; so outside of type inference we
339 // can be sure that no errors should occur.
340 let mut predicates: Vec<_> = util::elaborate(
341 tcx,
342 unnormalized_env.caller_bounds().into_iter().map(|predicate| {
343 if tcx.features().generic_const_exprs() || tcx.next_trait_solver_globally() {
344 return predicate;
345 }
346
347 struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
348
349 impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
350 fn cx(&self) -> TyCtxt<'tcx> {
351 self.0
352 }
353
354 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
355 // FIXME(return_type_notation): track binders in this normalizer, as
356 // `ty::Const::normalize` can only work with properly preserved binders.
357
358 if c.has_escaping_bound_vars() {
359 return ty::Const::new_misc_error(self.0);
360 }
361
362 // While it is pretty sus to be evaluating things with an empty param env, it
363 // should actually be okay since without `feature(generic_const_exprs)` the only
364 // const arguments that have a non-empty param env are array repeat counts. These
365 // do not appear in the type system though.
366 if let ty::ConstKind::Unevaluated(uv) = c.kind()
367 && self.0.def_kind(uv.def) == DefKind::AnonConst
368 {
369 let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
370 let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
371 // We should never wind up with any `infcx` local state when normalizing anon consts
372 // under min const generics.
373 assert!(!c.has_infer() && !c.has_placeholders());
374 return c;
375 }
376
377 c
378 }
379 }
380
381 // This whole normalization step is a hack to work around the fact that
382 // `normalize_param_env_or_error` is fundamentally broken from using an
383 // unnormalized param env with a trait solver that expects the param env
384 // to be normalized.
385 //
386 // When normalizing the param env we can end up evaluating obligations
387 // that have been normalized but can only be proven via a where clause
388 // which is still in its unnormalized form. example:
389 //
390 // Attempting to prove `T: Trait<<u8 as Identity>::Assoc>` in a param env
391 // with a `T: Trait<<u8 as Identity>::Assoc>` where clause will fail because
392 // we first normalize obligations before proving them so we end up proving
393 // `T: Trait<u8>`. Since lazy normalization is not implemented equating `u8`
394 // with `<u8 as Identity>::Assoc` fails outright so we incorrectly believe that
395 // we cannot prove `T: Trait<u8>`.
396 //
397 // The same thing is true for const generics- attempting to prove
398 // `T: Trait<ConstKind::Unevaluated(...)>` with the same thing as a where clauses
399 // will fail. After normalization we may be attempting to prove `T: Trait<4>` with
400 // the unnormalized where clause `T: Trait<ConstKind::Unevaluated(...)>`. In order
401 // for the obligation to hold `4` must be equal to `ConstKind::Unevaluated(...)`
402 // but as we do not have lazy norm implemented, equating the two consts fails outright.
403 //
404 // Ideally we would not normalize consts here at all but it is required for backwards
405 // compatibility. Eventually when lazy norm is implemented this can just be removed.
406 // We do not normalize types here as there is no backwards compatibility requirement
407 // for us to do so.
408 predicate.fold_with(&mut ConstNormalizer(tcx))
409 }),
410 )
411 .collect();
412
413 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
414
415 let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
416 if !elaborated_env.has_aliases() {
417 return elaborated_env;
418 }
419
420 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
421 // normalization expects its param-env to be already normalized, which means we have
422 // a circularity.
423 //
424 // The way we handle this is by normalizing the param-env inside an unnormalized version
425 // of the param-env, which means that if the param-env contains unnormalized projections,
426 // we'll have some normalization failures. This is unfortunate.
427 //
428 // Lazy normalization would basically handle this by treating just the
429 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
430 //
431 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
432 // types, so to make the situation less bad, we normalize all the predicates *but*
433 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
434 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
435 //
436 // This works fairly well because trait matching does not actually care about param-env
437 // TypeOutlives predicates - these are normally used by regionck.
438 let outlives_predicates: Vec<_> = predicates
439 .extract_if(.., |predicate| {
440 matches!(predicate.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
441 })
442 .collect();
443
444 debug!(
445 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
446 predicates, outlives_predicates
447 );
448 let Ok(non_outlives_predicates) =
449 do_normalize_predicates(tcx, cause.clone(), elaborated_env, predicates)
450 else {
451 // An unnormalized env is better than nothing.
452 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
453 return elaborated_env;
454 };
455
456 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
457
458 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
459 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
460 // predicates here anyway. Keeping them here anyway because it seems safer.
461 let outlives_env = non_outlives_predicates.iter().chain(&outlives_predicates).cloned();
462 let outlives_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
463 let Ok(outlives_predicates) =
464 do_normalize_predicates(tcx, cause, outlives_env, outlives_predicates)
465 else {
466 // An unnormalized env is better than nothing.
467 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
468 return elaborated_env;
469 };
470 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
471
472 let mut predicates = non_outlives_predicates;
473 predicates.extend(outlives_predicates);
474 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
475 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
476}
477
478#[derive(Debug)]
479pub enum EvaluateConstErr {
480 /// The constant being evaluated was either a generic parameter or inference variable, *or*,
481 /// some unevaluated constant with either generic parameters or inference variables in its
482 /// generic arguments.
483 HasGenericsOrInfers,
484 /// The type this constant evalauted to is not valid for use in const generics. This should
485 /// always result in an error when checking the constant is correctly typed for the parameter
486 /// it is an argument to, so a bug is delayed when encountering this.
487 InvalidConstParamTy(ErrorGuaranteed),
488 /// CTFE failed to evaluate the constant in some unrecoverable way (e.g. encountered a `panic!`).
489 /// This is also used when the constant was already tainted by error.
490 EvaluationFailure(ErrorGuaranteed),
491}
492
493// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
494// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
495// normalization scheme
496/// Evaluates a type system constant returning a `ConstKind::Error` in cases where CTFE failed and
497/// returning the passed in constant if it was not fully concrete (i.e. depended on generic parameters
498/// or inference variables)
499///
500/// You should not call this function unless you are implementing normalization itself. Prefer to use
501/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
502pub fn evaluate_const<'tcx>(
503 infcx: &InferCtxt<'tcx>,
504 ct: ty::Const<'tcx>,
505 param_env: ty::ParamEnv<'tcx>,
506) -> ty::Const<'tcx> {
507 match try_evaluate_const(infcx, ct, param_env) {
508 Ok(ct) => ct,
509 Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
510 ty::Const::new_error(infcx.tcx, e)
511 }
512 Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
513 }
514}
515
516// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
517// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
518// normalization scheme
519/// Evaluates a type system constant making sure to not allow constants that depend on generic parameters
520/// or inference variables to succeed in evaluating.
521///
522/// You should not call this function unless you are implementing normalization itself. Prefer to use
523/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
524#[instrument(level = "debug", skip(infcx), ret)]
525pub fn try_evaluate_const<'tcx>(
526 infcx: &InferCtxt<'tcx>,
527 ct: ty::Const<'tcx>,
528 param_env: ty::ParamEnv<'tcx>,
529) -> Result<ty::Const<'tcx>, EvaluateConstErr> {
530 let tcx = infcx.tcx;
531 let ct = infcx.resolve_vars_if_possible(ct);
532 debug!(?ct);
533
534 match ct.kind() {
535 ty::ConstKind::Value(..) => Ok(ct),
536 ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
537 ty::ConstKind::Param(_)
538 | ty::ConstKind::Infer(_)
539 | ty::ConstKind::Bound(_, _)
540 | ty::ConstKind::Placeholder(_)
541 | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
542 ty::ConstKind::Unevaluated(uv) => {
543 let opt_anon_const_kind =
544 (tcx.def_kind(uv.def) == DefKind::AnonConst).then(|| tcx.anon_const_kind(uv.def));
545
546 // Postpone evaluation of constants that depend on generic parameters or
547 // inference variables.
548 //
549 // We use `TypingMode::PostAnalysis` here which is not *technically* correct
550 // to be revealing opaque types here as borrowcheck has not run yet. However,
551 // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during
552 // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
553 // As a result we always use a revealed env when resolving the instance to evaluate.
554 //
555 // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
556 // instead of having this logic here
557 let (args, typing_env) = match opt_anon_const_kind {
558 // We handle `generic_const_exprs` separately as reasonable ways of handling constants in the type system
559 // completely fall apart under `generic_const_exprs` and makes this whole function Really hard to reason
560 // about if you have to consider gce whatsoever.
561 Some(ty::AnonConstKind::GCE) => {
562 if uv.has_non_region_infer() || uv.has_non_region_param() {
563 // `feature(generic_const_exprs)` causes anon consts to inherit all parent generics. This can cause
564 // inference variables and generic parameters to show up in `ty::Const` even though the anon const
565 // does not actually make use of them. We handle this case specially and attempt to evaluate anyway.
566 match tcx.thir_abstract_const(uv.def) {
567 Ok(Some(ct)) => {
568 let ct = tcx.expand_abstract_consts(ct.instantiate(tcx, uv.args));
569 if let Err(e) = ct.error_reported() {
570 return Err(EvaluateConstErr::EvaluationFailure(e));
571 } else if ct.has_non_region_infer() || ct.has_non_region_param() {
572 // If the anon const *does* actually use generic parameters or inference variables from
573 // the generic arguments provided for it, then we should *not* attempt to evaluate it.
574 return Err(EvaluateConstErr::HasGenericsOrInfers);
575 } else {
576 let args =
577 replace_param_and_infer_args_with_placeholder(tcx, uv.args);
578 let typing_env = infcx
579 .typing_env(tcx.erase_regions(param_env))
580 .with_post_analysis_normalized(tcx);
581 (args, typing_env)
582 }
583 }
584 Err(_) | Ok(None) => {
585 let args = GenericArgs::identity_for_item(tcx, uv.def);
586 let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
587 (args, typing_env)
588 }
589 }
590 } else {
591 let typing_env = infcx
592 .typing_env(tcx.erase_regions(param_env))
593 .with_post_analysis_normalized(tcx);
594 (uv.args, typing_env)
595 }
596 }
597 Some(ty::AnonConstKind::RepeatExprCount) => {
598 if uv.has_non_region_infer() {
599 // Diagnostics will sometimes replace the identity args of anon consts in
600 // array repeat expr counts with inference variables so we have to handle this
601 // even though it is not something we should ever actually encounter.
602 //
603 // Array repeat expr counts are allowed to syntactically use generic parameters
604 // but must not actually depend on them in order to evalaute successfully. This means
605 // that it is actually fine to evalaute them in their own environment rather than with
606 // the actually provided generic arguments.
607 tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
608 }
609
610 // The generic args of repeat expr counts under `min_const_generics` are not supposed to
611 // affect evaluation of the constant as this would make it a "truly" generic const arg.
612 // To prevent this we discard all the generic arguments and evalaute with identity args
613 // and in its own environment instead of the current environment we are normalizing in.
614 let args = GenericArgs::identity_for_item(tcx, uv.def);
615 let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
616
617 (args, typing_env)
618 }
619 _ => {
620 // We are only dealing with "truly" generic/uninferred constants here:
621 // - GCEConsts have been handled separately
622 // - Repeat expr count back compat consts have also been handled separately
623 // So we are free to simply defer evaluation here.
624 //
625 // FIXME: This assumes that `args` are normalized which is not necessarily true
626 //
627 // Const patterns are converted to type system constants before being
628 // evaluated. However, we don't care about them here as pattern evaluation
629 // logic does not go through type system normalization. If it did this would
630 // be a backwards compatibility problem as we do not enforce "syntactic" non-
631 // usage of generic parameters like we do here.
632 if uv.args.has_non_region_param() || uv.args.has_non_region_infer() {
633 return Err(EvaluateConstErr::HasGenericsOrInfers);
634 }
635
636 let typing_env = infcx
637 .typing_env(tcx.erase_regions(param_env))
638 .with_post_analysis_normalized(tcx);
639 (uv.args, typing_env)
640 }
641 };
642
643 let uv = ty::UnevaluatedConst::new(uv.def, args);
644 let erased_uv = tcx.erase_regions(uv);
645
646 use rustc_middle::mir::interpret::ErrorHandled;
647 match tcx.const_eval_resolve_for_typeck(typing_env, erased_uv, DUMMY_SP) {
648 Ok(Ok(val)) => Ok(ty::Const::new_value(
649 tcx,
650 val,
651 tcx.type_of(uv.def).instantiate(tcx, uv.args),
652 )),
653 Ok(Err(_)) => {
654 let e = tcx.dcx().delayed_bug(
655 "Type system constant with non valtree'able type evaluated but no error emitted",
656 );
657 Err(EvaluateConstErr::InvalidConstParamTy(e))
658 }
659 Err(ErrorHandled::Reported(info, _)) => {
660 Err(EvaluateConstErr::EvaluationFailure(info.into()))
661 }
662 Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
663 }
664 }
665 }
666}
667
668/// Replaces args that reference param or infer variables with suitable
669/// placeholders. This function is meant to remove these param and infer
670/// args when they're not actually needed to evaluate a constant.
671fn replace_param_and_infer_args_with_placeholder<'tcx>(
672 tcx: TyCtxt<'tcx>,
673 args: GenericArgsRef<'tcx>,
674) -> GenericArgsRef<'tcx> {
675 struct ReplaceParamAndInferWithPlaceholder<'tcx> {
676 tcx: TyCtxt<'tcx>,
677 idx: ty::BoundVar,
678 }
679
680 impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
681 fn cx(&self) -> TyCtxt<'tcx> {
682 self.tcx
683 }
684
685 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
686 if let ty::Infer(_) = t.kind() {
687 let idx = self.idx;
688 self.idx += 1;
689 Ty::new_placeholder(
690 self.tcx,
691 ty::PlaceholderType {
692 universe: ty::UniverseIndex::ROOT,
693 bound: ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
694 },
695 )
696 } else {
697 t.super_fold_with(self)
698 }
699 }
700
701 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
702 if let ty::ConstKind::Infer(_) = c.kind() {
703 let idx = self.idx;
704 self.idx += 1;
705 ty::Const::new_placeholder(
706 self.tcx,
707 ty::PlaceholderConst { universe: ty::UniverseIndex::ROOT, bound: idx },
708 )
709 } else {
710 c.super_fold_with(self)
711 }
712 }
713 }
714
715 args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: ty::BoundVar::ZERO })
716}
717
718/// Normalizes the predicates and checks whether they hold in an empty environment. If this
719/// returns true, then either normalize encountered an error or one of the predicates did not
720/// hold. Used when creating vtables to check for unsatisfiable methods. This should not be
721/// used during analysis.
722pub fn impossible_predicates<'tcx>(tcx: TyCtxt<'tcx>, predicates: Vec<ty::Clause<'tcx>>) -> bool {
723 debug!("impossible_predicates(predicates={:?})", predicates);
724 let (infcx, param_env) = tcx
725 .infer_ctxt()
726 .with_next_trait_solver(true)
727 .build_with_typing_env(ty::TypingEnv::fully_monomorphized());
728
729 let ocx = ObligationCtxt::new(&infcx);
730 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
731 for predicate in predicates {
732 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
733 ocx.register_obligation(obligation);
734 }
735
736 // Use `select_where_possible` to only return impossible for true errors,
737 // and not ambiguities or overflows. Since the new trait solver forces
738 // some currently undetected overlap between `dyn Trait: Trait` built-in
739 // vs user-written impls to AMBIGUOUS, this may return ambiguity even
740 // with no infer vars. There may also be ways to encounter ambiguity due
741 // to post-mono overflow.
742 let true_errors = ocx.select_where_possible();
743 if !true_errors.is_empty() {
744 return true;
745 }
746
747 false
748}
749
750fn instantiate_and_check_impossible_predicates<'tcx>(
751 tcx: TyCtxt<'tcx>,
752 key: (DefId, GenericArgsRef<'tcx>),
753) -> bool {
754 debug!("instantiate_and_check_impossible_predicates(key={:?})", key);
755
756 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
757
758 // Specifically check trait fulfillment to avoid an error when trying to resolve
759 // associated items.
760 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
761 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
762 predicates.push(trait_ref.upcast(tcx));
763 }
764
765 predicates.retain(|predicate| !predicate.has_param());
766 let result = impossible_predicates(tcx, predicates);
767
768 debug!("instantiate_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
769 result
770}
771
772/// Checks whether a trait's associated item is impossible to reference on a given impl.
773///
774/// This only considers predicates that reference the impl's generics, and not
775/// those that reference the method's generics.
776fn is_impossible_associated_item(
777 tcx: TyCtxt<'_>,
778 (impl_def_id, trait_item_def_id): (DefId, DefId),
779) -> bool {
780 struct ReferencesOnlyParentGenerics<'tcx> {
781 tcx: TyCtxt<'tcx>,
782 generics: &'tcx ty::Generics,
783 trait_item_def_id: DefId,
784 }
785 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
786 type Result = ControlFlow<()>;
787 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
788 // If this is a parameter from the trait item's own generics, then bail
789 if let ty::Param(param) = *t.kind()
790 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
791 && self.tcx.parent(param_def_id) == self.trait_item_def_id
792 {
793 return ControlFlow::Break(());
794 }
795 t.super_visit_with(self)
796 }
797 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
798 if let ty::ReEarlyParam(param) = r.kind()
799 && let param_def_id = self.generics.region_param(param, self.tcx).def_id
800 && self.tcx.parent(param_def_id) == self.trait_item_def_id
801 {
802 return ControlFlow::Break(());
803 }
804 ControlFlow::Continue(())
805 }
806 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
807 if let ty::ConstKind::Param(param) = ct.kind()
808 && let param_def_id = self.generics.const_param(param, self.tcx).def_id
809 && self.tcx.parent(param_def_id) == self.trait_item_def_id
810 {
811 return ControlFlow::Break(());
812 }
813 ct.super_visit_with(self)
814 }
815 }
816
817 let generics = tcx.generics_of(trait_item_def_id);
818 let predicates = tcx.predicates_of(trait_item_def_id);
819
820 // Be conservative in cases where we have `W<T: ?Sized>` and a method like `Self: Sized`,
821 // since that method *may* have some substitutions where the predicates hold.
822 //
823 // This replicates the logic we use in coherence.
824 let infcx = tcx
825 .infer_ctxt()
826 .ignoring_regions()
827 .with_next_trait_solver(true)
828 .build(TypingMode::Coherence);
829 let param_env = ty::ParamEnv::empty();
830 let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
831
832 let impl_trait_ref = tcx
833 .impl_trait_ref(impl_def_id)
834 .expect("expected impl to correspond to trait")
835 .instantiate(tcx, fresh_args);
836
837 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
838 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
839 pred.visit_with(&mut visitor).is_continue().then(|| {
840 Obligation::new(
841 tcx,
842 ObligationCause::dummy_with_span(*span),
843 param_env,
844 ty::EarlyBinder::bind(*pred).instantiate(tcx, impl_trait_ref.args),
845 )
846 })
847 });
848
849 let ocx = ObligationCtxt::new(&infcx);
850 ocx.register_obligations(predicates_for_trait);
851 !ocx.select_where_possible().is_empty()
852}
853
854pub fn provide(providers: &mut Providers) {
855 dyn_compatibility::provide(providers);
856 vtable::provide(providers);
857 *providers = Providers {
858 specialization_graph_of: specialize::specialization_graph_provider,
859 specializes: specialize::specializes,
860 specialization_enabled_in: specialize::specialization_enabled_in,
861 instantiate_and_check_impossible_predicates,
862 is_impossible_associated_item,
863 ..*providers
864 };
865}