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
45pub 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;
19pub mod specialize;
20mod structural_normalize;
21#[allow(hidden_glob_reexports)]
22mod util;
23pub mod vtable;
24pub mod wf;
2526use std::fmt::Debug;
27use std::ops::ControlFlow;
2829use 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::{
37self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
38TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode, Upcast,
39};
40use rustc_span::Span;
41use rustc_span::def_id::DefId;
42use tracing::{debug, instrument};
4344pub use self::coherence::{
45InCrate, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams,
46add_placeholder_note, orphan_check_trait_ref, overlapping_inherent_impls,
47overlapping_trait_impls,
48};
49pub use self::dyn_compatibility::{
50DynCompatibilityViolation, dyn_compatibility_violations_for_assoc_item,
51hir_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::{
58EvaluationCache, EvaluationResult, IntercrateAmbiguityCause, OverflowError, SelectionCache,
59SelectionContext,
60};
61pub use self::specialize::specialization_graph::{
62FutureCompatOverlapError, FutureCompatOverlapErrorKind,
63};
64pub use self::specialize::{
65OverlapError, specialization_graph, translate_args, translate_args_with_cause,
66};
67pub use self::structural_normalize::StructurallyNormalizeExt;
68pub use self::util::{
69BoundVarReplacer, PlaceholderReplacer, elaborate, expand_trait_aliases, impl_item_is_final,
70sizedness_fast_path, supertrait_def_ids, supertraits, transitive_bounds_that_define_assoc_item,
71upcast_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::InferCtxtExtas _;
7879#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FulfillmentError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"FulfillmentError", "obligation", &self.obligation, "code",
&self.code, "root_obligation", &&self.root_obligation)
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for FulfillmentError<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
FulfillmentError {
obligation: ref __binding_0,
code: ref __binding_1,
root_obligation: ref __binding_2 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
80pub struct FulfillmentError<'tcx> {
81pub obligation: PredicateObligation<'tcx>,
82pub 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`
86pub root_obligation: PredicateObligation<'tcx>,
87}
8889impl<'tcx> FulfillmentError<'tcx> {
90pub fn new(
91 obligation: PredicateObligation<'tcx>,
92 code: FulfillmentErrorCode<'tcx>,
93 root_obligation: PredicateObligation<'tcx>,
94 ) -> FulfillmentError<'tcx> {
95FulfillmentError { obligation, code, root_obligation }
96 }
9798pub fn is_true_error(&self) -> bool {
99match self.code {
100 FulfillmentErrorCode::Select(_)
101 | FulfillmentErrorCode::Project(_)
102 | FulfillmentErrorCode::Subtype(_, _)
103 | FulfillmentErrorCode::ConstEquate(_, _) => true,
104 FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
105false
106}
107 }
108 }
109}
110111#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for FulfillmentErrorCode<'tcx> {
#[inline]
fn clone(&self) -> FulfillmentErrorCode<'tcx> {
match self {
FulfillmentErrorCode::Cycle(__self_0) =>
FulfillmentErrorCode::Cycle(::core::clone::Clone::clone(__self_0)),
FulfillmentErrorCode::Select(__self_0) =>
FulfillmentErrorCode::Select(::core::clone::Clone::clone(__self_0)),
FulfillmentErrorCode::Project(__self_0) =>
FulfillmentErrorCode::Project(::core::clone::Clone::clone(__self_0)),
FulfillmentErrorCode::Subtype(__self_0, __self_1) =>
FulfillmentErrorCode::Subtype(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
FulfillmentErrorCode::ConstEquate(__self_0, __self_1) =>
FulfillmentErrorCode::ConstEquate(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
FulfillmentErrorCode::Ambiguity { overflow: __self_0 } =>
FulfillmentErrorCode::Ambiguity {
overflow: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for FulfillmentErrorCode<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
FulfillmentErrorCode::Cycle(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
FulfillmentErrorCode::Select(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
FulfillmentErrorCode::Project(ref __binding_0) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
FulfillmentErrorCode::Subtype(ref __binding_0,
ref __binding_1) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
FulfillmentErrorCode::ConstEquate(ref __binding_0,
ref __binding_1) => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
FulfillmentErrorCode::Ambiguity { overflow: ref __binding_0
} => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
112pub enum FulfillmentErrorCode<'tcx> {
113/// Inherently impossible to fulfill; this trait is implemented if and only
114 /// if it is already implemented.
115Cycle(PredicateObligations<'tcx>),
116 Select(SelectionError<'tcx>),
117 Project(MismatchedProjectionTypes<'tcx>),
118 Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
119ConstEquate(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.
124overflow: Option<bool>,
125 },
126}
127128impl<'tcx> Debugfor FulfillmentErrorCode<'tcx> {
129fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130match *self {
131 FulfillmentErrorCode::Select(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
132 FulfillmentErrorCode::Project(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
133 FulfillmentErrorCode::Subtype(ref a, ref b) => {
134f.write_fmt(format_args!("CodeSubtypeError({0:?}, {1:?})", a, b))write!(f, "CodeSubtypeError({a:?}, {b:?})")135 }
136 FulfillmentErrorCode::ConstEquate(ref a, ref b) => {
137f.write_fmt(format_args!("CodeConstEquateError({0:?}, {1:?})", a, b))write!(f, "CodeConstEquateError({a:?}, {b:?})")138 }
139 FulfillmentErrorCode::Ambiguity { overflow: None } => f.write_fmt(format_args!("Ambiguity"))write!(f, "Ambiguity"),
140 FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
141f.write_fmt(format_args!("Overflow({0})", suggest_increasing_limit))write!(f, "Overflow({suggest_increasing_limit})")142 }
143 FulfillmentErrorCode::Cycle(ref cycle) => f.write_fmt(format_args!("Cycle({0:?})", cycle))write!(f, "Cycle({cycle:?})"),
144 }
145 }
146}
147148/// 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(#[automatically_derived]
impl ::core::marker::Copy for SkipLeakCheck { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SkipLeakCheck {
#[inline]
fn clone(&self) -> SkipLeakCheck { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for SkipLeakCheck {
#[inline]
fn eq(&self, other: &SkipLeakCheck) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SkipLeakCheck {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SkipLeakCheck {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
SkipLeakCheck::Yes => "Yes",
SkipLeakCheck::No => "No",
})
}
}Debug, #[automatically_derived]
impl ::core::default::Default for SkipLeakCheck {
#[inline]
fn default() -> SkipLeakCheck { Self::No }
}Default)]
154pub enum SkipLeakCheck {
155 Yes,
156#[default]
157No,
158}
159160impl SkipLeakCheck {
161fn is_yes(self) -> bool {
162self == SkipLeakCheck::Yes163 }
164}
165166/// The mode that trait queries run in.
167#[derive(#[automatically_derived]
impl ::core::marker::Copy for TraitQueryMode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TraitQueryMode {
#[inline]
fn clone(&self) -> TraitQueryMode { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for TraitQueryMode {
#[inline]
fn eq(&self, other: &TraitQueryMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TraitQueryMode {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for TraitQueryMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
TraitQueryMode::Standard => "Standard",
TraitQueryMode::Canonical => "Canonical",
})
}
}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.
172Standard,
173/// Canonical queries get dummy spans and hence
174 /// must generally propagate errors to
175 /// pre-canonicalization callsites.
176Canonical,
177}
178179/// Creates predicate obligations from the generic bounds.
180#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("predicates_for_generics",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(180u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["generic_bounds"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_bounds)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: _ = loop {};
return __tracing_attr_fake_return;
}
{
generic_bounds.into_iter().enumerate().map(move
|(idx, (clause, span))|
Obligation {
cause: cause(idx, span),
recursion_depth: 0,
param_env,
predicate: clause.as_predicate(),
})
}
}
}#[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}
193194/// 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 {
205let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
206pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
207}
208209/// 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.
213x;#[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 {
219let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
220221let result = infcx.evaluate_obligation_no_overflow(&obligation);
222debug!(?result);
223224if result.must_apply_modulo_regions() {
225true
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.
231let goal = infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
232 infcx.probe(|_| {
233let ocx = ObligationCtxt::new(infcx);
234 ocx.register_obligation(obligation);
235236let errors = ocx.evaluate_obligations_error_on_ambiguity();
237match errors.as_slice() {
238// Only known to hold if we did no inference.
239[] => infcx.resolve_vars_if_possible(goal) == goal,
240241 errors => {
242debug!(?errors);
243false
244}
245 }
246 })
247 } else {
248false
249}
250}
251252#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("do_normalize_predicates",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(252u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["cause",
"predicates"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicates)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let span = cause.span;
let infcx =
tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
let predicates =
ocx.normalize(&cause, elaborated_env, predicates);
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.is_empty() {
let reported =
infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(reported);
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:284",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(284u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("do_normalize_predicates: normalized predicates = {0:?}",
predicates) as &dyn Value))])
});
} else { ; }
};
let errors =
infcx.resolve_regions(cause.body_id, elaborated_env, []);
if !errors.is_empty() {
tcx.dcx().span_delayed_bug(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed region resolution while normalizing {0:?}: {1:?}",
elaborated_env, errors))
}));
}
match infcx.fully_resolve(predicates) {
Ok(predicates) => Ok(predicates),
Err(fixup_err) => {
Err(tcx.dcx().span_delayed_bug(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("inference variables in normalized parameter environment: {0}",
fixup_err))
})))
}
}
}
}
}#[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> {
259let span = cause.span;
260261// 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*.
274let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
275let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
276let predicates = ocx.normalize(&cause, elaborated_env, predicates);
277278let errors = ocx.evaluate_obligations_error_on_ambiguity();
279if !errors.is_empty() {
280let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
281return Err(reported);
282 }
283284debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
285286// 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.
291let errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
292if !errors.is_empty() {
293 tcx.dcx().span_delayed_bug(
294 span,
295format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
296 );
297 }
298299match infcx.fully_resolve(predicates) {
300Ok(predicates) => Ok(predicates),
301Err(fixup_err) => {
302// If we encounter a fixup error, it means that some type
303 // variable wound up unconstrained. That can happen for
304 // ill-formed impls, so we delay a bug here instead of
305 // immediately ICEing and let type checking report the
306 // actual user-facing errors.
307Err(tcx.dcx().span_delayed_bug(
308 span,
309format!("inference variables in normalized parameter environment: {fixup_err}"),
310 ))
311 }
312 }
313}
314315// FIXME: this is gonna need to be removed ...
316/// Normalizes the parameter environment, reporting errors if they occur.
317#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("normalize_param_env_or_error",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(317u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["unnormalized_env",
"cause"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unnormalized_env)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::ParamEnv<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let mut predicates: Vec<_> =
util::elaborate(tcx,
unnormalized_env.caller_bounds().into_iter().map(|predicate|
{
if tcx.features().generic_const_exprs() ||
tcx.next_trait_solver_globally() {
return predicate;
}
struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for
ConstNormalizer<'tcx> {
fn cx(&self) -> TyCtxt<'tcx> { self.0 }
fn fold_const(&mut self, c: ty::Const<'tcx>)
-> ty::Const<'tcx> {
if c.has_escaping_bound_vars() {
return ty::Const::new_misc_error(self.0);
}
if let ty::ConstKind::Unevaluated(uv) = c.kind() &&
self.0.def_kind(uv.def) == DefKind::AnonConst {
let infcx =
self.0.infer_ctxt().build(TypingMode::non_body_analysis());
let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
if !(!c.has_infer() && !c.has_placeholders()) {
::core::panicking::panic("assertion failed: !c.has_infer() && !c.has_placeholders()")
};
return c;
}
c
}
}
predicate.fold_with(&mut ConstNormalizer(tcx))
})).collect();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:410",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(410u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: elaborated-predicates={0:?}",
predicates) as &dyn Value))])
});
} else { ; }
};
let elaborated_env =
ty::ParamEnv::new(tcx.mk_clauses(&predicates));
if !elaborated_env.has_aliases() { return elaborated_env; }
let outlives_predicates: Vec<_> =
predicates.extract_if(..,
|predicate|
{
#[allow(non_exhaustive_omitted_patterns)]
match predicate.kind().skip_binder() {
ty::ClauseKind::TypeOutlives(..) => true,
_ => false,
}
}).collect();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:441",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(441u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: predicates=(non-outlives={0:?}, outlives={1:?})",
predicates, outlives_predicates) as &dyn Value))])
});
} else { ; }
};
let Ok(non_outlives_predicates) =
do_normalize_predicates(tcx, cause.clone(), elaborated_env,
predicates) else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:449",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(449u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: errored resolving non-outlives predicates")
as &dyn Value))])
});
} else { ; }
};
return elaborated_env;
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:453",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(453u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: non-outlives predicates={0:?}",
non_outlives_predicates) as &dyn Value))])
});
} else { ; }
};
let outlives_env =
non_outlives_predicates.iter().chain(&outlives_predicates).cloned();
let outlives_env =
ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
let Ok(outlives_predicates) =
do_normalize_predicates(tcx, cause, outlives_env,
outlives_predicates) else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:464",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(464u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: errored resolving outlives predicates")
as &dyn Value))])
});
} else { ; }
};
return elaborated_env;
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:467",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(467u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: outlives predicates={0:?}",
outlives_predicates) as &dyn Value))])
});
} else { ; }
};
let mut predicates = non_outlives_predicates;
predicates.extend(outlives_predicates);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:471",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(471u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: final predicates={0:?}",
predicates) as &dyn Value))])
});
} else { ; }
};
ty::ParamEnv::new(tcx.mk_clauses(&predicates))
}
}
}#[instrument(level = "debug", skip(tcx))]318pub fn normalize_param_env_or_error<'tcx>(
319 tcx: TyCtxt<'tcx>,
320 unnormalized_env: ty::ParamEnv<'tcx>,
321 cause: ObligationCause<'tcx>,
322) -> ty::ParamEnv<'tcx> {
323// I'm not wild about reporting errors here; I'd prefer to
324 // have the errors get reported at a defined place (e.g.,
325 // during typeck). Instead I have all parameter
326 // environments, in effect, going through this function
327 // and hence potentially reporting errors. This ensures of
328 // course that we never forget to normalize (the
329 // alternative seemed like it would involve a lot of
330 // manual invocations of this fn -- and then we'd have to
331 // deal with the errors at each of those sites).
332 //
333 // In any case, in practice, typeck constructs all the
334 // parameter environments once for every fn as it goes,
335 // and errors will get reported then; so outside of type inference we
336 // can be sure that no errors should occur.
337let mut predicates: Vec<_> = util::elaborate(
338 tcx,
339 unnormalized_env.caller_bounds().into_iter().map(|predicate| {
340if tcx.features().generic_const_exprs() || tcx.next_trait_solver_globally() {
341return predicate;
342 }
343344struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
345346impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
347fn cx(&self) -> TyCtxt<'tcx> {
348self.0
349}
350351fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
352// FIXME(return_type_notation): track binders in this normalizer, as
353 // `ty::Const::normalize` can only work with properly preserved binders.
354355if c.has_escaping_bound_vars() {
356return ty::Const::new_misc_error(self.0);
357 }
358359// While it is pretty sus to be evaluating things with an empty param env, it
360 // should actually be okay since without `feature(generic_const_exprs)` the only
361 // const arguments that have a non-empty param env are array repeat counts. These
362 // do not appear in the type system though.
363if let ty::ConstKind::Unevaluated(uv) = c.kind()
364 && self.0.def_kind(uv.def) == DefKind::AnonConst
365 {
366let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
367let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
368// We should never wind up with any `infcx` local state when normalizing anon consts
369 // under min const generics.
370assert!(!c.has_infer() && !c.has_placeholders());
371return c;
372 }
373374 c
375 }
376 }
377378// This whole normalization step is a hack to work around the fact that
379 // `normalize_param_env_or_error` is fundamentally broken from using an
380 // unnormalized param env with a trait solver that expects the param env
381 // to be normalized.
382 //
383 // When normalizing the param env we can end up evaluating obligations
384 // that have been normalized but can only be proven via a where clause
385 // which is still in its unnormalized form. example:
386 //
387 // Attempting to prove `T: Trait<<u8 as Identity>::Assoc>` in a param env
388 // with a `T: Trait<<u8 as Identity>::Assoc>` where clause will fail because
389 // we first normalize obligations before proving them so we end up proving
390 // `T: Trait<u8>`. Since lazy normalization is not implemented equating `u8`
391 // with `<u8 as Identity>::Assoc` fails outright so we incorrectly believe that
392 // we cannot prove `T: Trait<u8>`.
393 //
394 // The same thing is true for const generics- attempting to prove
395 // `T: Trait<ConstKind::Unevaluated(...)>` with the same thing as a where clauses
396 // will fail. After normalization we may be attempting to prove `T: Trait<4>` with
397 // the unnormalized where clause `T: Trait<ConstKind::Unevaluated(...)>`. In order
398 // for the obligation to hold `4` must be equal to `ConstKind::Unevaluated(...)`
399 // but as we do not have lazy norm implemented, equating the two consts fails outright.
400 //
401 // Ideally we would not normalize consts here at all but it is required for backwards
402 // compatibility. Eventually when lazy norm is implemented this can just be removed.
403 // We do not normalize types here as there is no backwards compatibility requirement
404 // for us to do so.
405predicate.fold_with(&mut ConstNormalizer(tcx))
406 }),
407 )
408 .collect();
409410debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
411412let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
413if !elaborated_env.has_aliases() {
414return elaborated_env;
415 }
416417// HACK: we are trying to normalize the param-env inside *itself*. The problem is that
418 // normalization expects its param-env to be already normalized, which means we have
419 // a circularity.
420 //
421 // The way we handle this is by normalizing the param-env inside an unnormalized version
422 // of the param-env, which means that if the param-env contains unnormalized projections,
423 // we'll have some normalization failures. This is unfortunate.
424 //
425 // Lazy normalization would basically handle this by treating just the
426 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
427 //
428 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
429 // types, so to make the situation less bad, we normalize all the predicates *but*
430 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
431 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
432 //
433 // This works fairly well because trait matching does not actually care about param-env
434 // TypeOutlives predicates - these are normally used by regionck.
435let outlives_predicates: Vec<_> = predicates
436 .extract_if(.., |predicate| {
437matches!(predicate.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
438 })
439 .collect();
440441debug!(
442"normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
443 predicates, outlives_predicates
444 );
445let Ok(non_outlives_predicates) =
446 do_normalize_predicates(tcx, cause.clone(), elaborated_env, predicates)
447else {
448// An unnormalized env is better than nothing.
449debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
450return elaborated_env;
451 };
452453debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
454455// Not sure whether it is better to include the unnormalized TypeOutlives predicates
456 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
457 // predicates here anyway. Keeping them here anyway because it seems safer.
458let outlives_env = non_outlives_predicates.iter().chain(&outlives_predicates).cloned();
459let outlives_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
460let Ok(outlives_predicates) =
461 do_normalize_predicates(tcx, cause, outlives_env, outlives_predicates)
462else {
463// An unnormalized env is better than nothing.
464debug!("normalize_param_env_or_error: errored resolving outlives predicates");
465return elaborated_env;
466 };
467debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
468469let mut predicates = non_outlives_predicates;
470 predicates.extend(outlives_predicates);
471debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
472 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
473}
474475/// Deeply normalize the param env using the next solver ignoring
476/// region errors.
477///
478/// FIXME(-Zhigher-ranked-assumptions): this is a hack to work around
479/// the fact that we don't support placeholder assumptions right now
480/// and is necessary for `compare_method_predicate_entailment`, see the
481/// use of this function for more info. We should remove this once we
482/// have proper support for implied bounds on binders.
483#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("deeply_normalize_param_env_ignoring_regions",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(483u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["unnormalized_env",
"cause"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unnormalized_env)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ty::ParamEnv<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let predicates: Vec<_> =
util::elaborate(tcx,
unnormalized_env.caller_bounds().into_iter()).collect();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:492",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(492u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: elaborated-predicates={0:?}",
predicates) as &dyn Value))])
});
} else { ; }
};
let elaborated_env =
ty::ParamEnv::new(tcx.mk_clauses(&predicates));
if !elaborated_env.has_aliases() { return elaborated_env; }
let span = cause.span;
let infcx =
tcx.infer_ctxt().with_next_trait_solver(true).ignoring_regions().build(TypingMode::non_body_analysis());
let predicates =
match crate::solve::deeply_normalize::<_,
FulfillmentError<'tcx>>(infcx.at(&cause, elaborated_env),
predicates) {
Ok(predicates) => predicates,
Err(errors) => {
infcx.err_ctxt().report_fulfillment_errors(errors);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:513",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(513u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: errored resolving predicates")
as &dyn Value))])
});
} else { ; }
};
return elaborated_env;
}
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:518",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(518u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("do_normalize_predicates: normalized predicates = {0:?}",
predicates) as &dyn Value))])
});
} else { ; }
};
let _errors =
infcx.resolve_regions(cause.body_id, elaborated_env, []);
let predicates =
match infcx.fully_resolve(predicates) {
Ok(predicates) => predicates,
Err(fixup_err) => {
::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("inference variables in normalized parameter environment: {0}",
fixup_err))
}
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:534",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(534u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: final predicates={0:?}",
predicates) as &dyn Value))])
});
} else { ; }
};
ty::ParamEnv::new(tcx.mk_clauses(&predicates))
}
}
}#[instrument(level = "debug", skip(tcx))]484pub fn deeply_normalize_param_env_ignoring_regions<'tcx>(
485 tcx: TyCtxt<'tcx>,
486 unnormalized_env: ty::ParamEnv<'tcx>,
487 cause: ObligationCause<'tcx>,
488) -> ty::ParamEnv<'tcx> {
489let predicates: Vec<_> =
490 util::elaborate(tcx, unnormalized_env.caller_bounds().into_iter()).collect();
491492debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
493494let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
495if !elaborated_env.has_aliases() {
496return elaborated_env;
497 }
498499let span = cause.span;
500let infcx = tcx
501 .infer_ctxt()
502 .with_next_trait_solver(true)
503 .ignoring_regions()
504 .build(TypingMode::non_body_analysis());
505let predicates = match crate::solve::deeply_normalize::<_, FulfillmentError<'tcx>>(
506 infcx.at(&cause, elaborated_env),
507 predicates,
508 ) {
509Ok(predicates) => predicates,
510Err(errors) => {
511 infcx.err_ctxt().report_fulfillment_errors(errors);
512// An unnormalized env is better than nothing.
513debug!("normalize_param_env_or_error: errored resolving predicates");
514return elaborated_env;
515 }
516 };
517518debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
519// FIXME(-Zhigher-ranked-assumptions): We're ignoring region errors for now.
520 // There're placeholder constraints `leaking` out.
521 // See the fixme in the enclosing function's docs for more.
522let _errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
523524let predicates = match infcx.fully_resolve(predicates) {
525Ok(predicates) => predicates,
526Err(fixup_err) => {
527span_bug!(
528 span,
529"inference variables in normalized parameter environment: {}",
530 fixup_err
531 )
532 }
533 };
534debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
535 ty::ParamEnv::new(tcx.mk_clauses(&predicates))
536}
537538#[derive(#[automatically_derived]
impl ::core::fmt::Debug for EvaluateConstErr {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
EvaluateConstErr::HasGenericsOrInfers =>
::core::fmt::Formatter::write_str(f, "HasGenericsOrInfers"),
EvaluateConstErr::InvalidConstParamTy(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidConstParamTy", &__self_0),
EvaluateConstErr::EvaluationFailure(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"EvaluationFailure", &__self_0),
}
}
}Debug)]
539pub enum EvaluateConstErr {
540/// The constant being evaluated was either a generic parameter or inference variable, *or*,
541 /// some unevaluated constant with either generic parameters or inference variables in its
542 /// generic arguments.
543HasGenericsOrInfers,
544/// The type this constant evaluated to is not valid for use in const generics. This should
545 /// always result in an error when checking the constant is correctly typed for the parameter
546 /// it is an argument to, so a bug is delayed when encountering this.
547InvalidConstParamTy(ErrorGuaranteed),
548/// CTFE failed to evaluate the constant in some unrecoverable way (e.g. encountered a `panic!`).
549 /// This is also used when the constant was already tainted by error.
550EvaluationFailure(ErrorGuaranteed),
551}
552553// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
554// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
555// normalization scheme
556/// Evaluates a type system constant returning a `ConstKind::Error` in cases where CTFE failed and
557/// returning the passed in constant if it was not fully concrete (i.e. depended on generic parameters
558/// or inference variables)
559///
560/// You should not call this function unless you are implementing normalization itself. Prefer to use
561/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
562pub fn evaluate_const<'tcx>(
563 infcx: &InferCtxt<'tcx>,
564 ct: ty::Const<'tcx>,
565 param_env: ty::ParamEnv<'tcx>,
566) -> ty::Const<'tcx> {
567match try_evaluate_const(infcx, ct, param_env) {
568Ok(ct) => ct,
569Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
570 ty::Const::new_error(infcx.tcx, e)
571 }
572Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
573 }
574}
575576// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
577// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
578// normalization scheme
579/// Evaluates a type system constant making sure to not allow constants that depend on generic parameters
580/// or inference variables to succeed in evaluating.
581///
582/// You should not call this function unless you are implementing normalization itself. Prefer to use
583/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
584x;#[instrument(level = "debug", skip(infcx), ret)]585pub fn try_evaluate_const<'tcx>(
586 infcx: &InferCtxt<'tcx>,
587 ct: ty::Const<'tcx>,
588 param_env: ty::ParamEnv<'tcx>,
589) -> Result<ty::Const<'tcx>, EvaluateConstErr> {
590let tcx = infcx.tcx;
591let ct = infcx.resolve_vars_if_possible(ct);
592debug!(?ct);
593594match ct.kind() {
595 ty::ConstKind::Value(..) => Ok(ct),
596 ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
597 ty::ConstKind::Param(_)
598 | ty::ConstKind::Infer(_)
599 | ty::ConstKind::Bound(_, _)
600 | ty::ConstKind::Placeholder(_)
601 | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
602 ty::ConstKind::Unevaluated(uv) => {
603let opt_anon_const_kind =
604 (tcx.def_kind(uv.def) == DefKind::AnonConst).then(|| tcx.anon_const_kind(uv.def));
605606// Postpone evaluation of constants that depend on generic parameters or
607 // inference variables.
608 //
609 // We use `TypingMode::PostAnalysis` here which is not *technically* correct
610 // to be revealing opaque types here as borrowcheck has not run yet. However,
611 // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during
612 // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
613 // As a result we always use a revealed env when resolving the instance to evaluate.
614 //
615 // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
616 // instead of having this logic here
617let (args, typing_env) = match opt_anon_const_kind {
618// We handle `generic_const_exprs` separately as reasonable ways of handling constants in the type system
619 // completely fall apart under `generic_const_exprs` and makes this whole function Really hard to reason
620 // about if you have to consider gce whatsoever.
621Some(ty::AnonConstKind::GCE) => {
622if uv.has_non_region_infer() || uv.has_non_region_param() {
623// `feature(generic_const_exprs)` causes anon consts to inherit all parent generics. This can cause
624 // inference variables and generic parameters to show up in `ty::Const` even though the anon const
625 // does not actually make use of them. We handle this case specially and attempt to evaluate anyway.
626match tcx.thir_abstract_const(uv.def) {
627Ok(Some(ct)) => {
628let ct = tcx.expand_abstract_consts(ct.instantiate(tcx, uv.args));
629if let Err(e) = ct.error_reported() {
630return Err(EvaluateConstErr::EvaluationFailure(e));
631 } else if ct.has_non_region_infer() || ct.has_non_region_param() {
632// If the anon const *does* actually use generic parameters or inference variables from
633 // the generic arguments provided for it, then we should *not* attempt to evaluate it.
634return Err(EvaluateConstErr::HasGenericsOrInfers);
635 } else {
636let args =
637 replace_param_and_infer_args_with_placeholder(tcx, uv.args);
638let typing_env = infcx
639 .typing_env(tcx.erase_and_anonymize_regions(param_env))
640 .with_post_analysis_normalized(tcx);
641 (args, typing_env)
642 }
643 }
644Err(_) | Ok(None) => {
645let args = GenericArgs::identity_for_item(tcx, uv.def);
646let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
647 (args, typing_env)
648 }
649 }
650 } else {
651let typing_env = infcx
652 .typing_env(tcx.erase_and_anonymize_regions(param_env))
653 .with_post_analysis_normalized(tcx);
654 (uv.args, typing_env)
655 }
656 }
657Some(ty::AnonConstKind::RepeatExprCount) => {
658if uv.has_non_region_infer() {
659// Diagnostics will sometimes replace the identity args of anon consts in
660 // array repeat expr counts with inference variables so we have to handle this
661 // even though it is not something we should ever actually encounter.
662 //
663 // Array repeat expr counts are allowed to syntactically use generic parameters
664 // but must not actually depend on them in order to evalaute successfully. This means
665 // that it is actually fine to evalaute them in their own environment rather than with
666 // the actually provided generic arguments.
667tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
668 }
669670// The generic args of repeat expr counts under `min_const_generics` are not supposed to
671 // affect evaluation of the constant as this would make it a "truly" generic const arg.
672 // To prevent this we discard all the generic arguments and evalaute with identity args
673 // and in its own environment instead of the current environment we are normalizing in.
674let args = GenericArgs::identity_for_item(tcx, uv.def);
675let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
676677 (args, typing_env)
678 }
679Some(ty::AnonConstKind::GCA)
680 | Some(ty::AnonConstKind::MCG)
681 | Some(ty::AnonConstKind::NonTypeSystem)
682 | None => {
683// We are only dealing with "truly" generic/uninferred constants here:
684 // - GCEConsts have been handled separately
685 // - Repeat expr count back compat consts have also been handled separately
686 // So we are free to simply defer evaluation here.
687 //
688 // FIXME: This assumes that `args` are normalized which is not necessarily true
689 //
690 // Const patterns are converted to type system constants before being
691 // evaluated. However, we don't care about them here as pattern evaluation
692 // logic does not go through type system normalization. If it did this would
693 // be a backwards compatibility problem as we do not enforce "syntactic" non-
694 // usage of generic parameters like we do here.
695if uv.args.has_non_region_param() || uv.args.has_non_region_infer() {
696return Err(EvaluateConstErr::HasGenericsOrInfers);
697 }
698699// Since there is no generic parameter, we can just drop the environment
700 // to prevent query cycle.
701let typing_env = ty::TypingEnv::fully_monomorphized();
702703 (uv.args, typing_env)
704 }
705 };
706707let uv = ty::UnevaluatedConst::new(uv.def, args);
708let erased_uv = tcx.erase_and_anonymize_regions(uv);
709710use rustc_middle::mir::interpret::ErrorHandled;
711// FIXME: `def_span` will point at the definition of this const; ideally, we'd point at
712 // where it gets used as a const generic.
713match tcx.const_eval_resolve_for_typeck(typing_env, erased_uv, tcx.def_span(uv.def)) {
714Ok(Ok(val)) => Ok(ty::Const::new_value(
715 tcx,
716 val,
717 tcx.type_of(uv.def).instantiate(tcx, uv.args),
718 )),
719Ok(Err(_)) => {
720let e = tcx.dcx().delayed_bug(
721"Type system constant with non valtree'able type evaluated but no error emitted",
722 );
723Err(EvaluateConstErr::InvalidConstParamTy(e))
724 }
725Err(ErrorHandled::Reported(info, _)) => {
726Err(EvaluateConstErr::EvaluationFailure(info.into()))
727 }
728Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
729 }
730 }
731 }
732}
733734/// Replaces args that reference param or infer variables with suitable
735/// placeholders. This function is meant to remove these param and infer
736/// args when they're not actually needed to evaluate a constant.
737fn replace_param_and_infer_args_with_placeholder<'tcx>(
738 tcx: TyCtxt<'tcx>,
739 args: GenericArgsRef<'tcx>,
740) -> GenericArgsRef<'tcx> {
741struct ReplaceParamAndInferWithPlaceholder<'tcx> {
742 tcx: TyCtxt<'tcx>,
743 idx: ty::BoundVar,
744 }
745746impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
747fn cx(&self) -> TyCtxt<'tcx> {
748self.tcx
749 }
750751fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
752if let ty::Infer(_) = t.kind() {
753let idx = self.idx;
754self.idx += 1;
755Ty::new_placeholder(
756self.tcx,
757 ty::PlaceholderType::new(
758 ty::UniverseIndex::ROOT,
759 ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
760 ),
761 )
762 } else {
763t.super_fold_with(self)
764 }
765 }
766767fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
768if let ty::ConstKind::Infer(_) = c.kind() {
769let idx = self.idx;
770self.idx += 1;
771 ty::Const::new_placeholder(
772self.tcx,
773 ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst::new(idx)),
774 )
775 } else {
776c.super_fold_with(self)
777 }
778 }
779 }
780781args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: ty::BoundVar::ZERO })
782}
783784/// Normalizes the predicates and checks whether they hold in an empty environment. If this
785/// returns true, then either normalize encountered an error or one of the predicates did not
786/// hold. Used when creating vtables to check for unsatisfiable methods. This should not be
787/// used during analysis.
788pub fn impossible_predicates<'tcx>(tcx: TyCtxt<'tcx>, predicates: Vec<ty::Clause<'tcx>>) -> bool {
789{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:789",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(789u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("impossible_predicates(predicates={0:?})",
predicates) as &dyn Value))])
});
} else { ; }
};debug!("impossible_predicates(predicates={:?})", predicates);
790let (infcx, param_env) = tcx791 .infer_ctxt()
792 .with_next_trait_solver(true)
793 .build_with_typing_env(ty::TypingEnv::fully_monomorphized());
794795let ocx = ObligationCtxt::new(&infcx);
796let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
797for predicate in predicates {
798let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
799 ocx.register_obligation(obligation);
800 }
801802// Use `try_evaluate_obligations` to only return impossible for true errors,
803 // and not ambiguities or overflows. Since the new trait solver forces
804 // some currently undetected overlap between `dyn Trait: Trait` built-in
805 // vs user-written impls to AMBIGUOUS, this may return ambiguity even
806 // with no infer vars. There may also be ways to encounter ambiguity due
807 // to post-mono overflow.
808let true_errors = ocx.try_evaluate_obligations();
809if !true_errors.is_empty() {
810return true;
811 }
812813false
814}
815816fn instantiate_and_check_impossible_predicates<'tcx>(
817 tcx: TyCtxt<'tcx>,
818 key: (DefId, GenericArgsRef<'tcx>),
819) -> bool {
820{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:820",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(820u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_predicates(key={0:?})",
key) as &dyn Value))])
});
} else { ; }
};debug!("instantiate_and_check_impossible_predicates(key={:?})", key);
821822let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
823824// Specifically check trait fulfillment to avoid an error when trying to resolve
825 // associated items.
826if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) {
827let trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, key.1);
828predicates.push(trait_ref.upcast(tcx));
829 }
830831predicates.retain(|predicate| !predicate.has_param());
832let result = impossible_predicates(tcx, predicates);
833834{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/mod.rs:834",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(834u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_predicates(key={0:?}) = {1:?}",
key, result) as &dyn Value))])
});
} else { ; }
};debug!("instantiate_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
835result836}
837838/// Checks whether a trait's associated item is impossible to reference on a given impl.
839///
840/// This only considers predicates that reference the impl's generics, and not
841/// those that reference the method's generics.
842fn is_impossible_associated_item(
843 tcx: TyCtxt<'_>,
844 (impl_def_id, trait_item_def_id): (DefId, DefId),
845) -> bool {
846struct ReferencesOnlyParentGenerics<'tcx> {
847 tcx: TyCtxt<'tcx>,
848 generics: &'tcx ty::Generics,
849 trait_item_def_id: DefId,
850 }
851impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
852type Result = ControlFlow<()>;
853fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
854// If this is a parameter from the trait item's own generics, then bail
855if let ty::Param(param) = *t.kind()
856 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
857 && self.tcx.parent(param_def_id) == self.trait_item_def_id
858 {
859return ControlFlow::Break(());
860 }
861t.super_visit_with(self)
862 }
863fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
864if let ty::ReEarlyParam(param) = r.kind()
865 && let param_def_id = self.generics.region_param(param, self.tcx).def_id
866 && self.tcx.parent(param_def_id) == self.trait_item_def_id
867 {
868return ControlFlow::Break(());
869 }
870 ControlFlow::Continue(())
871 }
872fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
873if let ty::ConstKind::Param(param) = ct.kind()
874 && let param_def_id = self.generics.const_param(param, self.tcx).def_id
875 && self.tcx.parent(param_def_id) == self.trait_item_def_id
876 {
877return ControlFlow::Break(());
878 }
879ct.super_visit_with(self)
880 }
881 }
882883let generics = tcx.generics_of(trait_item_def_id);
884let predicates = tcx.predicates_of(trait_item_def_id);
885886// Be conservative in cases where we have `W<T: ?Sized>` and a method like `Self: Sized`,
887 // since that method *may* have some substitutions where the predicates hold.
888 //
889 // This replicates the logic we use in coherence.
890let infcx = tcx891 .infer_ctxt()
892 .ignoring_regions()
893 .with_next_trait_solver(true)
894 .build(TypingMode::Coherence);
895let param_env = ty::ParamEnv::empty();
896let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
897898let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate(tcx, fresh_args);
899900let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
901let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
902pred.visit_with(&mut visitor).is_continue().then(|| {
903Obligation::new(
904tcx,
905ObligationCause::dummy_with_span(*span),
906param_env,
907 ty::EarlyBinder::bind(*pred).instantiate(tcx, impl_trait_ref.args),
908 )
909 })
910 });
911912let ocx = ObligationCtxt::new(&infcx);
913ocx.register_obligations(predicates_for_trait);
914 !ocx.try_evaluate_obligations().is_empty()
915}
916917pub fn provide(providers: &mut Providers) {
918 dyn_compatibility::provide(providers);
919 vtable::provide(providers);
920*providers = Providers {
921 specialization_graph_of: specialize::specialization_graph_provider,
922 specializes: specialize::specializes,
923 specialization_enabled_in: specialize::specialization_enabled_in,
924instantiate_and_check_impossible_predicates,
925is_impossible_associated_item,
926 ..*providers927 };
928}