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 implied_outlives_bounds;
13pub mod misc;
14pub mod normalize;
15pub mod outlives_bounds;
16pub mod outlives_for_liveness;
17pub mod project;
18pub mod query;
19pub mod select;
20pub mod specialize;
21mod structural_normalize;
22pub mod util;
23pub mod vtable;
24pub mod wf;
2526use std::fmt::Debug;
27use std::ops::ControlFlow;
2829use rustc_errors::ErrorGuaranteed;
30pub use rustc_infer::traits::*;
31use rustc_macros::TypeVisitable;
32use rustc_middle::query::Providers;
33use rustc_middle::ty::consts::ConstExt;
34use rustc_middle::ty::error::{ExpectedFound, TypeError};
35use rustc_middle::ty::{
36self, BottomUpFolder, Clause, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
37TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode,
38Unnormalized, 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::{FulfillmentEngine, ObligationCtxt};
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::Outlives103 | FulfillmentErrorCode::Subtype(_, _)
104 | FulfillmentErrorCode::ConstEquate(_, _) => true,
105 FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
106false
107}
108 }
109 }
110}
111112#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for FulfillmentErrorCode<'tcx> {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Cycle(__self_0) =>
Self::Cycle(::core::clone::Clone::clone(__self_0)),
Self::Select(__self_0) =>
Self::Select(::core::clone::Clone::clone(__self_0)),
Self::Project(__self_0) =>
Self::Project(::core::clone::Clone::clone(__self_0)),
Self::Outlives => Self::Outlives,
Self::Subtype(__self_0, __self_1) =>
Self::Subtype(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::ConstEquate(__self_0, __self_1) =>
Self::ConstEquate(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::Ambiguity { overflow: __self_0 } =>
Self::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::Outlives => {}
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)]
113pub enum FulfillmentErrorCode<'tcx> {
114/// Inherently impossible to fulfill; this trait is implemented if and only
115 /// if it is already implemented.
116Cycle(PredicateObligations<'tcx>),
117 Select(SelectionError<'tcx>),
118 Project(MismatchedProjectionTypes<'tcx>),
119/// An outlives constraint emitted for `-Zassumptions-on-binders` was unsatisfiable.
120Outlives,
121 Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
122ConstEquate(ExpectedFound<ty::Const<'tcx>>, TypeError<'tcx>),
123 Ambiguity {
124/// Overflow is only `Some(suggest_recursion_limit)` when using the next generation
125 /// trait solver `-Znext-solver`. With the old solver overflow is eagerly handled by
126 /// emitting a fatal error instead.
127overflow: Option<bool>,
128 },
129}
130131impl<'tcx> Debugfor FulfillmentErrorCode<'tcx> {
132fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133match *self {
134 FulfillmentErrorCode::Select(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
135 FulfillmentErrorCode::Project(ref e) => f.write_fmt(format_args!("{0:?}", e))write!(f, "{e:?}"),
136 FulfillmentErrorCode::Outlives => f.write_fmt(format_args!("CodeOutlivesError"))write!(f, "CodeOutlivesError"),
137 FulfillmentErrorCode::Subtype(ref a, ref b) => {
138f.write_fmt(format_args!("CodeSubtypeError({0:?}, {1:?})", a, b))write!(f, "CodeSubtypeError({a:?}, {b:?})")139 }
140 FulfillmentErrorCode::ConstEquate(ref a, ref b) => {
141f.write_fmt(format_args!("CodeConstEquateError({0:?}, {1:?})", a, b))write!(f, "CodeConstEquateError({a:?}, {b:?})")142 }
143 FulfillmentErrorCode::Ambiguity { overflow: None } => f.write_fmt(format_args!("Ambiguity"))write!(f, "Ambiguity"),
144 FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
145f.write_fmt(format_args!("Overflow({0})", suggest_increasing_limit))write!(f, "Overflow({suggest_increasing_limit})")146 }
147 FulfillmentErrorCode::Cycle(ref cycle) => f.write_fmt(format_args!("Cycle({0:?})", cycle))write!(f, "Cycle({cycle:?})"),
148 }
149 }
150}
151152/// Whether to skip the leak check, as part of a future compatibility warning step.
153///
154/// The "default" for skip-leak-check corresponds to the current
155/// behavior (do not skip the leak check) -- not the behavior we are
156/// transitioning into.
157#[derive(#[automatically_derived]
impl ::core::marker::Copy for SkipLeakCheck { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SkipLeakCheck { }
#[automatically_derived]
impl ::core::clone::Clone for SkipLeakCheck {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SkipLeakCheck { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SkipLeakCheck {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SkipLeakCheck { }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() -> Self { Self::No }
}Default)]
158pub enum SkipLeakCheck {
159 Yes,
160#[default]
161No,
162}
163164impl SkipLeakCheck {
165fn is_yes(self) -> bool {
166self == SkipLeakCheck::Yes167 }
168}
169170/// The mode that trait queries run in.
171#[derive(#[automatically_derived]
impl ::core::marker::Copy for TraitQueryMode { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TraitQueryMode { }
#[automatically_derived]
impl ::core::clone::Clone for TraitQueryMode {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for TraitQueryMode { }
#[automatically_derived]
impl ::core::cmp::PartialEq for TraitQueryMode {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TraitQueryMode { }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)]
172pub enum TraitQueryMode {
173/// Standard/un-canonicalized queries get accurate
174 /// spans etc. passed in and hence can do reasonable
175 /// error reporting on their own.
176Standard,
177/// Canonical queries get dummy spans and hence
178 /// must generally propagate errors to
179 /// pre-canonicalization callsites.
180Canonical,
181}
182183/// Creates predicate obligations from the generic bounds.
184{}
#[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("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(184u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("generic_bounds")
}> =
::tracing::__macro_support::FieldName::new("generic_bounds");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_bounds)
as &dyn ::tracing::field::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: normalize_clause(clause).as_predicate(),
})
}
}
}#[instrument(level = "debug", skip(cause, param_env, normalize_clause))]185pub fn predicates_for_generics<'tcx>(
186 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
187mut normalize_clause: impl FnMut(Unnormalized<'tcx, Clause<'tcx>>) -> Clause<'tcx>,
188 param_env: ty::ParamEnv<'tcx>,
189 generic_bounds: ty::InstantiatedClauses<'tcx>,
190) -> impl Iterator<Item = PredicateObligation<'tcx>> {
191 generic_bounds.into_iter().enumerate().map(move |(idx, (clause, span))| Obligation {
192 cause: cause(idx, span),
193 recursion_depth: 0,
194 param_env,
195 predicate: normalize_clause(clause).as_predicate(),
196 })
197}
198199/// Determines whether the type `ty` is known to meet `bound` and
200/// returns true if so. Returns false if `ty` either does not meet
201/// `bound` or is not known to meet bound (note that this is
202/// conservative towards *no impl*, which is the opposite of the
203/// `evaluate` methods).
204pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
205 infcx: &InferCtxt<'tcx>,
206 param_env: ty::ParamEnv<'tcx>,
207 ty: Ty<'tcx>,
208 def_id: DefId,
209) -> bool {
210let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
211pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
212}
213214/// FIXME(@lcnr): this function doesn't seem right and shouldn't exist?
215///
216/// Ping me on zulip if you want to use this method and need help with finding
217/// an appropriate replacement.
218{}
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("pred_known_to_hold_modulo_regions",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(218u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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: bool = loop {};
return __tracing_attr_fake_return;
}
{
let obligation =
Obligation::new(infcx.tcx, ObligationCause::dummy(),
param_env, pred);
let result =
infcx.evaluate_obligation_no_overflow(&obligation);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:227",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(227u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("result")
}> =
::tracing::__macro_support::FieldName::new("result");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&result)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if result.must_apply_modulo_regions() {
true
} else if result.may_apply() && !infcx.next_trait_solver() {
let goal =
infcx.deeply_resolve_ignoring_regions((obligation.predicate,
obligation.param_env));
infcx.probe(|_|
{
let ocx = ObligationCtxt::new(infcx);
ocx.register_obligation(obligation);
let errors = ocx.evaluate_obligations_error_on_ambiguity();
match errors {
TraitErrors::NoErrors =>
infcx.deeply_resolve_ignoring_regions(goal) == goal,
TraitErrors::HasErrors(errors) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:248",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(248u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("errors")
}> =
::tracing::__macro_support::FieldName::new("errors");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&errors)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
false
}
}
})
} else { false }
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:218",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(218u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(infcx, param_env, pred), ret)]219fn pred_known_to_hold_modulo_regions<'tcx>(
220 infcx: &InferCtxt<'tcx>,
221 param_env: ty::ParamEnv<'tcx>,
222 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
223) -> bool {
224let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
225226let result = infcx.evaluate_obligation_no_overflow(&obligation);
227debug!(?result);
228229if result.must_apply_modulo_regions() {
230true
231} else if result.may_apply() && !infcx.next_trait_solver() {
232// Sometimes obligations are ambiguous because the recursive evaluator
233 // is not smart enough, so we fall back to fulfillment when we're not certain
234 // that an obligation holds or not. Even still, we must make sure that
235 // the we do no inference in the process of checking this obligation.
236let goal =
237 infcx.deeply_resolve_ignoring_regions((obligation.predicate, obligation.param_env));
238 infcx.probe(|_| {
239let ocx = ObligationCtxt::new(infcx);
240 ocx.register_obligation(obligation);
241242let errors = ocx.evaluate_obligations_error_on_ambiguity();
243match errors {
244// Only known to hold if we did no inference.
245TraitErrors::NoErrors => infcx.deeply_resolve_ignoring_regions(goal) == goal,
246247 TraitErrors::HasErrors(errors) => {
248debug!(?errors);
249false
250}
251 }
252 })
253 } else {
254false
255}
256}
257258fn set_projection_term_to_non_rigid<'tcx>(
259 tcx: TyCtxt<'tcx>,
260 predicates: impl IntoIterator<Item = ty::Clause<'tcx>>,
261) -> impl Iterator<Item = ty::Clause<'tcx>> {
262predicates.into_iter().map(move |clause| {
263if let ty::ClauseKind::Projection(projection_pred) = clause.kind().skip_binder() {
264clause265 .kind()
266 .rebind(ty::ProjectionClause {
267 projection_term: projection_pred.projection_term,
268 term: ty::set_aliases_to_non_rigid(tcx, projection_pred.term).skip_norm_wip(),
269 })
270 .upcast(tcx)
271 } else {
272clause273 }
274 })
275}
276277enum ReplaceRegions {
278 Yes,
279 No,
280}
281282fn replace_infer_and_non_rigid_alias_with_error<'tcx, T>(
283 infcx: &InferCtxt<'tcx>,
284 value: T,
285 guar: ErrorGuaranteed,
286 replace_regions: ReplaceRegions,
287) -> T
288where
289T: TypeFoldable<TyCtxt<'tcx>>,
290{
291let tcx = infcx.tcx;
292value.fold_with(&mut BottomUpFolder {
293tcx,
294 ty_op: |ty| {
295let ty = infcx.shallow_resolve(ty);
296match ty.kind() {
297 ty::Infer(ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_)) => {
298Ty::new_error(tcx, guar)
299 }
300 ty::Alias(ty::IsRigid::No, _) if tcx.next_trait_solver_globally() => {
301Ty::new_error(tcx, guar)
302 }
303_ => ty,
304 }
305 },
306 lt_op: |lt| match replace_regions {
307// We can't resolve regions using lexical resolution here since
308 // that's private. It probably doesn't matter since we already
309 // got more severe error.
310ReplaceRegions::Yes => match lt.kind() {
311 ty::ReVar(_) => ty::Region::new_error(tcx, guar),
312_ => lt,
313 },
314 ReplaceRegions::No => lt,
315 },
316 ct_op: |ct| {
317let ct = infcx.shallow_resolve_const(ct);
318match ct.kind() {
319 ty::ConstKind::Infer(ty::InferConst::Var(_)) => ty::Const::new_error(tcx, guar),
320 ty::ConstKind::Alias(ty::IsRigid::No, _) if tcx.next_trait_solver_globally() => {
321 ty::Const::new_error(tcx, guar)
322 }
323_ => ct,
324 }
325 },
326 })
327}
328329{}
#[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_clauses",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(329u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("clauses")
}> =
::tracing::__macro_support::FieldName::new("clauses");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clauses)
as &dyn ::tracing::field::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: Vec<ty::Clause<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{
let infcx =
tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
let elaborated_env =
if tcx.next_trait_solver_globally() &&
!tcx.disable_param_env_normalization_hack() {
let elaborated_env =
ty::set_type_aliases_to_rigid(tcx, elaborated_env);
let elaborated_env =
set_projection_term_to_non_rigid(tcx,
elaborated_env.caller_bounds());
ty::ParamEnv::new(tcx, elaborated_env)
} else { elaborated_env };
let clauses =
ocx.normalize(&cause, elaborated_env,
Unnormalized::new_wip(clauses));
let clauses =
if tcx.next_trait_solver_globally() {
if !tcx.disable_param_env_normalization_hack() {
let clauses: Vec<_> =
set_projection_term_to_non_rigid(tcx, clauses).collect();
ty::set_opaques_to_non_rigid(tcx, clauses).skip_norm_wip()
} else {
ty::set_aliases_to_non_rigid(tcx, clauses).skip_norm_wip()
}
} else { clauses };
let errors = ocx.evaluate_obligations_error_on_ambiguity();
let clauses =
if let TraitErrors::HasErrors(errors) = errors {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:384",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(384u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("do_normalize_clauses: failed to normalize clauses")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let guar =
infcx.err_ctxt().report_fulfillment_errors(errors);
replace_infer_and_non_rigid_alias_with_error(&infcx,
clauses, guar, ReplaceRegions::No)
} else { clauses };
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:391",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(391u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("do_normalize_clauses: normalized clauses = {0:?}",
clauses) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let normalized_env =
ty::ParamEnv::new(tcx, clauses.iter().copied());
let _errors =
infcx.resolve_regions(cause.body_def_id, normalized_env, []);
match infcx.deeply_resolve_via_region_graph(clauses.clone()) {
Ok(clauses) => clauses,
Err(fixup_err) => {
let guar =
tcx.dcx().span_delayed_bug(cause.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("inference variables in normalized parameter environment: {0}",
fixup_err))
}));
replace_infer_and_non_rigid_alias_with_error(&infcx,
clauses, guar, ReplaceRegions::Yes)
}
}
}
}
}#[instrument(level = "debug", skip(tcx, elaborated_env))]330fn do_normalize_clauses<'tcx>(
331 tcx: TyCtxt<'tcx>,
332 cause: ObligationCause<'tcx>,
333 elaborated_env: ty::ParamEnv<'tcx>,
334 clauses: Vec<ty::Clause<'tcx>>,
335) -> Vec<ty::Clause<'tcx>> {
336// FIXME. We should really... do something with these region
337 // obligations. But this call just continues the older
338 // behavior (i.e., doesn't cause any new bugs), and it would
339 // take some further refactoring to actually solve them. In
340 // particular, we would have to handle implied bounds
341 // properly, and that code is currently largely confined to
342 // regionck (though I made some efforts to extract it
343 // out). -nmatsakis
344 //
345 // @arielby: In any case, these obligations are checked
346 // by wfcheck anyway, so I'm not sure we have to check
347 // them here too, and we will remove this function when
348 // we move over to lazy normalization *anyway*.
349let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
350let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
351// FIXME: `elaborated_env` is not really rigid. We do this to be
352 // consistent with the old solver.
353let elaborated_env = if tcx.next_trait_solver_globally()
354 && !tcx.disable_param_env_normalization_hack()
355 {
356let elaborated_env = ty::set_type_aliases_to_rigid(tcx, elaborated_env);
357let elaborated_env = set_projection_term_to_non_rigid(tcx, elaborated_env.caller_bounds());
358 ty::ParamEnv::new(tcx, elaborated_env)
359 } else {
360 elaborated_env
361 };
362let clauses = ocx.normalize(&cause, elaborated_env, Unnormalized::new_wip(clauses));
363let clauses = if tcx.next_trait_solver_globally() {
364if !tcx.disable_param_env_normalization_hack() {
365let clauses: Vec<_> = set_projection_term_to_non_rigid(tcx, clauses).collect();
366// FIXME(type_alias_impl_trait): opaque types in param env might be
367 // in defining scope but we're using non body analysis here.
368 // So the rigidness marker is wrong.
369ty::set_opaques_to_non_rigid(tcx, clauses).skip_norm_wip()
370 } else {
371// Param env is used in different typing modes but itself
372 // is normalized in `non_body_analysis`.
373 // That not only makes the rigidness of opaques types wrong,
374 // other aliases can be indirectly affected as well.
375 // So we conservatively set everything to be non-rigid.
376ty::set_aliases_to_non_rigid(tcx, clauses).skip_norm_wip()
377 }
378 } else {
379 clauses
380 };
381382let errors = ocx.evaluate_obligations_error_on_ambiguity();
383let clauses = if let TraitErrors::HasErrors(errors) = errors {
384debug!("do_normalize_clauses: failed to normalize clauses");
385let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
386 replace_infer_and_non_rigid_alias_with_error(&infcx, clauses, guar, ReplaceRegions::No)
387 } else {
388 clauses
389 };
390391debug!("do_normalize_clauses: normalized clauses = {:?}", clauses);
392393// FIXME: It's very weird that we ignore region obligations but apparently
394 // still need to use `resolve_regions` as we need the resolved regions in
395 // the normalized clauses.
396 //
397 // FIXME(-Zhigher-ranked-assumptions): We're ignoring region errors for now.
398 // There're placeholder constraints `leaking` out. This is a hack to work around
399 // the fact that we don't support placeholder assumptions right now and is necessary
400 // for `compare_method_clause_entailment`. We should remove this once we have proper
401 // support for implied bounds on binders.
402 //
403 // This ignoring is required by trait-system-refactor-initiative#166. The new solver encounters
404 // this more frequently as we entirely ignore outlives clauses with the old solver.
405 //
406 // FIXME: We should avoid interning clauses both here and at the
407 // caller sites. We should also avoid cloning if possible.
408let normalized_env = ty::ParamEnv::new(tcx, clauses.iter().copied());
409let _errors = infcx.resolve_regions(cause.body_def_id, normalized_env, []);
410match infcx.deeply_resolve_via_region_graph(clauses.clone()) {
411Ok(clauses) => clauses,
412Err(fixup_err) => {
413// The first folder only replaces infers from normalization failure. We might not have
414 // normalization failure and have unconstrained ty/const vars from ill-formed impls.
415 // See `tests/ui/traits/normalize/self-referential-param-env-normalization.rs`.
416 //
417 // We delay a bug here instead of immediately ICEing and let type checking report the
418 // actual user-facing errors.
419let guar = tcx.dcx().span_delayed_bug(
420 cause.span,
421format!("inference variables in normalized parameter environment: {fixup_err}"),
422 );
423424// This is slightly wrong as we replace opaques with errors.
425 //
426 // We still need to replace regions because `fully_resolve` eagerly returns `Err` if
427 // it encounters unconstrained ty/const var. Thus region vars might not get replaced.
428replace_infer_and_non_rigid_alias_with_error(&infcx, clauses, guar, ReplaceRegions::Yes)
429 }
430 }
431}
432433// FIXME: this is gonna need to be removed ...
434/// Normalizes the parameter environment, reporting errors if they occur.
435{}
#[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("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(435u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("unnormalized_env")
}> =
::tracing::__macro_support::FieldName::new("unnormalized_env");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unnormalized_env)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::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 clauses: Vec<_> =
util::elaborate(tcx,
unnormalized_env.caller_bounds().into_iter().map(|clause|
{
if tcx.features().generic_const_exprs() ||
tcx.next_trait_solver_globally() {
return clause;
}
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::Alias(_, alias_const) = c.kind() &&
#[allow(non_exhaustive_omitted_patterns)] match alias_const.kind
{
ty::AliasConstKind::Anon { .. } => true,
_ => false,
} {
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
}
}
clause.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 /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:528",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(528u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: elaborated-clauses={0:?}",
clauses) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let elaborated_env =
ty::ParamEnv::new(tcx, clauses.iter().copied());
if !elaborated_env.has_aliases() { return elaborated_env; }
let outlives_clauses: Vec<_> =
clauses.extract_if(..,
|clause|
{
#[allow(non_exhaustive_omitted_patterns)]
match clause.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 /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:559",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(559u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: clauses=(non-outlives={0:?}, outlives={1:?})",
clauses, outlives_clauses) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
let non_outlives_clauses =
do_normalize_clauses(tcx, cause.clone(), elaborated_env,
clauses);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:565",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(565u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: non-outlives clauses={0:?}",
non_outlives_clauses) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let outlives_env =
non_outlives_clauses.iter().chain(&outlives_clauses).cloned();
let outlives_env = ty::ParamEnv::new(tcx, outlives_env);
let outlives_clauses =
do_normalize_clauses(tcx, cause, outlives_env,
outlives_clauses);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:573",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(573u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: outlives clauses={0:?}",
outlives_clauses) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let mut clauses = non_outlives_clauses;
clauses.extend(outlives_clauses);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:577",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(577u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalize_param_env_or_error: final clauses={0:?}",
clauses) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
ty::ParamEnv::new(tcx, clauses)
}
}
}#[instrument(level = "debug", skip(tcx))]436pub fn normalize_param_env_or_error<'tcx>(
437 tcx: TyCtxt<'tcx>,
438 unnormalized_env: ty::ParamEnv<'tcx>,
439 cause: ObligationCause<'tcx>,
440) -> ty::ParamEnv<'tcx> {
441// I'm not wild about reporting errors here; I'd prefer to
442 // have the errors get reported at a defined place (e.g.,
443 // during typeck). Instead I have all parameter
444 // environments, in effect, going through this function
445 // and hence potentially reporting errors. This ensures of
446 // course that we never forget to normalize (the
447 // alternative seemed like it would involve a lot of
448 // manual invocations of this fn -- and then we'd have to
449 // deal with the errors at each of those sites).
450 //
451 // In any case, in practice, typeck constructs all the
452 // parameter environments once for every fn as it goes,
453 // and errors will get reported then; so outside of type inference we
454 // can be sure that no errors should occur.
455let mut clauses: Vec<_> = util::elaborate(
456 tcx,
457 unnormalized_env.caller_bounds().into_iter().map(|clause| {
458if tcx.features().generic_const_exprs() || tcx.next_trait_solver_globally() {
459return clause;
460 }
461462struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
463464impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
465fn cx(&self) -> TyCtxt<'tcx> {
466self.0
467}
468469fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
470// FIXME(return_type_notation): track binders in this normalizer, as
471 // `ty::Const::normalize` can only work with properly preserved binders.
472473if c.has_escaping_bound_vars() {
474return ty::Const::new_misc_error(self.0);
475 }
476477// While it is pretty sus to be evaluating things with an empty param env, it
478 // should actually be okay since without `feature(generic_const_exprs)` the only
479 // const arguments that have a non-empty param env are array repeat counts. These
480 // do not appear in the type system though.
481if let ty::ConstKind::Alias(_, alias_const) = c.kind()
482 && matches!(alias_const.kind, ty::AliasConstKind::Anon { .. })
483 {
484let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
485let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
486// We should never wind up with any `infcx` local state when normalizing anon consts
487 // under min const generics.
488assert!(!c.has_infer() && !c.has_placeholders());
489return c;
490 }
491492 c
493 }
494 }
495496// This whole normalization step is a hack to work around the fact that
497 // `normalize_param_env_or_error` is fundamentally broken from using an
498 // unnormalized param env with a trait solver that expects the param env
499 // to be normalized.
500 //
501 // When normalizing the param env we can end up evaluating obligations
502 // that have been normalized but can only be proven via a where clause
503 // which is still in its unnormalized form. example:
504 //
505 // Attempting to prove `T: Trait<<u8 as Identity>::Assoc>` in a param env
506 // with a `T: Trait<<u8 as Identity>::Assoc>` where clause will fail because
507 // we first normalize obligations before proving them so we end up proving
508 // `T: Trait<u8>`. Since lazy normalization is not implemented equating `u8`
509 // with `<u8 as Identity>::Assoc` fails outright so we incorrectly believe that
510 // we cannot prove `T: Trait<u8>`.
511 //
512 // The same thing is true for const generics- attempting to prove
513 // `T: Trait<ConstKind::Alias(...)>` with the same thing as a where clauses
514 // will fail. After normalization we may be attempting to prove `T: Trait<4>` with
515 // the unnormalized where clause `T: Trait<ConstKind::Alias(...)>`. In order
516 // for the obligation to hold `4` must be equal to `ConstKind::Alias(...)`
517 // but as we do not have lazy norm implemented, equating the two consts fails outright.
518 //
519 // Ideally we would not normalize consts here at all but it is required for backwards
520 // compatibility. Eventually when lazy norm is implemented this can just be removed.
521 // We do not normalize types here as there is no backwards compatibility requirement
522 // for us to do so.
523clause.fold_with(&mut ConstNormalizer(tcx))
524 }),
525 )
526 .collect();
527528debug!("normalize_param_env_or_error: elaborated-clauses={:?}", clauses);
529530let elaborated_env = ty::ParamEnv::new(tcx, clauses.iter().copied());
531if !elaborated_env.has_aliases() {
532return elaborated_env;
533 }
534535// HACK: we are trying to normalize the param-env inside *itself*. The problem is that
536 // normalization expects its param-env to be already normalized, which means we have
537 // a circularity.
538 //
539 // The way we handle this is by normalizing the param-env inside an unnormalized version
540 // of the param-env, which means that if the param-env contains unnormalized projections,
541 // we'll have some normalization failures. This is unfortunate.
542 //
543 // Lazy normalization would basically handle this by treating just the
544 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
545 //
546 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
547 // types, so to make the situation less bad, we normalize all the predicates *but*
548 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
549 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
550 //
551 // This works fairly well because trait matching does not actually care about param-env
552 // TypeOutlives clauses - these are normally used by regionck.
553let outlives_clauses: Vec<_> = clauses
554 .extract_if(.., |clause| {
555matches!(clause.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
556 })
557 .collect();
558559debug!(
560"normalize_param_env_or_error: clauses=(non-outlives={:?}, outlives={:?})",
561 clauses, outlives_clauses
562 );
563let non_outlives_clauses = do_normalize_clauses(tcx, cause.clone(), elaborated_env, clauses);
564565debug!("normalize_param_env_or_error: non-outlives clauses={:?}", non_outlives_clauses);
566567// Not sure whether it is better to include the unnormalized TypeOutlives clauses
568 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
569 // clauses here anyway. Keeping them here anyway because it seems safer.
570let outlives_env = non_outlives_clauses.iter().chain(&outlives_clauses).cloned();
571let outlives_env = ty::ParamEnv::new(tcx, outlives_env);
572let outlives_clauses = do_normalize_clauses(tcx, cause, outlives_env, outlives_clauses);
573debug!("normalize_param_env_or_error: outlives clauses={:?}", outlives_clauses);
574575let mut clauses = non_outlives_clauses;
576 clauses.extend(outlives_clauses);
577debug!("normalize_param_env_or_error: final clauses={:?}", clauses);
578 ty::ParamEnv::new(tcx, clauses)
579}
580581#[derive(#[automatically_derived]
impl<E: ::core::fmt::Debug> ::core::fmt::Debug for EvaluateConstErr<E> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::HasGenericsOrInfers =>
::core::fmt::Formatter::write_str(f, "HasGenericsOrInfers"),
Self::InvalidConstParamTy(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InvalidConstParamTy", &__self_0),
Self::EvaluationFailure(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"EvaluationFailure", &__self_0),
Self::FailedNormalization(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"FailedNormalization", &__self_0),
}
}
}Debug)]
582pub enum EvaluateConstErr<E> {
583/// The constant being evaluated was either a generic parameter or inference variable, *or*,
584 /// some alias const with either generic parameters or inference variables in its
585 /// generic arguments.
586HasGenericsOrInfers,
587/// The type this constant evaluated to is not valid for use in const generics. This should
588 /// always result in an error when checking the constant is correctly typed for the parameter
589 /// it is an argument to, so a bug is delayed when encountering this.
590InvalidConstParamTy(ErrorGuaranteed),
591/// CTFE failed to evaluate the constant in some unrecoverable way (e.g. encountered a `panic!`).
592 /// This is also used when the constant was already tainted by error.
593EvaluationFailure(ErrorGuaranteed),
594 FailedNormalization(E),
595}
596597// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
598// FIXME(generic_const_exprs): Consider accepting a `ty::AliasConst` when we are not rolling our own
599// normalization scheme
600/// Evaluates a type system constant returning a `ConstKind::Error` in cases where CTFE failed and
601/// returning the passed in constant if it was not fully concrete (i.e. depended on generic parameters
602/// or inference variables)
603///
604/// You should not call this function unless you are implementing normalization itself. Prefer to use
605/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
606pub fn evaluate_const<'tcx>(
607 infcx: &InferCtxt<'tcx>,
608 ct: ty::Const<'tcx>,
609 param_env: ty::ParamEnv<'tcx>,
610) -> ty::Const<'tcx> {
611match try_evaluate_const(infcx, ct, param_env, |v| Ok::<_, !>(v.skip_norm_wip())) {
612Ok(ct) => ct,
613Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
614 ty::Const::new_error(infcx.tcx, e)
615 }
616Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
617 }
618}
619620// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
621// FIXME(generic_const_exprs): Consider accepting a `ty::AliasConst` when we are not rolling our own
622// normalization scheme
623/// Evaluates a type system constant making sure to not allow constants that depend on generic parameters
624/// or inference variables to succeed in evaluating.
625///
626/// You should not call this function unless you are implementing normalization itself. Prefer to use
627/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
628{}
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("try_evaluate_const",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(628u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ct")
}> =
::tracing::__macro_support::FieldName::new("ct");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_env")
}> =
::tracing::__macro_support::FieldName::new("param_env");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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<ty::Const<'tcx>, EvaluateConstErr<E>> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = infcx.tcx;
let ct = infcx.deeply_resolve_ignoring_regions(ct);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:637",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(637u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ct")
}> =
::tracing::__macro_support::FieldName::new("ct");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
match ct.kind() {
ty::ConstKind::Value(..) => Ok(ct),
ty::ConstKind::Error(e) =>
Err(EvaluateConstErr::EvaluationFailure(e)),
ty::ConstKind::Param(_) | ty::ConstKind::Infer(_) |
ty::ConstKind::Bound(_, _) | ty::ConstKind::Placeholder(_) |
ty::ConstKind::Expr(_) =>
Err(EvaluateConstErr::HasGenericsOrInfers),
ty::ConstKind::Alias(_, alias_const) => {
let opt_anon_const_kind =
match alias_const.kind {
ty::AliasConstKind::Anon { def_id } =>
Some((def_id, tcx.anon_const_kind(def_id))),
_ => None,
};
let (args, typing_env) =
match opt_anon_const_kind {
Some((def_id, ty::AnonConstKind::GCE)) => {
if alias_const.has_non_region_infer() ||
alias_const.has_non_region_param() {
match tcx.thir_abstract_const(def_id) {
Ok(Some(ct)) => {
let ct =
tcx.expand_abstract_consts(ct.instantiate(tcx,
alias_const.args).skip_norm_wip());
if let Err(e) = ct.error_reported() {
return Err(EvaluateConstErr::EvaluationFailure(e));
} else if ct.has_non_region_infer() ||
ct.has_non_region_param() {
return Err(EvaluateConstErr::HasGenericsOrInfers);
} else {
let args =
replace_param_and_infer_args_with_placeholder(tcx,
alias_const.args);
let typing_env =
infcx.typing_env(tcx.erase_and_anonymize_regions(param_env)).with_post_analysis_normalized(tcx);
(args, typing_env)
}
}
Err(_) | Ok(None) => {
let args = GenericArgs::identity_for_item(tcx, def_id);
let typing_env = ty::TypingEnv::post_analysis(tcx, def_id);
(args, typing_env)
}
}
} else {
let typing_env =
infcx.typing_env(tcx.erase_and_anonymize_regions(param_env)).with_post_analysis_normalized(tcx);
(alias_const.args, typing_env)
}
}
Some((def_id, ty::AnonConstKind::RepeatExprCount)) => {
if alias_const.has_non_region_infer() {
tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
}
let args = GenericArgs::identity_for_item(tcx, def_id);
let typing_env = ty::TypingEnv::post_analysis(tcx, def_id);
(args, typing_env)
}
Some((_,
ty::AnonConstKind::MCG |
ty::AnonConstKind::NonTypeSystemAnon |
ty::AnonConstKind::NonTypeSystemInline)) | None => {
if alias_const.args.has_non_region_param() ||
alias_const.args.has_non_region_infer() ||
alias_const.args.has_non_region_placeholders() {
return Err(EvaluateConstErr::HasGenericsOrInfers);
}
let typing_env = ty::TypingEnv::fully_monomorphized();
(alias_const.args, typing_env)
}
};
let alias_const =
ty::AliasConst::new(tcx, alias_const.kind, args);
let erased_alias_const =
tcx.erase_and_anonymize_regions(alias_const);
use rustc_middle::mir::interpret::ErrorHandled;
let span = alias_const.kind.def_span(tcx);
match tcx.const_eval_resolve_for_typeck(typing_env,
erased_alias_const, span) {
Ok(Ok(val)) => {
let ty =
normalize_ty(alias_const.type_of(tcx)).map_err(EvaluateConstErr::FailedNormalization)?;
Ok(ty::Const::new_value(tcx, val, ty))
}
Ok(Err(_)) => {
let e =
tcx.dcx().delayed_bug("Type system constant with non valtree'able type evaluated but no error emitted");
Err(EvaluateConstErr::InvalidConstParamTy(e))
}
Err(ErrorHandled::Reported(info, _)) => {
Err(EvaluateConstErr::EvaluationFailure(info.into()))
}
Err(ErrorHandled::TooGeneric(_)) =>
Err(EvaluateConstErr::HasGenericsOrInfers),
}
}
}
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:628",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(628u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(infcx, normalize_ty), ret)]629pub fn try_evaluate_const<'tcx, E: Debug>(
630 infcx: &InferCtxt<'tcx>,
631 ct: ty::Const<'tcx>,
632 param_env: ty::ParamEnv<'tcx>,
633 normalize_ty: impl FnOnce(Unnormalized<'tcx, Ty<'tcx>>) -> Result<Ty<'tcx>, E>,
634) -> Result<ty::Const<'tcx>, EvaluateConstErr<E>> {
635let tcx = infcx.tcx;
636let ct = infcx.deeply_resolve_ignoring_regions(ct);
637debug!(?ct);
638639match ct.kind() {
640 ty::ConstKind::Value(..) => Ok(ct),
641 ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
642 ty::ConstKind::Param(_)
643 | ty::ConstKind::Infer(_)
644 | ty::ConstKind::Bound(_, _)
645 | ty::ConstKind::Placeholder(_)
646 | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
647 ty::ConstKind::Alias(_, alias_const) => {
648let opt_anon_const_kind = match alias_const.kind {
649 ty::AliasConstKind::Anon { def_id } => Some((def_id, tcx.anon_const_kind(def_id))),
650_ => None,
651 };
652653// Postpone evaluation of constants that depend on generic parameters or
654 // inference variables.
655 //
656 // We use `TypingMode::PostAnalysis` here which is not *technically* correct
657 // to be revealing opaque types here as borrowcheck has not run yet. However,
658 // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during
659 // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
660 // As a result we always use a revealed env when resolving the instance to evaluate.
661 //
662 // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
663 // instead of having this logic here
664let (args, typing_env) = match opt_anon_const_kind {
665// We handle `generic_const_exprs` separately as reasonable ways of handling constants in the type system
666 // completely fall apart under `generic_const_exprs` and makes this whole function Really hard to reason
667 // about if you have to consider gce whatsoever.
668Some((def_id, ty::AnonConstKind::GCE)) => {
669if alias_const.has_non_region_infer() || alias_const.has_non_region_param() {
670// `feature(generic_const_exprs)` causes anon consts to inherit all parent generics. This can cause
671 // inference variables and generic parameters to show up in `ty::Const` even though the anon const
672 // does not actually make use of them. We handle this case specially and attempt to evaluate anyway.
673match tcx.thir_abstract_const(def_id) {
674Ok(Some(ct)) => {
675let ct = tcx.expand_abstract_consts(
676 ct.instantiate(tcx, alias_const.args).skip_norm_wip(),
677 );
678if let Err(e) = ct.error_reported() {
679return Err(EvaluateConstErr::EvaluationFailure(e));
680 } else if ct.has_non_region_infer() || ct.has_non_region_param() {
681// If the anon const *does* actually use generic parameters or inference variables from
682 // the generic arguments provided for it, then we should *not* attempt to evaluate it.
683return Err(EvaluateConstErr::HasGenericsOrInfers);
684 } else {
685let args = replace_param_and_infer_args_with_placeholder(
686 tcx,
687 alias_const.args,
688 );
689let typing_env = infcx
690 .typing_env(tcx.erase_and_anonymize_regions(param_env))
691 .with_post_analysis_normalized(tcx);
692 (args, typing_env)
693 }
694 }
695Err(_) | Ok(None) => {
696let args = GenericArgs::identity_for_item(tcx, def_id);
697let typing_env = ty::TypingEnv::post_analysis(tcx, def_id);
698 (args, typing_env)
699 }
700 }
701 } else {
702let typing_env = infcx
703 .typing_env(tcx.erase_and_anonymize_regions(param_env))
704 .with_post_analysis_normalized(tcx);
705 (alias_const.args, typing_env)
706 }
707 }
708Some((def_id, ty::AnonConstKind::RepeatExprCount)) => {
709if alias_const.has_non_region_infer() {
710// Diagnostics will sometimes replace the identity args of anon consts in
711 // array repeat expr counts with inference variables so we have to handle this
712 // even though it is not something we should ever actually encounter.
713 //
714 // Array repeat expr counts are allowed to syntactically use generic parameters
715 // but must not actually depend on them in order to evalaute successfully. This means
716 // that it is actually fine to evalaute them in their own environment rather than with
717 // the actually provided generic arguments.
718tcx.dcx().delayed_bug("AnonConst with infer args but no error reported");
719 }
720721// The generic args of repeat expr counts under `min_const_generics` are not supposed to
722 // affect evaluation of the constant as this would make it a "truly" generic const arg.
723 // To prevent this we discard all the generic arguments and evalaute with identity args
724 // and in its own environment instead of the current environment we are normalizing in.
725let args = GenericArgs::identity_for_item(tcx, def_id);
726let typing_env = ty::TypingEnv::post_analysis(tcx, def_id);
727728 (args, typing_env)
729 }
730Some((
731_,
732 ty::AnonConstKind::MCG
733 | ty::AnonConstKind::NonTypeSystemAnon
734 | ty::AnonConstKind::NonTypeSystemInline,
735 ))
736 | None => {
737// We are only dealing with "truly" generic/uninferred constants here:
738 // - GCEConsts have been handled separately
739 // - Repeat expr count back compat consts have also been handled separately
740 // So we are free to simply defer evaluation here.
741 //
742 // FIXME: This assumes that `args` are normalized which is not necessarily true
743 //
744 // Const patterns are converted to type system constants before being
745 // evaluated. However, we don't care about them here as pattern evaluation
746 // logic does not go through type system normalization. If it did this would
747 // be a backwards compatibility problem as we do not enforce "syntactic" non-
748 // usage of generic parameters like we do here.
749if alias_const.args.has_non_region_param()
750 || alias_const.args.has_non_region_infer()
751 || alias_const.args.has_non_region_placeholders()
752 {
753return Err(EvaluateConstErr::HasGenericsOrInfers);
754 }
755756// Since there is no generic parameter, we can just drop the environment
757 // to prevent query cycle.
758let typing_env = ty::TypingEnv::fully_monomorphized();
759760 (alias_const.args, typing_env)
761 }
762 };
763764let alias_const = ty::AliasConst::new(tcx, alias_const.kind, args);
765let erased_alias_const = tcx.erase_and_anonymize_regions(alias_const);
766767use rustc_middle::mir::interpret::ErrorHandled;
768// FIXME: `def_span` will point at the definition of this const; ideally, we'd point at
769 // where it gets used as a const generic.
770let span = alias_const.kind.def_span(tcx);
771match tcx.const_eval_resolve_for_typeck(typing_env, erased_alias_const, span) {
772Ok(Ok(val)) => {
773let ty = normalize_ty(alias_const.type_of(tcx))
774 .map_err(EvaluateConstErr::FailedNormalization)?;
775Ok(ty::Const::new_value(tcx, val, ty))
776 }
777Ok(Err(_)) => {
778let e = tcx.dcx().delayed_bug(
779"Type system constant with non valtree'able type evaluated but no error emitted",
780 );
781Err(EvaluateConstErr::InvalidConstParamTy(e))
782 }
783Err(ErrorHandled::Reported(info, _)) => {
784Err(EvaluateConstErr::EvaluationFailure(info.into()))
785 }
786Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
787 }
788 }
789 }
790}
791792/// Replaces args that reference param or infer variables with suitable
793/// placeholders. This function is meant to remove these param and infer
794/// args when they're not actually needed to evaluate a constant.
795fn replace_param_and_infer_args_with_placeholder<'tcx>(
796 tcx: TyCtxt<'tcx>,
797 args: GenericArgsRef<'tcx>,
798) -> GenericArgsRef<'tcx> {
799struct ReplaceParamAndInferWithPlaceholder<'tcx> {
800 tcx: TyCtxt<'tcx>,
801 idx: ty::BoundVar,
802 }
803804impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
805fn cx(&self) -> TyCtxt<'tcx> {
806self.tcx
807 }
808809fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
810if let ty::Infer(_) = t.kind() {
811let idx = self.idx;
812self.idx += 1;
813Ty::new_placeholder(
814self.tcx,
815 ty::PlaceholderType::new(
816 ty::UniverseIndex::ROOT,
817 ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon },
818 ),
819 )
820 } else {
821t.super_fold_with(self)
822 }
823 }
824825fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
826if let ty::ConstKind::Infer(_) = c.kind() {
827let idx = self.idx;
828self.idx += 1;
829 ty::Const::new_placeholder(
830self.tcx,
831 ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst::new(idx)),
832 )
833 } else {
834c.super_fold_with(self)
835 }
836 }
837 }
838839args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: ty::BoundVar::ZERO })
840}
841842/// Normalizes the clauses and checks whether they hold in an empty environment. If this
843/// returns true, then either normalize encountered an error or one of the clauses did not
844/// hold. Used when creating vtables to check for unsatisfiable methods. This should not be
845/// used during analysis.
846pub fn impossible_clauses<'tcx>(tcx: TyCtxt<'tcx>, clauses: Vec<ty::Clause<'tcx>>) -> bool {
847{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:847",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(847u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("impossible_clauses(clauses={0:?})",
clauses) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("impossible_clauses(clauses={:?})", clauses);
848let (infcx, param_env) = tcx849 .infer_ctxt()
850 .with_next_trait_solver(true)
851 .enable_next_solver_overflow_fcw(false)
852 .build_with_typing_env(ty::TypingEnv::fully_monomorphized());
853854let ocx = ObligationCtxt::new(&infcx);
855let clauses =
856ocx.normalize(&ObligationCause::dummy(), param_env, Unnormalized::new_wip(clauses));
857for clause in clauses {
858let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause);
859 ocx.register_obligation(obligation);
860 }
861862// Use `try_evaluate_obligations` to only return impossible for true errors,
863 // and not ambiguities or overflows. Since the new trait solver forces
864 // some currently undetected overlap between `dyn Trait: Trait` built-in
865 // vs user-written impls to AMBIGUOUS, this may return ambiguity even
866 // with no infer vars. There may also be ways to encounter ambiguity due
867 // to post-mono overflow.
868!ocx.try_evaluate_obligations().no_errors()
869}
870871fn instantiate_and_check_impossible_clauses<'tcx>(
872 tcx: TyCtxt<'tcx>,
873 key: (DefId, GenericArgsRef<'tcx>),
874) -> bool {
875{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:875",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(875u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_clauses(key={0:?})",
key) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("instantiate_and_check_impossible_clauses(key={:?})", key);
876877let mut clauses: Vec<_> = tcx878 .clauses_of(key.0)
879 .instantiate(tcx, key.1)
880 .clauses
881 .into_iter()
882 .map(Unnormalized::skip_norm_wip)
883 .collect();
884885// Specifically check trait fulfillment to avoid an error when trying to resolve
886 // associated items.
887if let Some(trait_def_id) = tcx.trait_of_assoc(key.0) {
888let trait_ref = ty::TraitRef::from_assoc(tcx, trait_def_id, key.1);
889clauses.push(trait_ref.upcast(tcx));
890 }
891892clauses.retain(|clause| !clause.has_param());
893let result = impossible_clauses(tcx, clauses);
894895{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs:895",
"rustc_trait_selection::traits", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c36f1457196e315bc204b9564a6a5a7fe7f5a51f/compiler/rustc_trait_selection/src/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(895u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("instantiate_and_check_impossible_clauses(key={0:?}) = {1:?}",
key, result) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("instantiate_and_check_impossible_clauses(key={:?}) = {:?}", key, result);
896result897}
898899/// Checks whether a trait's associated item is impossible to reference on a given impl.
900///
901/// This only considers predicates that reference the impl's generics, and not
902/// those that reference the method's generics.
903fn is_impossible_associated_item(
904 tcx: TyCtxt<'_>,
905 (impl_def_id, trait_item_def_id): (DefId, DefId),
906) -> bool {
907struct ReferencesOnlyParentGenerics<'tcx> {
908 tcx: TyCtxt<'tcx>,
909 generics: &'tcx ty::Generics,
910 trait_item_def_id: DefId,
911 }
912impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
913type Result = ControlFlow<()>;
914fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
915// If this is a parameter from the trait item's own generics, then bail
916if let ty::Param(param) = *t.kind()
917 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
918 && self.tcx.parent(param_def_id) == self.trait_item_def_id
919 {
920return ControlFlow::Break(());
921 }
922t.super_visit_with(self)
923 }
924fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
925if let ty::ReEarlyParam(param) = r.kind()
926 && let param_def_id = self.generics.region_param(param, self.tcx).def_id
927 && self.tcx.parent(param_def_id) == self.trait_item_def_id
928 {
929return ControlFlow::Break(());
930 }
931 ControlFlow::Continue(())
932 }
933fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
934if let ty::ConstKind::Param(param) = ct.kind()
935 && let param_def_id = self.generics.const_param(param, self.tcx).def_id
936 && self.tcx.parent(param_def_id) == self.trait_item_def_id
937 {
938return ControlFlow::Break(());
939 }
940ct.super_visit_with(self)
941 }
942 }
943944let generics = tcx.generics_of(trait_item_def_id);
945let gen_clauses = tcx.clauses_of(trait_item_def_id);
946947// Be conservative in cases where we have `W<T: ?Sized>` and a method like `Self: Sized`,
948 // since that method *may* have some substitutions where the predicates hold.
949 //
950 // This replicates the logic we use in coherence.
951let infcx = tcx952 .infer_ctxt()
953 .ignoring_regions()
954 .with_next_trait_solver(true)
955 .enable_next_solver_overflow_fcw(false)
956 .build(TypingMode::Coherence);
957let param_env = ty::ParamEnv::empty();
958let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
959960let impl_trait_ref =
961tcx.impl_trait_ref(impl_def_id).instantiate(tcx, fresh_args).skip_norm_wip();
962963let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
964let predicates_for_trait = gen_clauses.clauses.iter().filter_map(|(clause, span)| {
965clause.visit_with(&mut visitor).is_continue().then(|| {
966Obligation::new(
967tcx,
968ObligationCause::dummy_with_span(*span),
969param_env,
970 ty::EarlyBinder::bind(tcx, *clause)
971 .instantiate(tcx, impl_trait_ref.args)
972 .skip_norm_wip(),
973 )
974 })
975 });
976977let ocx = ObligationCtxt::new(&infcx);
978ocx.register_obligations(predicates_for_trait);
979 !ocx.try_evaluate_obligations().no_errors()
980}
981982pub fn provide(providers: &mut Providers) {
983 dyn_compatibility::provide(providers);
984 vtable::provide(providers);
985*providers = Providers {
986 specialization_graph_of: specialize::specialization_graph_provider,
987 specializes: specialize::specializes,
988 specialization_enabled_in: specialize::specialization_enabled_in,
989instantiate_and_check_impossible_clauses,
990is_impossible_associated_item,
991 live_args_for_alias_from_outlives_bounds:
992 outlives_for_liveness::live_args_for_alias_from_outlives_bounds,
993 args_known_to_outlive_alias_params:
994 outlives_for_liveness::args_known_to_outlive_alias_params,
995 ..*providers996 };
997}