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