1use std::cell::LazyCell;
2use std::ops::{ControlFlow, Deref};
3
4use hir::intravisit::{self, Visitor};
5use rustc_abi::{ExternAbi, ScalableElt};
6use rustc_ast as ast;
7use rustc_attr_ir::lang_items::LangItem;
8use rustc_attr_ir::{EiiDecl, EiiImpl, EiiImplResolution, find_attr};
9use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
10use rustc_data_structures::transitive_relation::TransitiveRelationBuilder;
11use rustc_errors::codes::*;
12use rustc_errors::{
13 Applicability, ErrorGuaranteed, MultiSpan, msg, pluralize, struct_span_code_err,
14};
15use rustc_hir as hir;
16use rustc_hir::def::{DefKind, Res};
17use rustc_hir::def_id::{DefId, LocalDefId};
18use rustc_hir::{AmbigArg, ItemKind};
19use rustc_infer::infer::outlives::env::OutlivesEnvironment;
20use rustc_infer::infer::{BoundRegionConversionTime, SolverRegionConstraint, TyCtxtInferExt};
21use rustc_infer::traits::{PredicateObligations, TraitErrors};
22use rustc_lint_defs::builtin::{
23 REDUNDANT_LIFETIMES, SHADOWING_SUPERTRAIT_ITEMS, UNEVALUATED_DEFAULT_FIELD_VALUE,
24};
25use rustc_macros::{Diagnostic, TypeFoldable, TypeVisitable};
26use rustc_middle::mir::interpret::ErrorHandled;
27use rustc_middle::traits::solve::NoSolution;
28use rustc_middle::ty::print::with_no_trimmed_paths;
29use rustc_middle::ty::region_constraint::{And, LeafRegionConstraint, Or};
30use rustc_middle::ty::trait_def::TraitSpecializationKind;
31use rustc_middle::ty::{
32 self, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags, TypeFoldable,
33 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
34 Upcast,
35};
36use rustc_session::diagnostics::feature_err;
37use rustc_span::{DUMMY_SP, Span, bug, span_bug, sym};
38use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
39use rustc_trait_selection::regions::{
40 OutlivesEnvironmentBuildExt, region_known_to_outlive, ty_known_to_outlive,
41};
42use rustc_trait_selection::traits::misc::{
43 ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
44};
45use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
46use rustc_trait_selection::traits::{
47 self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
48 WellFormedLoc,
49};
50use tracing::{debug, instrument};
51
52use super::compare_eii::{compare_eii_function_types, compare_eii_statics};
53use crate::autoderef::Autoderef;
54use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
55use crate::diagnostics::{
56 self, InvalidReceiverTyHint, ParamInTyOfConstParam, UnevaluatedDefaultFieldValue,
57};
58
59pub(super) struct WfCheckingCtxt<'a, 'tcx> {
60 pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
61 body_def_id: LocalDefId,
62 param_env: ty::ParamEnv<'tcx>,
63}
64impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
65 type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
66 fn deref(&self) -> &Self::Target {
67 &self.ocx
68 }
69}
70
71impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
72 fn tcx(&self) -> TyCtxt<'tcx> {
73 self.ocx.infcx.tcx
74 }
75
76 fn normalize<T>(&self, span: Span, loc: WellFormedLoc, value: Unnormalized<'tcx, T>) -> T
79 where
80 T: TypeFoldable<TyCtxt<'tcx>>,
81 {
82 self.ocx.normalize(
83 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
84 self.param_env,
85 value,
86 )
87 }
88
89 pub(super) fn deeply_normalize<T>(
99 &self,
100 span: Span,
101 loc: WellFormedLoc,
102 value: Unnormalized<'tcx, T>,
103 ) -> T
104 where
105 T: TypeFoldable<TyCtxt<'tcx>>,
106 {
107 if self.infcx.next_trait_solver() {
108 match self.ocx.deeply_normalize(
109 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
110 self.param_env,
111 value.clone(),
112 ) {
113 Ok(value) => value,
114 Err(errors) => {
115 self.infcx.err_ctxt().report_fulfillment_errors(errors);
116 value.skip_norm_wip()
117 }
118 }
119 } else {
120 self.normalize(span, loc, value)
121 }
122 }
123
124 pub(super) fn register_wf_obligation(
125 &self,
126 span: Span,
127 loc: WellFormedLoc,
128 term: ty::Term<'tcx>,
129 ) {
130 let cause = traits::ObligationCause::new(
131 span,
132 self.body_def_id,
133 ObligationCauseCode::WellFormed(loc),
134 );
135 self.ocx.register_obligation(Obligation::new(
136 self.tcx(),
137 cause,
138 self.param_env,
139 ty::ClauseKind::WellFormed(term),
140 ));
141 }
142
143 pub(super) fn unnormalized_obligations(
144 &self,
145 span: Span,
146 ty: Ty<'tcx>,
147 ) -> Option<PredicateObligations<'tcx>> {
148 traits::wf::unnormalized_obligations(
149 self.ocx.infcx,
150 self.param_env,
151 ty.into(),
152 span,
153 self.body_def_id,
154 )
155 }
156}
157
158pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
159 tcx: TyCtxt<'tcx>,
160 body_def_id: LocalDefId,
161 f: F,
162) -> Result<(), ErrorGuaranteed>
163where
164 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
165{
166 let param_env = tcx.param_env(body_def_id);
167 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
168 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
169
170 let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
171
172 let ignore_bounds =
175 tcx.def_kind(body_def_id) == DefKind::TyAlias && !tcx.type_alias_is_checked(body_def_id);
176
177 if !ignore_bounds && !tcx.features().trivial_bounds() {
178 wfcx.check_false_global_bounds()
179 }
180 f(&mut wfcx)?;
181
182 let errors = wfcx.evaluate_obligations_error_on_ambiguity();
183 if let TraitErrors::HasErrors(errors) = errors {
184 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
185 }
186
187 let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
188 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:188",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(188u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("assumed_wf_types")
}> =
::tracing::__macro_support::FieldName::new("assumed_wf_types");
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(&assumed_wf_types)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?assumed_wf_types);
189
190 let infcx_compat = infcx.fork();
191
192 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
195 &infcx,
196 body_def_id,
197 param_env,
198 assumed_wf_types.iter().copied(),
199 true,
200 );
201
202 lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
203
204 let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
205 if errors.is_empty() {
206 return Ok(());
207 }
208
209 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
210 &infcx_compat,
211 body_def_id,
212 param_env,
213 assumed_wf_types,
214 false,
217 );
218 let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
219 if errors_compat.is_empty() {
220 Ok(())
223 } else {
224 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
225 }
226}
227
228pub(super) fn check_well_formed(
229 tcx: TyCtxt<'_>,
230 def_id: LocalDefId,
231) -> Result<(), ErrorGuaranteed> {
232 let mut res = crate::check::check::check_item_type(tcx, def_id);
233
234 for param in &tcx.generics_of(def_id).own_params {
235 res = res.and(check_param_wf(tcx, param));
236 }
237
238 res
239}
240
241{}
#[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("check_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(254u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
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(&item)
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let def_id = item.owner_id.def_id;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:261",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(261u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.owner_id")
}> =
::tracing::__macro_support::FieldName::new("item.owner_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.name")
}> =
::tracing::__macro_support::FieldName::new("item.name");
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(&item.owner_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tcx.def_path_str(def_id))
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
match item.kind {
hir::ItemKind::Impl(ref impl_) => {
crate::impl_wf_check::check_impl_wf(tcx, def_id,
impl_.of_trait.is_some())?;
let mut res = Ok(());
if let Some(of_trait) = impl_.of_trait {
let header = tcx.impl_trait_header(def_id);
let is_auto =
tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
if let (hir::Defaultness::Default { .. }, true) =
(of_trait.defaultness, is_auto) {
let sp = of_trait.trait_ref.path.span;
res =
Err(tcx.dcx().struct_span_err(sp,
"impls of auto traits cannot be default").with_span_labels(of_trait.defaultness_span,
"default because of this").with_span_label(sp,
"auto trait").emit_err());
}
match header.polarity {
ty::ImplPolarity::Positive => {
res = res.and(check_impl(tcx, item, impl_));
}
ty::ImplPolarity::Negative => {
let ast::ImplPolarity::Negative(span) =
of_trait.polarity else {
::rustc_span::macros::bug_impl(None,
format_args!("impl_polarity query disagrees with impl\'s polarity in HIR"),
Location::caller());
};
if let hir::Defaultness::Default { .. } =
of_trait.defaultness {
let mut spans =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[span]));
spans.extend(of_trait.defaultness_span);
res =
Err({
tcx.dcx().struct_span_err(spans,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("negative impls cannot be default impls"))
})).with_code(E0750)
}.emit_err());
}
}
}
} else { res = res.and(check_impl(tcx, item, impl_)); }
res
}
hir::ItemKind::Fn { sig, .. } =>
check_item_fn(tcx, def_id, sig.decl),
_ =>
::rustc_span::macros::bug_impl(Some(item.span),
format_args!("should have been handled by the type based wf check: {0:?}",
item), Location::caller()),
}
}
}
}#[instrument(skip(tcx), level = "debug")]
255pub(super) fn check_item<'tcx>(
256 tcx: TyCtxt<'tcx>,
257 item: &'tcx hir::Item<'tcx>,
258) -> Result<(), ErrorGuaranteed> {
259 let def_id = item.owner_id.def_id;
260
261 debug!(
262 ?item.owner_id,
263 item.name = ? tcx.def_path_str(def_id)
264 );
265
266 match item.kind {
267 hir::ItemKind::Impl(ref impl_) => {
285 crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
286 let mut res = Ok(());
287 if let Some(of_trait) = impl_.of_trait {
288 let header = tcx.impl_trait_header(def_id);
289 let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
290 if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
291 let sp = of_trait.trait_ref.path.span;
292 res = Err(tcx
293 .dcx()
294 .struct_span_err(sp, "impls of auto traits cannot be default")
295 .with_span_labels(of_trait.defaultness_span, "default because of this")
296 .with_span_label(sp, "auto trait")
297 .emit_err());
298 }
299 match header.polarity {
300 ty::ImplPolarity::Positive => {
301 res = res.and(check_impl(tcx, item, impl_));
302 }
303 ty::ImplPolarity::Negative => {
304 let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
305 bug!("impl_polarity query disagrees with impl's polarity in HIR");
306 };
307 if let hir::Defaultness::Default { .. } = of_trait.defaultness {
309 let mut spans = vec![span];
310 spans.extend(of_trait.defaultness_span);
311 res = Err(struct_span_code_err!(
312 tcx.dcx(),
313 spans,
314 E0750,
315 "negative impls cannot be default impls"
316 )
317 .emit_err());
318 }
319 }
320 }
321 } else {
322 res = res.and(check_impl(tcx, item, impl_));
323 }
324 res
325 }
326 hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
327 _ => span_bug!(item.span, "should have been handled by the type based wf check: {item:?}"),
329 }
330}
331
332pub(super) fn check_foreign_item<'tcx>(
333 tcx: TyCtxt<'tcx>,
334 item: &'tcx hir::ForeignItem<'tcx>,
335) -> Result<(), ErrorGuaranteed> {
336 let def_id = item.owner_id.def_id;
337
338 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:338",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(338u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.owner_id")
}> =
::tracing::__macro_support::FieldName::new("item.owner_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.name")
}> =
::tracing::__macro_support::FieldName::new("item.name");
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(&item.owner_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tcx.def_path_str(def_id))
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
339 ?item.owner_id,
340 item.name = ? tcx.def_path_str(def_id)
341 );
342
343 match item.kind {
344 hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
345 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
346 }
347}
348
349pub(crate) fn check_trait_item<'tcx>(
350 tcx: TyCtxt<'tcx>,
351 def_id: LocalDefId,
352) -> Result<(), ErrorGuaranteed> {
353 lint_item_shadowing_supertrait_item(tcx, def_id);
355
356 let mut res = Ok(());
357
358 if tcx.def_kind(def_id) == DefKind::AssocFn {
359 for &assoc_ty_def_id in
360 tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
361 {
362 res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
363 }
364 }
365 res
366}
367
368pub(crate) fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
381 let mut required_bounds_by_item = FxIndexMap::default();
383 let associated_items = tcx.associated_items(trait_def_id);
384
385 loop {
391 let mut should_continue = false;
392 for gat_item in associated_items.in_definition_order() {
393 let gat_def_id = gat_item.def_id.expect_local();
394 let gat_item = tcx.associated_item(gat_def_id);
395 if !gat_item.is_type() {
397 continue;
398 }
399 let gat_generics = tcx.generics_of(gat_def_id);
400 if gat_generics.is_own_empty() {
402 continue;
403 }
404
405 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
409 for item in associated_items.in_definition_order() {
410 let item_def_id = item.def_id.expect_local();
411 if item_def_id == gat_def_id {
413 continue;
414 }
415
416 let param_env = tcx.param_env(item_def_id);
417
418 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
419 ty::AssocKind::Fn { .. } => {
421 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
425 item_def_id.to_def_id(),
426 tcx.fn_sig(item_def_id).instantiate_identity().skip_norm_wip(),
427 );
428 gather_gat_bounds(
429 tcx,
430 param_env,
431 item_def_id,
432 sig.inputs_and_output,
433 &sig.inputs().iter().copied().collect(),
436 gat_def_id,
437 gat_generics,
438 )
439 }
440 ty::AssocKind::Type { .. } => {
442 let param_env = augment_param_env(
446 tcx,
447 param_env,
448 required_bounds_by_item.get(&item_def_id),
449 );
450 gather_gat_bounds(
451 tcx,
452 param_env,
453 item_def_id,
454 tcx.explicit_item_bounds(item_def_id)
455 .iter_identity_copied()
456 .map(Unnormalized::skip_norm_wip)
457 .collect::<Vec<_>>(),
458 &FxIndexSet::default(),
459 gat_def_id,
460 gat_generics,
461 )
462 }
463 ty::AssocKind::Const { .. } => None,
464 };
465
466 if let Some(item_required_bounds) = item_required_bounds {
467 if let Some(new_required_bounds) = &mut new_required_bounds {
473 new_required_bounds.retain(|b| item_required_bounds.contains(b));
474 } else {
475 new_required_bounds = Some(item_required_bounds);
476 }
477 }
478 }
479
480 if let Some(new_required_bounds) = new_required_bounds {
481 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
482 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
483 should_continue = true;
486 }
487 }
488 }
489 if !should_continue {
494 break;
495 }
496 }
497
498 for (gat_def_id, required_bounds) in required_bounds_by_item {
499 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
501 continue;
502 }
503
504 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
505 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:505",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(505u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("required_bounds")
}> =
::tracing::__macro_support::FieldName::new("required_bounds");
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(&required_bounds)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?required_bounds);
506 let param_env = tcx.param_env(gat_def_id);
507
508 let unsatisfied_bounds: Vec<_> = required_bounds
509 .into_iter()
510 .filter(|clause| match clause.kind().skip_binder() {
511 ty::ClauseKind::RegionOutlives(ty::OutlivesClause(a, b)) => {
512 !region_known_to_outlive(
513 tcx,
514 gat_def_id,
515 param_env,
516 &FxIndexSet::default(),
517 a,
518 b,
519 )
520 }
521 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(a, b)) => !ty_known_to_outlive(
522 tcx,
523 gat_def_id,
524 param_env,
525 &FxIndexSet::default(),
526 Unnormalized::new_wip(a),
527 b,
528 ),
529 _ => ::rustc_span::macros::bug_impl(None, format_args!("Unexpected ClauseKind"),
Location::caller())bug!("Unexpected ClauseKind"),
530 })
531 .map(|clause| clause.to_string())
532 .collect();
533
534 if !unsatisfied_bounds.is_empty() {
535 let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
536 let suggestion = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
gat_item_hir.generics.add_where_or_trailing_comma(),
unsatisfied_bounds.join(", ")))
})format!(
537 "{} {}",
538 gat_item_hir.generics.add_where_or_trailing_comma(),
539 unsatisfied_bounds.join(", "),
540 );
541 let bound =
542 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
543 tcx.dcx()
544 .struct_span_err(
545 gat_item_hir.span,
546 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing required bound{0} on `{1}`",
plural, gat_item_hir.ident))
})format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
547 )
548 .with_span_suggestion(
549 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
550 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add the required where clause{0}",
plural))
})format!("add the required where clause{plural}"),
551 suggestion,
552 Applicability::MachineApplicable,
553 )
554 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
bound))
})format!(
555 "{bound} currently required to ensure that impls have maximum flexibility"
556 ))
557 .with_note(
558 "we are soliciting feedback, see issue #87479 \
559 <https://github.com/rust-lang/rust/issues/87479> for more information",
560 )
561 .emit();
562 }
563 }
564}
565
566fn augment_param_env<'tcx>(
568 tcx: TyCtxt<'tcx>,
569 param_env: ty::ParamEnv<'tcx>,
570 new_clauses: Option<&FxIndexSet<ty::Clause<'tcx>>>,
571) -> ty::ParamEnv<'tcx> {
572 let Some(new_clauses) = new_clauses else {
573 return param_env;
574 };
575
576 if new_clauses.is_empty() {
577 return param_env;
578 }
579
580 let bounds = param_env.caller_bounds().chain(new_clauses.iter().copied());
581 ty::ParamEnv::new(tcx, bounds)
584}
585
586fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
597 tcx: TyCtxt<'tcx>,
598 param_env: ty::ParamEnv<'tcx>,
599 item_def_id: LocalDefId,
600 to_check: T,
601 wf_tys: &FxIndexSet<Ty<'tcx>>,
602 gat_def_id: LocalDefId,
603 gat_generics: &'tcx ty::Generics,
604) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
605 let mut bounds = FxIndexSet::default();
607
608 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
609
610 if types.is_empty() && regions.is_empty() {
616 return None;
617 }
618
619 for (region_a, region_a_idx) in ®ions {
620 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
624 continue;
625 }
626 for (ty, ty_idx) in &types {
631 if ty_known_to_outlive(
633 tcx,
634 item_def_id,
635 param_env,
636 wf_tys,
637 Unnormalized::new_wip(*ty),
638 *region_a,
639 ) {
640 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:640",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(640u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty_idx")
}> =
::tracing::__macro_support::FieldName::new("ty_idx");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_a_idx")
}> =
::tracing::__macro_support::FieldName::new("region_a_idx");
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(&ty_idx)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_a_idx)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?ty_idx, ?region_a_idx);
641 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:641",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(641u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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!("required clause: {0} must outlive {1}",
ty, region_a) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("required clause: {ty} must outlive {region_a}");
642 let ty_param = gat_generics.param_at(*ty_idx, tcx);
646 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
647 let region_param = gat_generics.param_at(*region_a_idx, tcx);
650 let region_param = ty::Region::new_early_param(
651 tcx,
652 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
653 );
654 bounds.insert(
657 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty_param, region_param))
658 .upcast(tcx),
659 );
660 }
661 }
662
663 for (region_b, region_b_idx) in ®ions {
668 if #[allow(non_exhaustive_omitted_patterns)] match region_b.kind() {
ty::ReStatic | ty::ReError(_) => true,
_ => false,
}matches!(region_b.kind(), ty::ReStatic | ty::ReError(_)) || region_a == region_b {
672 continue;
673 }
674 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
675 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:675",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(675u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_a_idx")
}> =
::tracing::__macro_support::FieldName::new("region_a_idx");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_b_idx")
}> =
::tracing::__macro_support::FieldName::new("region_b_idx");
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(®ion_a_idx)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_b_idx)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?region_a_idx, ?region_b_idx);
676 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:676",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(676u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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!("required clause: {0} must outlive {1}",
region_a, region_b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("required clause: {region_a} must outlive {region_b}");
677 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
679 let region_a_param = ty::Region::new_early_param(
680 tcx,
681 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
682 );
683 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
685 let region_b_param = ty::Region::new_early_param(
686 tcx,
687 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
688 );
689 bounds.insert(
691 ty::ClauseKind::RegionOutlives(ty::OutlivesClause(
692 region_a_param,
693 region_b_param,
694 ))
695 .upcast(tcx),
696 );
697 }
698 }
699 }
700
701 Some(bounds)
702}
703
704struct GATArgsCollector<'tcx> {
709 gat: DefId,
710 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
712 types: FxIndexSet<(Ty<'tcx>, usize)>,
714}
715
716impl<'tcx> GATArgsCollector<'tcx> {
717 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
718 gat: DefId,
719 t: T,
720 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
721 let mut visitor =
722 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
723 t.visit_with(&mut visitor);
724 (visitor.regions, visitor.types)
725 }
726}
727
728impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
729 fn visit_ty(&mut self, t: Ty<'tcx>) {
730 match t.kind() {
731 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
732 if def_id == self.gat =>
733 {
734 for (idx, arg) in args.iter().enumerate() {
735 match arg.kind() {
736 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
737 self.regions.insert((lt, idx));
738 }
739 GenericArgKind::Type(t) => {
740 self.types.insert((t, idx));
741 }
742 _ => {}
743 }
744 }
745 }
746 _ => {}
747 }
748 t.super_visit_with(self)
749 }
750}
751
752fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
753 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
754 let trait_def_id = tcx.local_parent(trait_item_def_id);
755
756 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
757 .skip(1)
758 .flat_map(|supertrait_def_id| {
759 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
760 })
761 .collect();
762 if !shadowed.is_empty() {
763 let shadowee = if let [shadowed] = shadowed[..] {
764 diagnostics::SupertraitItemShadowee::Labeled {
765 span: tcx.def_span(shadowed.def_id),
766 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
767 }
768 } else {
769 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
770 .iter()
771 .map(|item| {
772 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
773 })
774 .unzip();
775 diagnostics::SupertraitItemShadowee::Several {
776 traits: traits.into(),
777 spans: spans.into(),
778 }
779 };
780
781 tcx.emit_node_span_lint(
782 SHADOWING_SUPERTRAIT_ITEMS,
783 tcx.local_def_id_to_hir_id(trait_item_def_id),
784 tcx.def_span(trait_item_def_id),
785 diagnostics::SupertraitItemShadowing {
786 item: item_name,
787 subtrait: tcx.item_name(trait_def_id.to_def_id()),
788 shadowee,
789 },
790 );
791 }
792}
793
794fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
795 match param.kind {
796 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
798
799 ty::GenericParamDefKind::Const { .. } => {
801 let ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
802 let span = tcx.def_span(param.def_id);
803 let def_id = param.def_id.expect_local();
804
805 if tcx.features().const_param_ty_unchecked() {
806 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
807 wfcx.register_wf_obligation(span, WellFormedLoc::None, ty.into());
808 Ok(())
809 })
810 } else if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
811 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
812 wfcx.register_bound(
813 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
814 wfcx.param_env,
815 ty,
816 tcx.require_lang_item(LangItem::ConstParamTy, span),
817 );
818 Ok(())
819 })
820 } else {
821 let span = || {
822 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
823 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
824 else {
825 ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!()
826 };
827 span
828 };
829 let mut diag = match ty.kind() {
830 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
831 ty::FnPtr(..) => tcx.dcx().struct_span_err(
832 span(),
833 "using function pointers as const generic parameters is forbidden",
834 ),
835 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
836 span(),
837 "using raw pointers as const generic parameters is forbidden",
838 ),
839 _ => {
840 ty.error_reported()?;
842
843 tcx.dcx().struct_span_err(
844 span(),
845 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
846 "`{ty}` is forbidden as the type of a const generic parameter",
847 ),
848 )
849 }
850 };
851
852 diag.note("the only supported types are integers, `bool`, and `char`");
853
854 let cause = ObligationCause::misc(span(), def_id);
855 let adt_const_params_feature_string =
856 " more complex and user defined types".to_string();
857 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
858 tcx,
859 tcx.param_env(param.def_id),
860 ty,
861 cause,
862 ) {
863 Err(
865 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
866 | ConstParamTyImplementationError::NonExhaustive(..)
867 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
868 ) => None,
869 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
870 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params),
(" references to implement the `ConstParamTy` trait".into(),
sym::unsized_const_params)]))vec![
871 (adt_const_params_feature_string, sym::min_adt_const_params),
872 (
873 " references to implement the `ConstParamTy` trait".into(),
874 sym::unsized_const_params,
875 ),
876 ])
877 }
878 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
881 fn ty_is_local(ty: Ty<'_>) -> bool {
882 match ty.kind() {
883 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
884 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
886 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
889 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
892 _ => false,
893 }
894 }
895
896 ty_is_local(ty).then_some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params)]))vec![(
897 adt_const_params_feature_string,
898 sym::min_adt_const_params,
899 )])
900 }
901 Ok(..) => {
903 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params)]))vec![(adt_const_params_feature_string, sym::min_adt_const_params)])
904 }
905 };
906 if let Some(features) = may_suggest_feature {
907 tcx.disabled_nightly_features(&mut diag, features);
908 }
909
910 Err(diag.emit_err())
911 }
912 }
913 }
914}
915
916{}
#[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("check_associated_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(916u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
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(&def_id)
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let loc = WellFormedLoc::Ty(def_id);
enter_wf_checking_ctxt(tcx, def_id,
|wfcx|
{
let item = tcx.associated_item(def_id);
tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
let self_ty =
match item.container {
ty::AssocContainer::Trait => tcx.types.self_param,
ty::AssocContainer::InherentImpl |
ty::AssocContainer::TraitImpl(_) => {
tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
}
};
let span = tcx.def_span(def_id);
match item.kind {
ty::AssocKind::Const { .. } => {
let ty = tcx.type_of(def_id).instantiate_identity();
let ty =
wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), ty);
wfcx.register_wf_obligation(span, loc, ty.into());
if item.defaultness(tcx).has_value() {
let code = ObligationCauseCode::SizedConstOrStatic;
wfcx.register_bound(ObligationCause::new(span, def_id,
code), wfcx.param_env, ty,
tcx.require_lang_item(LangItem::Sized, span));
}
check_const_item(wfcx, def_id, ty)
}
ty::AssocKind::Fn { .. } => {
let sig =
tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
let hir_sig =
tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
check_method_receiver(wfcx, hir_sig, item, self_ty)
}
ty::AssocKind::Type { .. } => {
if let ty::AssocContainer::Trait = item.container {
check_associated_type_bounds(wfcx, item, span)
}
if item.defaultness(tcx).has_value() {
let ty = tcx.type_of(def_id).instantiate_identity();
let ty =
wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), ty);
wfcx.register_wf_obligation(span, loc, ty.into());
}
Ok(())
}
}
})
}
}
}#[instrument(level = "debug", skip(tcx))]
917pub(crate) fn check_associated_item(
918 tcx: TyCtxt<'_>,
919 def_id: LocalDefId,
920) -> Result<(), ErrorGuaranteed> {
921 let loc = WellFormedLoc::Ty(def_id);
922 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
923 let item = tcx.associated_item(def_id);
924
925 tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
928
929 let self_ty = match item.container {
930 ty::AssocContainer::Trait => tcx.types.self_param,
931 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
932 tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
933 }
934 };
935
936 let span = tcx.def_span(def_id);
937
938 match item.kind {
939 ty::AssocKind::Const { .. } => {
940 let ty = tcx.type_of(def_id).instantiate_identity();
941 let ty = wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), ty);
942 wfcx.register_wf_obligation(span, loc, ty.into());
943
944 if item.defaultness(tcx).has_value() {
945 let code = ObligationCauseCode::SizedConstOrStatic;
946 wfcx.register_bound(
947 ObligationCause::new(span, def_id, code),
948 wfcx.param_env,
949 ty,
950 tcx.require_lang_item(LangItem::Sized, span),
951 );
952 }
953
954 check_const_item(wfcx, def_id, ty)
955 }
956 ty::AssocKind::Fn { .. } => {
957 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
958 let hir_sig =
959 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
960 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
961 check_method_receiver(wfcx, hir_sig, item, self_ty)
962 }
963 ty::AssocKind::Type { .. } => {
964 if let ty::AssocContainer::Trait = item.container {
965 check_associated_type_bounds(wfcx, item, span)
966 }
967 if item.defaultness(tcx).has_value() {
968 let ty = tcx.type_of(def_id).instantiate_identity();
969 let ty = wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), ty);
970 wfcx.register_wf_obligation(span, loc, ty.into());
971 }
972 Ok(())
973 }
974 }
975 })
976}
977
978pub(crate) fn check_type_defn<'tcx>(
980 tcx: TyCtxt<'tcx>,
981 item: LocalDefId,
982 all_sized: bool,
983) -> Result<(), ErrorGuaranteed> {
984 tcx.ensure_ok().check_representability(item);
985 let adt_def = tcx.adt_def(item);
986
987 enter_wf_checking_ctxt(tcx, item, |wfcx| {
988 let variants = adt_def.variants();
989 let packed = adt_def.repr().packed();
990 let own_params_require_monomorphization =
991 tcx.generics_of(item).own_requires_monomorphization();
992
993 for variant in variants.iter() {
994 for field in &variant.fields {
996 if let Some(def_id) = field.value {
997 if !own_params_require_monomorphization {
998 let _ = tcx.const_eval_poly(def_id);
999 } else if tcx.features().default_field_values()
1000 && let Some(local_def_id) = def_id.as_local()
1001 {
1002 let field_span = tcx.def_span(def_id).source_callsite();
1007 let mut multispan: MultiSpan = field_span.into();
1008 multispan
1009 .push_span_label(field_span, "this can't be const-evaluated until use");
1010 let struct_start = tcx.def_span(item).shrink_to_lo();
1011 multispan.push_span_context(tcx.def_span(field.did));
1012 multispan.push_span_context(struct_start);
1013 tcx.emit_node_span_lint(
1014 UNEVALUATED_DEFAULT_FIELD_VALUE,
1015 tcx.local_def_id_to_hir_id(local_def_id),
1016 multispan,
1017 UnevaluatedDefaultFieldValue {
1018 field: field.name,
1019 ty: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(item) }with_no_trimmed_paths!(tcx.def_path_str(item)),
1020 padding: tcx
1021 .sess
1022 .source_map()
1023 .indentation_before(struct_start)
1024 .unwrap_or_default(),
1025 struct_start,
1026 },
1027 );
1028 }
1029 }
1030 let field_id = field.did.expect_local();
1031 let span = tcx.ty_span(field_id);
1032 let ty = wfcx.deeply_normalize(
1033 span,
1034 WellFormedLoc::None,
1035 tcx.type_of(field.did).instantiate_identity(),
1036 );
1037 wfcx.register_wf_obligation(span, WellFormedLoc::Ty(field_id), ty.into());
1038
1039 if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Adt(def, _) if def.repr().scalable() => true,
_ => false,
}matches!(ty.kind(), ty::Adt(def, _) if def.repr().scalable())
1040 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1041 {
1042 tcx.dcx().span_err(
1045 span,
1046 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1047 "scalable vectors cannot be fields of a {}",
1048 adt_def.variant_descr()
1049 ),
1050 );
1051 }
1052 }
1053
1054 let needs_drop_copy = || {
1057 packed && {
1058 let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1059 let ty = tcx.erase_and_anonymize_regions(ty);
1060 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1061 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1062 }
1063 };
1064 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1066 let unsized_len = if all_sized { 0 } else { 1 };
1067 for (idx, field) in
1068 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1069 {
1070 let last = idx == variant.fields.len() - 1;
1071 let span = tcx.ty_span(field.did.expect_local());
1072 let ty = wfcx.normalize(
1073 span,
1074 WellFormedLoc::None,
1075 tcx.type_of(field.did).instantiate_identity(),
1076 );
1077 wfcx.register_bound(
1078 traits::ObligationCause::new(
1079 span,
1080 wfcx.body_def_id,
1081 ObligationCauseCode::FieldSized {
1082 adt_kind: adt_def.adt_kind(),
1083 span,
1084 last,
1085 },
1086 ),
1087 wfcx.param_env,
1088 ty,
1089 tcx.require_lang_item(LangItem::Sized, span),
1090 );
1091 }
1092
1093 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1095 match tcx.const_eval_poly(discr_def_id) {
1096 Ok(_) => {}
1097 Err(ErrorHandled::Reported(..)) => {}
1098 Err(ErrorHandled::TooGeneric(sp)) => {
1099 ::rustc_span::macros::bug_impl(Some(sp),
format_args!("enum variant discr was too generic to eval"),
Location::caller())span_bug!(sp, "enum variant discr was too generic to eval")
1100 }
1101 }
1102 }
1103 }
1104
1105 check_where_clauses(wfcx, item);
1106 Ok(())
1107 })
1108}
1109
1110{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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("check_trait",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1110u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
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::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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(&def_id)
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
return Ok(());
}
let trait_def = tcx.trait_def(def_id);
if trait_def.is_marker ||
#[allow(non_exhaustive_omitted_patterns)] match trait_def.specialization_kind
{
TraitSpecializationKind::Marker => true,
_ => false,
} {
for associated_def_id in &*tcx.associated_item_def_ids(def_id)
{
{
tcx.dcx().struct_span_err(tcx.def_span(*associated_def_id),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("marker traits cannot have associated items"))
})).with_code(E0714)
}.with_span_context(tcx.def_span(def_id)).emit();
}
}
let res =
enter_wf_checking_ctxt(tcx, def_id,
|wfcx| { check_where_clauses(wfcx, def_id); Ok(()) });
res
}
}
}#[instrument(skip(tcx))]
1111pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1112 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1113 return Ok(());
1115 }
1116
1117 let trait_def = tcx.trait_def(def_id);
1118 if trait_def.is_marker
1119 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1120 {
1121 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1122 struct_span_code_err!(
1123 tcx.dcx(),
1124 tcx.def_span(*associated_def_id),
1125 E0714,
1126 "marker traits cannot have associated items",
1127 )
1128 .with_span_context(tcx.def_span(def_id))
1129 .emit();
1130 }
1131 }
1132
1133 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1134 check_where_clauses(wfcx, def_id);
1135 Ok(())
1136 });
1137
1138 res
1139}
1140
1141fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1146 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1147
1148 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1148",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1148u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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!("check_associated_type_bounds: bounds={0:?}",
bounds) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_associated_type_bounds: bounds={:?}", bounds);
1149 let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1150 |(bound, bound_span)| {
1151 traits::wf::clause_obligations(
1152 wfcx.infcx,
1153 wfcx.param_env,
1154 wfcx.body_def_id,
1155 bound,
1156 bound_span,
1157 )
1158 },
1159 );
1160
1161 wfcx.register_obligations(wf_obligations);
1162}
1163
1164fn check_item_fn(
1165 tcx: TyCtxt<'_>,
1166 def_id: LocalDefId,
1167 decl: &hir::FnDecl<'_>,
1168) -> Result<(), ErrorGuaranteed> {
1169 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1170 check_eiis_fn(tcx, def_id);
1171
1172 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1173 check_fn_or_method(wfcx, sig, decl, def_id);
1174 Ok(())
1175 })
1176}
1177
1178fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1179 if let Some(EiiImpl { resolution, span, .. }) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
break 'done Some(&**i);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1182 let (foreign_item, name) = match resolution {
1183 EiiImplResolution::Macro(def_id) => {
1184 if let Some(foreign_item) =
1187 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
foreign_item: t, .. })) => {
break 'done Some(*t);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1188 {
1189 (foreign_item, tcx.item_name(*def_id))
1190 } else {
1191 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1192 return;
1193 }
1194 }
1195 EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1196 EiiImplResolution::Error(_eg) => return,
1197 };
1198
1199 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1200 }
1201}
1202
1203fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1204 if let Some(EiiImpl { resolution, span, .. }) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
break 'done Some(&**i);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1207 let (foreign_item, name) = match resolution {
1208 EiiImplResolution::Macro(def_id) => {
1209 if let Some(foreign_item) =
1212 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
foreign_item: t, .. })) => {
break 'done Some(*t);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1213 {
1214 (foreign_item, tcx.item_name(*def_id))
1215 } else {
1216 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1217 return;
1218 }
1219 }
1220 EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1221 EiiImplResolution::Error(_eg) => return,
1222 };
1223
1224 let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1225 }
1226}
1227
1228{}
#[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("check_static_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1228u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_id")
}> =
::tracing::__macro_support::FieldName::new("item_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("should_check_for_sync")
}> =
::tracing::__macro_support::FieldName::new("should_check_for_sync");
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(&item_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&should_check_for_sync
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
enter_wf_checking_ctxt(tcx, item_id,
|wfcx|
{
if should_check_for_sync {
check_eiis_static(tcx, item_id, ty);
}
let span = tcx.ty_span(item_id);
let loc = WellFormedLoc::Ty(item_id);
let item_ty =
wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
let is_foreign_item = tcx.is_foreign_item(item_id);
let is_structurally_foreign_item =
||
{
let tail =
tcx.struct_tail_raw(item_ty, &ObligationCause::dummy(),
|ty| wfcx.deeply_normalize(span, loc, ty), || {});
#[allow(non_exhaustive_omitted_patterns)]
match tail.kind() { ty::Foreign(_) => true, _ => false, }
};
let forbid_unsized =
!(is_foreign_item && is_structurally_foreign_item());
wfcx.register_wf_obligation(span,
WellFormedLoc::Ty(item_id), item_ty.into());
if forbid_unsized {
let span = tcx.def_span(item_id);
wfcx.register_bound(traits::ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::SizedConstOrStatic),
wfcx.param_env, item_ty,
tcx.require_lang_item(LangItem::Sized, span));
}
let should_check_for_sync =
should_check_for_sync && !is_foreign_item &&
tcx.static_mutability(item_id.to_def_id()) ==
Some(hir::Mutability::Not) &&
!tcx.is_thread_local_static(item_id.to_def_id());
if should_check_for_sync {
wfcx.register_bound(traits::ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::SharedStatic),
wfcx.param_env, item_ty,
tcx.require_lang_item(LangItem::Sync, span));
}
Ok(())
})
}
}
}#[instrument(level = "debug", skip(tcx))]
1229pub(crate) fn check_static_item<'tcx>(
1230 tcx: TyCtxt<'tcx>,
1231 item_id: LocalDefId,
1232 ty: Ty<'tcx>,
1233 should_check_for_sync: bool,
1234) -> Result<(), ErrorGuaranteed> {
1235 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1236 if should_check_for_sync {
1237 check_eiis_static(tcx, item_id, ty);
1238 }
1239
1240 let span = tcx.ty_span(item_id);
1241 let loc = WellFormedLoc::Ty(item_id);
1242 let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1243
1244 let is_foreign_item = tcx.is_foreign_item(item_id);
1245 let is_structurally_foreign_item = || {
1246 let tail = tcx.struct_tail_raw(
1247 item_ty,
1248 &ObligationCause::dummy(),
1249 |ty| wfcx.deeply_normalize(span, loc, ty),
1250 || {},
1251 );
1252
1253 matches!(tail.kind(), ty::Foreign(_))
1254 };
1255 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1256
1257 wfcx.register_wf_obligation(span, WellFormedLoc::Ty(item_id), item_ty.into());
1258 if forbid_unsized {
1259 let span = tcx.def_span(item_id);
1260 wfcx.register_bound(
1261 traits::ObligationCause::new(
1262 span,
1263 wfcx.body_def_id,
1264 ObligationCauseCode::SizedConstOrStatic,
1265 ),
1266 wfcx.param_env,
1267 item_ty,
1268 tcx.require_lang_item(LangItem::Sized, span),
1269 );
1270 }
1271
1272 let should_check_for_sync = should_check_for_sync
1274 && !is_foreign_item
1275 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1276 && !tcx.is_thread_local_static(item_id.to_def_id());
1277
1278 if should_check_for_sync {
1279 wfcx.register_bound(
1280 traits::ObligationCause::new(
1281 span,
1282 wfcx.body_def_id,
1283 ObligationCauseCode::SharedStatic,
1284 ),
1285 wfcx.param_env,
1286 item_ty,
1287 tcx.require_lang_item(LangItem::Sync, span),
1288 );
1289 }
1290 Ok(())
1291 })
1292}
1293
1294{}
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("check_const_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1295u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_ty")
}> =
::tracing::__macro_support::FieldName::new("item_ty");
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(&def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
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<(), ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = wfcx.tcx();
let span = tcx.def_span(def_id);
let mut res = Ok(());
if tcx.is_direct_const(def_id.into()) {
if !tcx.features().const_param_ty_unchecked() {
wfcx.register_bound(ObligationCause::new(tcx.ty_span(def_id),
def_id, ObligationCauseCode::ConstItemTy(item_ty)),
wfcx.param_env, item_ty,
tcx.require_lang_item(LangItem::ConstParamTy, span));
}
if !tcx.features().generic_const_parameter_types() &&
item_ty.has_param() {
res =
Err(tcx.dcx().emit_err(ParamInTyOfConstParam {
span,
ty: item_ty,
}));
}
}
if let Some(direct_rhs) = tcx.const_of_item(def_id) {
let raw_ct = direct_rhs.instantiate_identity();
let norm_ct =
wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id),
raw_ct);
wfcx.register_wf_obligation(span, WellFormedLoc::Ty(def_id),
norm_ct.into());
wfcx.register_obligation(Obligation::new(tcx,
ObligationCause::new(span, def_id,
ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id))),
wfcx.param_env,
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct,
item_ty))));
}
check_where_clauses(wfcx, def_id);
res
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1295",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1295u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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(wfcx), ret)]
1296pub(super) fn check_const_item<'tcx>(
1297 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1298 def_id: LocalDefId,
1299 item_ty: Ty<'tcx>,
1300) -> Result<(), ErrorGuaranteed> {
1301 let tcx = wfcx.tcx();
1302 let span = tcx.def_span(def_id);
1303
1304 let mut res = Ok(());
1305
1306 if tcx.is_direct_const(def_id.into()) {
1307 if !tcx.features().const_param_ty_unchecked() {
1308 wfcx.register_bound(
1309 ObligationCause::new(
1310 tcx.ty_span(def_id),
1311 def_id,
1312 ObligationCauseCode::ConstItemTy(item_ty),
1313 ),
1314 wfcx.param_env,
1315 item_ty,
1316 tcx.require_lang_item(LangItem::ConstParamTy, span),
1317 );
1318 }
1319 if !tcx.features().generic_const_parameter_types() && item_ty.has_param() {
1324 res = Err(tcx.dcx().emit_err(ParamInTyOfConstParam { span, ty: item_ty }));
1325 }
1326 }
1327
1328 if let Some(direct_rhs) = tcx.const_of_item(def_id) {
1329 let raw_ct = direct_rhs.instantiate_identity();
1330 let norm_ct = wfcx.deeply_normalize(span, WellFormedLoc::Ty(def_id), raw_ct);
1331 wfcx.register_wf_obligation(span, WellFormedLoc::Ty(def_id), norm_ct.into());
1332
1333 wfcx.register_obligation(Obligation::new(
1334 tcx,
1335 ObligationCause::new(
1336 span,
1337 def_id,
1338 ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id)),
1339 ),
1340 wfcx.param_env,
1341 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1342 ));
1343 }
1344
1345 check_where_clauses(wfcx, def_id);
1346
1347 res
1348}
1349
1350{}
#[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("check_impl",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1350u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
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(&item)
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
enter_wf_checking_ctxt(tcx, item.owner_id.def_id,
|wfcx|
{
match impl_.of_trait {
Some(of_trait) => {
let trait_ref =
tcx.impl_trait_ref(item.owner_id).instantiate_identity();
tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
let trait_span = of_trait.trait_ref.path.span;
let trait_ref =
wfcx.deeply_normalize(trait_span,
WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
trait_ref);
let trait_pred =
ty::TraitClause {
trait_ref,
polarity: ty::ClausePolarity::Positive,
};
let mut obligations =
traits::wf::trait_obligations(wfcx.infcx, wfcx.param_env,
wfcx.body_def_id, trait_pred, trait_span, item);
for obligation in &mut obligations {
if obligation.cause.span != trait_span { continue; }
if let Some(pred) = obligation.predicate.as_trait_clause()
&& pred.skip_binder().self_ty() == trait_ref.self_ty() {
obligation.cause.span = impl_.self_ty.span;
}
if let Some(pred) =
obligation.predicate.as_projection_clause() &&
pred.skip_binder().self_ty() == trait_ref.self_ty() {
obligation.cause.span = impl_.self_ty.span;
}
}
if tcx.is_conditionally_const(item.owner_id.def_id) {
for (bound, _) in
tcx.const_conditions(trait_ref.def_id).instantiate(tcx,
trait_ref.args) {
let bound =
wfcx.normalize(item.span,
WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
bound);
wfcx.register_obligation(Obligation::new(tcx,
ObligationCause::new(impl_.self_ty.span, wfcx.body_def_id,
ObligationCauseCode::WellFormed(WellFormedLoc::HirId(of_trait.trait_ref.hir_ref_id))),
wfcx.param_env,
bound.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe)))
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1421",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1421u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligations")
}> =
::tracing::__macro_support::FieldName::new("obligations");
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(&obligations)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
wfcx.register_obligations(obligations);
}
None => {
let self_ty =
tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
let self_ty =
wfcx.deeply_normalize(item.span,
WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
Unnormalized::new_wip(self_ty));
wfcx.register_wf_obligation(impl_.self_ty.span,
WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
self_ty.into());
}
}
check_where_clauses(wfcx, item.owner_id.def_id);
Ok(())
})
}
}
}#[instrument(level = "debug", skip(tcx, impl_))]
1351fn check_impl<'tcx>(
1352 tcx: TyCtxt<'tcx>,
1353 item: &'tcx hir::Item<'tcx>,
1354 impl_: &hir::Impl<'_>,
1355) -> Result<(), ErrorGuaranteed> {
1356 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1357 match impl_.of_trait {
1358 Some(of_trait) => {
1359 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1360 tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1363 let trait_span = of_trait.trait_ref.path.span;
1364 let trait_ref = wfcx.deeply_normalize(
1365 trait_span,
1366 WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1367 trait_ref,
1368 );
1369 let trait_pred =
1370 ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive };
1371 let mut obligations = traits::wf::trait_obligations(
1372 wfcx.infcx,
1373 wfcx.param_env,
1374 wfcx.body_def_id,
1375 trait_pred,
1376 trait_span,
1377 item,
1378 );
1379 for obligation in &mut obligations {
1380 if obligation.cause.span != trait_span {
1381 continue;
1383 }
1384 if let Some(pred) = obligation.predicate.as_trait_clause()
1385 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1386 {
1387 obligation.cause.span = impl_.self_ty.span;
1388 }
1389 if let Some(pred) = obligation.predicate.as_projection_clause()
1390 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1391 {
1392 obligation.cause.span = impl_.self_ty.span;
1393 }
1394 }
1395
1396 if tcx.is_conditionally_const(item.owner_id.def_id) {
1398 for (bound, _) in
1399 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1400 {
1401 let bound = wfcx.normalize(
1402 item.span,
1403 WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1404 bound,
1405 );
1406 wfcx.register_obligation(Obligation::new(
1407 tcx,
1408 ObligationCause::new(
1409 impl_.self_ty.span,
1410 wfcx.body_def_id,
1411 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(
1412 of_trait.trait_ref.hir_ref_id,
1413 )),
1414 ),
1415 wfcx.param_env,
1416 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1417 ))
1418 }
1419 }
1420
1421 debug!(?obligations);
1422 wfcx.register_obligations(obligations);
1423 }
1424 None => {
1425 let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1426 let self_ty = wfcx.deeply_normalize(
1427 item.span,
1428 WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1429 Unnormalized::new_wip(self_ty),
1430 );
1431 wfcx.register_wf_obligation(
1432 impl_.self_ty.span,
1433 WellFormedLoc::Ty(item.hir_id().expect_owner().def_id),
1434 self_ty.into(),
1435 );
1436 }
1437 }
1438
1439 check_where_clauses(wfcx, item.owner_id.def_id);
1440 Ok(())
1441 })
1442}
1443
1444{}
#[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("check_where_clauses",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1445u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
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(&def_id)
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;
}
{
let infcx = wfcx.infcx;
let tcx = wfcx.tcx();
let gen_clauses = tcx.clauses_of(def_id.to_def_id());
let generics = tcx.generics_of(def_id);
for param in &generics.own_params {
if let Some(default) =
param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
{
if !default.has_param() {
wfcx.register_wf_obligation(tcx.def_span(param.def_id),
(#[allow(non_exhaustive_omitted_patterns)] match param.kind
{
GenericParamDefKind::Type { .. } => true,
_ => false,
}).then(||
WellFormedLoc::Ty(param.def_id.expect_local())).unwrap_or(WellFormedLoc::None),
default.as_term().unwrap());
} else {
let GenericArgKind::Const(ct) =
default.kind() else { continue; };
let ct_ty =
match ct.kind() {
ty::ConstKind::Infer(_) | ty::ConstKind::Placeholder(_) |
ty::ConstKind::Bound(_, _) =>
::core::panicking::unreachable_default_msg(),
ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) =>
continue,
ty::ConstKind::Value(cv) => cv.ty,
ty::ConstKind::Alias(_, alias_const) => {
alias_const.type_of(infcx.tcx).skip_norm_wip()
}
ty::ConstKind::Param(param_ct) => {
param_ct.find_const_ty_from_env(wfcx.param_env)
}
};
let param_ty =
tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
if !ct_ty.has_param() && !param_ty.has_param() {
let cause =
traits::ObligationCause::new(tcx.def_span(param.def_id),
wfcx.body_def_id,
ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id)));
wfcx.register_obligation(Obligation::new(tcx, cause,
wfcx.param_env,
ty::ClauseKind::ConstArgHasType(ct, param_ty)));
}
}
}
}
let args =
GenericArgs::for_item(tcx, def_id.to_def_id(),
|param, _|
{
if param.index >= generics.parent_count as u32 &&
let Some(default) =
param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
&& !default.has_param() {
return default;
}
tcx.mk_param_from_def(param)
});
let default_obligations =
gen_clauses.clauses.iter().flat_map(|&(clause, sp)|
{
struct CountParams {
params: FxHashSet<u32>,
}
#[automatically_derived]
impl ::core::default::Default for CountParams {
#[inline]
fn default() -> Self {
CountParams { params: ::core::default::Default::default() }
}
}
impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
type Result = ControlFlow<()>;
fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
if let ty::Param(param) = t.kind() {
self.params.insert(param.index);
}
t.super_visit_with(self)
}
fn visit_region(&mut self, _: ty::Region<'tcx>)
-> Self::Result {
ControlFlow::Break(())
}
fn visit_const(&mut self, c: ty::Const<'tcx>)
-> Self::Result {
if let ty::ConstKind::Param(param) = c.kind() {
self.params.insert(param.index);
}
c.super_visit_with(self)
}
}
let mut param_count = CountParams::default();
let has_region =
clause.visit_with(&mut param_count).is_break();
let instantiated_clause =
ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
if instantiated_clause.skip_normalization().has_non_region_param()
|| param_count.params.len() > 1 || has_region {
None
} else if gen_clauses.clauses.iter().any(|&(p, _)|
Unnormalized::new_wip(p) == instantiated_clause) {
None
} else { Some((instantiated_clause, sp)) }
}).map(|(clause, sp)|
{
let clause =
wfcx.normalize(sp, WellFormedLoc::None, clause);
let cause =
traits::ObligationCause::new(sp, wfcx.body_def_id,
ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
Obligation::new(tcx, cause, wfcx.param_env, clause)
});
let gen_clauses = gen_clauses.instantiate_identity(tcx);
let assoc_const_obligations: Vec<_> =
gen_clauses.clauses.iter().copied().zip(gen_clauses.spans.iter().copied()).filter_map(|(clause,
sp)|
{
let clause = clause.skip_norm_wip();
let proj = clause.as_projection_clause()?;
let pred_binder =
proj.map_bound(|pred|
{
pred.term.as_const().map(|ct|
{
let assoc_const_ty =
pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
})
}).transpose();
pred_binder.map(|pred_binder|
{
let cause =
traits::ObligationCause::new(sp, wfcx.body_def_id,
ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
})
}).collect();
{
match (&gen_clauses.clauses.len(), &gen_clauses.spans.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
let wf_obligations =
gen_clauses.into_iter().flat_map(|(p, sp)|
{
traits::wf::clause_obligations(infcx, wfcx.param_env,
wfcx.body_def_id, p.skip_norm_wip(), sp)
});
let obligations: Vec<_> =
wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
wfcx.register_obligations(obligations);
}
}
}#[instrument(level = "debug", skip(wfcx))]
1446pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1447 let infcx = wfcx.infcx;
1448 let tcx = wfcx.tcx();
1449
1450 let gen_clauses = tcx.clauses_of(def_id.to_def_id());
1451 let generics = tcx.generics_of(def_id);
1452
1453 for param in &generics.own_params {
1460 if let Some(default) = param
1461 .default_value(tcx)
1462 .map(ty::EarlyBinder::instantiate_identity)
1463 .map(Unnormalized::skip_norm_wip)
1464 {
1465 if !default.has_param() {
1472 wfcx.register_wf_obligation(
1473 tcx.def_span(param.def_id),
1474 matches!(param.kind, GenericParamDefKind::Type { .. })
1475 .then(|| WellFormedLoc::Ty(param.def_id.expect_local()))
1476 .unwrap_or(WellFormedLoc::None),
1477 default.as_term().unwrap(),
1478 );
1479 } else {
1480 let GenericArgKind::Const(ct) = default.kind() else {
1483 continue;
1484 };
1485
1486 let ct_ty = match ct.kind() {
1487 ty::ConstKind::Infer(_)
1488 | ty::ConstKind::Placeholder(_)
1489 | ty::ConstKind::Bound(_, _) => unreachable!(),
1490 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1491 ty::ConstKind::Value(cv) => cv.ty,
1492 ty::ConstKind::Alias(_, alias_const) => {
1493 alias_const.type_of(infcx.tcx).skip_norm_wip()
1494 }
1495 ty::ConstKind::Param(param_ct) => {
1496 param_ct.find_const_ty_from_env(wfcx.param_env)
1497 }
1498 };
1499
1500 let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1501 if !ct_ty.has_param() && !param_ty.has_param() {
1502 let cause = traits::ObligationCause::new(
1503 tcx.def_span(param.def_id),
1504 wfcx.body_def_id,
1505 ObligationCauseCode::WellFormed(WellFormedLoc::Ty(def_id)),
1506 );
1507 wfcx.register_obligation(Obligation::new(
1508 tcx,
1509 cause,
1510 wfcx.param_env,
1511 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1512 ));
1513 }
1514 }
1515 }
1516 }
1517
1518 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1527 if param.index >= generics.parent_count as u32
1528 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1530 && !default.has_param()
1532 {
1533 return default;
1535 }
1536 tcx.mk_param_from_def(param)
1537 });
1538
1539 let default_obligations = gen_clauses
1541 .clauses
1542 .iter()
1543 .flat_map(|&(clause, sp)| {
1544 #[derive(Default)]
1545 struct CountParams {
1546 params: FxHashSet<u32>,
1547 }
1548 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1549 type Result = ControlFlow<()>;
1550 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1551 if let ty::Param(param) = t.kind() {
1552 self.params.insert(param.index);
1553 }
1554 t.super_visit_with(self)
1555 }
1556
1557 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1558 ControlFlow::Break(())
1559 }
1560
1561 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1562 if let ty::ConstKind::Param(param) = c.kind() {
1563 self.params.insert(param.index);
1564 }
1565 c.super_visit_with(self)
1566 }
1567 }
1568 let mut param_count = CountParams::default();
1569 let has_region = clause.visit_with(&mut param_count).is_break();
1570 let instantiated_clause = ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
1571 if instantiated_clause.skip_normalization().has_non_region_param()
1574 || param_count.params.len() > 1
1575 || has_region
1576 {
1577 None
1578 } else if gen_clauses
1579 .clauses
1580 .iter()
1581 .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_clause)
1582 {
1583 None
1585 } else {
1586 Some((instantiated_clause, sp))
1587 }
1588 })
1589 .map(|(clause, sp)| {
1590 let clause = wfcx.normalize(sp, WellFormedLoc::None, clause);
1600 let cause = traits::ObligationCause::new(
1601 sp,
1602 wfcx.body_def_id,
1603 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1604 );
1605 Obligation::new(tcx, cause, wfcx.param_env, clause)
1606 });
1607
1608 let gen_clauses = gen_clauses.instantiate_identity(tcx);
1609
1610 let assoc_const_obligations: Vec<_> = gen_clauses
1611 .clauses
1612 .iter()
1613 .copied()
1614 .zip(gen_clauses.spans.iter().copied())
1615 .filter_map(|(clause, sp)| {
1616 let clause = clause.skip_norm_wip();
1617 let proj = clause.as_projection_clause()?;
1618 let pred_binder = proj
1619 .map_bound(|pred| {
1620 pred.term.as_const().map(|ct| {
1621 let assoc_const_ty =
1622 pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
1623 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1624 })
1625 })
1626 .transpose();
1627 pred_binder.map(|pred_binder| {
1628 let cause = traits::ObligationCause::new(
1629 sp,
1630 wfcx.body_def_id,
1631 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1632 );
1633 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1634 })
1635 })
1636 .collect();
1637
1638 assert_eq!(gen_clauses.clauses.len(), gen_clauses.spans.len());
1639 let wf_obligations = gen_clauses.into_iter().flat_map(|(p, sp)| {
1640 traits::wf::clause_obligations(
1641 infcx,
1642 wfcx.param_env,
1643 wfcx.body_def_id,
1644 p.skip_norm_wip(),
1645 sp,
1646 )
1647 });
1648 let obligations: Vec<_> =
1649 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1650 wfcx.register_obligations(obligations);
1651}
1652
1653{}
#[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("check_fn_or_method",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1653u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sig")
}> =
::tracing::__macro_support::FieldName::new("sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
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(&sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
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;
}
{
let tcx = wfcx.tcx();
let mut sig =
tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
let arg_span =
|idx|
hir_decl.inputs.get(idx).map_or(hir_decl.output.span(),
|arg: &hir::Ty<'_>| arg.span);
sig.inputs_and_output =
tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx,
ty)|
{
wfcx.deeply_normalize(arg_span(idx),
WellFormedLoc::Param { function: def_id, param_idx: idx },
Unnormalized::new_wip(ty))
}));
for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
wfcx.register_wf_obligation(arg_span(idx),
WellFormedLoc::Param { function: def_id, param_idx: idx },
ty.into());
}
check_where_clauses(wfcx, def_id);
if sig.abi() == ExternAbi::RustCall {
let span = tcx.def_span(def_id);
let has_implicit_self =
hir_decl.implicit_self().has_implicit_self();
let mut inputs =
sig.inputs().iter().skip(if has_implicit_self {
1
} else { 0 });
if let Some(ty) = inputs.next() {
wfcx.register_bound(ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::RustCall),
wfcx.param_env, *ty,
tcx.require_lang_item(LangItem::Tuple, span));
wfcx.register_bound(ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::RustCall),
wfcx.param_env, *ty,
tcx.require_lang_item(LangItem::Sized, span));
} else {
tcx.dcx().span_err(hir_decl.inputs.last().map_or(span,
|input| input.span),
"functions with the \"rust-call\" ABI must take a single non-self tuple argument");
}
if inputs.next().is_some() {
tcx.dcx().span_err(hir_decl.inputs.last().map_or(span,
|input| input.span),
"functions with the \"rust-call\" ABI must take a single non-self tuple argument");
}
}
if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
let span =
match hir_decl.output {
hir::FnRetTy::Return(ty) => ty.span,
hir::FnRetTy::DefaultReturn(_) => body.value.span,
};
wfcx.register_bound(ObligationCause::new(span, def_id,
ObligationCauseCode::SizedReturnType), wfcx.param_env,
sig.output(), tcx.require_lang_item(LangItem::Sized, span));
}
}
}
}#[instrument(level = "debug", skip(wfcx, hir_decl))]
1654fn check_fn_or_method<'tcx>(
1655 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1656 sig: ty::PolyFnSig<'tcx>,
1657 hir_decl: &hir::FnDecl<'_>,
1658 def_id: LocalDefId,
1659) {
1660 let tcx = wfcx.tcx();
1661 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1662
1663 let arg_span =
1669 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1670
1671 sig.inputs_and_output =
1672 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1673 wfcx.deeply_normalize(
1674 arg_span(idx),
1675 WellFormedLoc::Param {
1676 function: def_id,
1677 param_idx: idx,
1680 },
1681 Unnormalized::new_wip(ty),
1682 )
1683 }));
1684
1685 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1686 wfcx.register_wf_obligation(
1687 arg_span(idx),
1688 WellFormedLoc::Param { function: def_id, param_idx: idx },
1689 ty.into(),
1690 );
1691 }
1692
1693 check_where_clauses(wfcx, def_id);
1694
1695 if sig.abi() == ExternAbi::RustCall {
1696 let span = tcx.def_span(def_id);
1697 let has_implicit_self = hir_decl.implicit_self().has_implicit_self();
1698 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1699 if let Some(ty) = inputs.next() {
1701 wfcx.register_bound(
1702 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1703 wfcx.param_env,
1704 *ty,
1705 tcx.require_lang_item(LangItem::Tuple, span),
1706 );
1707 wfcx.register_bound(
1708 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1709 wfcx.param_env,
1710 *ty,
1711 tcx.require_lang_item(LangItem::Sized, span),
1712 );
1713 } else {
1714 tcx.dcx().span_err(
1715 hir_decl.inputs.last().map_or(span, |input| input.span),
1716 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1717 );
1718 }
1719 if inputs.next().is_some() {
1721 tcx.dcx().span_err(
1722 hir_decl.inputs.last().map_or(span, |input| input.span),
1723 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1724 );
1725 }
1726 }
1727
1728 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1730 let span = match hir_decl.output {
1731 hir::FnRetTy::Return(ty) => ty.span,
1732 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1733 };
1734
1735 wfcx.register_bound(
1736 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1737 wfcx.param_env,
1738 sig.output(),
1739 tcx.require_lang_item(LangItem::Sized, span),
1740 );
1741 }
1742}
1743
1744#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ArbitrarySelfTypesLevel {
}
#[automatically_derived]impl ::core::clone::Clone for ArbitrarySelfTypesLevel
{
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ArbitrarySelfTypesLevel
{
}Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ArbitrarySelfTypesLevel {
}
#[automatically_derived]impl ::core::cmp::PartialEq for
ArbitrarySelfTypesLevel {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1746enum ArbitrarySelfTypesLevel {
1747 Basic, WithPointers, }
1750
1751{}
#[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("check_method_receiver",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1751u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fn_sig")
}> =
::tracing::__macro_support::FieldName::new("fn_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("method")
}> =
::tracing::__macro_support::FieldName::new("method");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self_ty")
}> =
::tracing::__macro_support::FieldName::new("self_ty");
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(&fn_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = wfcx.tcx();
if !method.is_method() { return Ok(()); }
let span = fn_sig.decl.inputs[0].span;
let loc =
WellFormedLoc::Param {
function: method.def_id.expect_local(),
param_idx: 0,
};
let sig =
tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
let sig =
wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1771",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1771u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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!("check_method_receiver: sig={0:?}",
sig) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let self_ty =
wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
let receiver_ty = sig.inputs()[0];
let receiver_ty =
wfcx.normalize(DUMMY_SP, loc,
Unnormalized::new_wip(receiver_ty));
receiver_ty.error_reported()?;
let arbitrary_self_types_level =
if tcx.features().arbitrary_self_types_pointers() {
Some(ArbitrarySelfTypesLevel::WithPointers)
} else if tcx.features().arbitrary_self_types() {
Some(ArbitrarySelfTypesLevel::Basic)
} else { None };
let generics = tcx.generics_of(method.def_id);
let receiver_validity =
receiver_is_valid(wfcx, span, receiver_ty, self_ty,
arbitrary_self_types_level, generics);
if let Err(receiver_validity_err) = receiver_validity {
return Err(match arbitrary_self_types_level {
None if
receiver_is_valid(wfcx, span, receiver_ty, self_ty,
Some(ArbitrarySelfTypesLevel::Basic), generics).is_ok() => {
feature_err(&tcx.sess, sym::arbitrary_self_types, span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types` feature",
receiver_ty))
})).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit_err()
}
None | Some(ArbitrarySelfTypesLevel::Basic) if
receiver_is_valid(wfcx, span, receiver_ty, self_ty,
Some(ArbitrarySelfTypesLevel::WithPointers),
generics).is_ok() => {
feature_err(&tcx.sess, sym::arbitrary_self_types_pointers,
span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types_pointers` feature",
receiver_ty))
})).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit_err()
}
_ => {
match receiver_validity_err {
ReceiverValidityError::DoesNotDeref if
arbitrary_self_types_level.is_some() => {
let adt_def =
receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def();
let hint =
match adt_def {
Some(adt) => {
if tcx.is_lang_item(adt.did(), LangItem::NonNull) {
Some(InvalidReceiverTyHint::NonNull)
} else {
match tcx.get_diagnostic_name(adt.did()) {
Some(sym::RcWeak | sym::ArcWeak) => {
Some(InvalidReceiverTyHint::Weak)
}
_ => None,
}
}
}
_ => None,
};
tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
span,
receiver_ty,
hint,
})
}
ReceiverValidityError::DoesNotDeref => {
tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
span,
receiver_ty,
})
}
ReceiverValidityError::MethodGenericParamUsed =>
tcx.dcx().emit_err(diagnostics::InvalidGenericReceiverTy {
span,
receiver_ty,
}),
}
}
});
}
Ok(())
}
}
}#[instrument(level = "debug", skip(wfcx))]
1752fn check_method_receiver<'tcx>(
1753 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1754 fn_sig: &hir::FnSig<'_>,
1755 method: ty::AssocItem,
1756 self_ty: Ty<'tcx>,
1757) -> Result<(), ErrorGuaranteed> {
1758 let tcx = wfcx.tcx();
1759
1760 if !method.is_method() {
1761 return Ok(());
1762 }
1763
1764 let span = fn_sig.decl.inputs[0].span;
1765 let loc = WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 };
1766
1767 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1768 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1769 let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1770
1771 debug!("check_method_receiver: sig={:?}", sig);
1772
1773 let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1774
1775 let receiver_ty = sig.inputs()[0];
1776 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1777
1778 receiver_ty.error_reported()?;
1781
1782 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1783 Some(ArbitrarySelfTypesLevel::WithPointers)
1784 } else if tcx.features().arbitrary_self_types() {
1785 Some(ArbitrarySelfTypesLevel::Basic)
1786 } else {
1787 None
1788 };
1789 let generics = tcx.generics_of(method.def_id);
1790
1791 let receiver_validity =
1792 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1793 if let Err(receiver_validity_err) = receiver_validity {
1794 return Err(match arbitrary_self_types_level {
1795 None if receiver_is_valid(
1799 wfcx,
1800 span,
1801 receiver_ty,
1802 self_ty,
1803 Some(ArbitrarySelfTypesLevel::Basic),
1804 generics,
1805 )
1806 .is_ok() =>
1807 {
1808 feature_err(
1810 &tcx.sess,
1811 sym::arbitrary_self_types,
1812 span,
1813 format!(
1814 "`{receiver_ty}` cannot be used as the type of `self` without \
1815 the `arbitrary_self_types` feature",
1816 ),
1817 )
1818 .with_help(msg!("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))
1819 .emit_err()
1820 }
1821 None | Some(ArbitrarySelfTypesLevel::Basic)
1822 if receiver_is_valid(
1823 wfcx,
1824 span,
1825 receiver_ty,
1826 self_ty,
1827 Some(ArbitrarySelfTypesLevel::WithPointers),
1828 generics,
1829 )
1830 .is_ok() =>
1831 {
1832 feature_err(
1834 &tcx.sess,
1835 sym::arbitrary_self_types_pointers,
1836 span,
1837 format!(
1838 "`{receiver_ty}` cannot be used as the type of `self` without \
1839 the `arbitrary_self_types_pointers` feature",
1840 ),
1841 )
1842 .with_help(msg!("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))
1843 .emit_err()
1844 }
1845 _ =>
1846 {
1848 match receiver_validity_err {
1849 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1850 let adt_def =
1851 receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def();
1852
1853 let hint = match adt_def {
1854 Some(adt) => {
1855 if tcx.is_lang_item(adt.did(), LangItem::NonNull) {
1856 Some(InvalidReceiverTyHint::NonNull)
1857 } else {
1858 match tcx.get_diagnostic_name(adt.did()) {
1859 Some(sym::RcWeak | sym::ArcWeak) => {
1860 Some(InvalidReceiverTyHint::Weak)
1861 }
1862 _ => None,
1863 }
1864 }
1865 }
1866 _ => None,
1867 };
1868
1869 tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
1870 span,
1871 receiver_ty,
1872 hint,
1873 })
1874 }
1875 ReceiverValidityError::DoesNotDeref => {
1876 tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
1877 span,
1878 receiver_ty,
1879 })
1880 }
1881 ReceiverValidityError::MethodGenericParamUsed => tcx
1882 .dcx()
1883 .emit_err(diagnostics::InvalidGenericReceiverTy { span, receiver_ty }),
1884 }
1885 }
1886 });
1887 }
1888 Ok(())
1889}
1890
1891enum ReceiverValidityError {
1895 DoesNotDeref,
1898 MethodGenericParamUsed,
1900}
1901
1902fn confirm_type_is_not_a_method_generic_param(
1905 ty: Ty<'_>,
1906 method_generics: &ty::Generics,
1907) -> Result<(), ReceiverValidityError> {
1908 if let ty::Param(param) = ty.kind() {
1909 if (param.index as usize) >= method_generics.parent_count {
1910 return Err(ReceiverValidityError::MethodGenericParamUsed);
1911 }
1912 }
1913 Ok(())
1914}
1915
1916fn receiver_is_valid<'tcx>(
1926 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1927 span: Span,
1928 receiver_ty: Ty<'tcx>,
1929 self_ty: Ty<'tcx>,
1930 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1931 method_generics: &ty::Generics,
1932) -> Result<(), ReceiverValidityError> {
1933 let infcx = wfcx.infcx;
1934 let tcx = wfcx.tcx();
1935 let cause =
1936 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1937
1938 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1940 let ocx = ObligationCtxt::new(wfcx.infcx);
1941 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1942 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
1943 Ok(())
1944 } else {
1945 Err(NoSolution)
1946 }
1947 }) {
1948 return Ok(());
1949 }
1950
1951 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1952
1953 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1954
1955 if arbitrary_self_types_enabled.is_some() {
1959 autoderef = autoderef.use_receiver_trait();
1960 }
1961
1962 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1964 autoderef = autoderef.include_raw_pointers();
1965 }
1966
1967 while let Some((potential_self_ty, _)) = autoderef.next() {
1969 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1969",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1969u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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!("receiver_is_valid: potential self type `{0:?}` to match `{1:?}`",
potential_self_ty, self_ty) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1970 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1971 potential_self_ty, self_ty
1972 );
1973
1974 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1975
1976 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1979 let ocx = ObligationCtxt::new(wfcx.infcx);
1980 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1981 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
1982 Ok(())
1983 } else {
1984 Err(NoSolution)
1985 }
1986 }) {
1987 wfcx.register_obligations(autoderef.into_obligations());
1988 return Ok(());
1989 }
1990
1991 if arbitrary_self_types_enabled.is_none() {
1994 let legacy_receiver_trait_def_id =
1995 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1996 if !legacy_receiver_is_implemented(
1997 wfcx,
1998 legacy_receiver_trait_def_id,
1999 cause.clone(),
2000 potential_self_ty,
2001 ) {
2002 break;
2004 }
2005
2006 wfcx.register_bound(
2008 cause.clone(),
2009 wfcx.param_env,
2010 potential_self_ty,
2011 legacy_receiver_trait_def_id,
2012 );
2013 }
2014 }
2015
2016 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:2016",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2016u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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!("receiver_is_valid: type `{0:?}` does not deref to `{1:?}`",
receiver_ty, self_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
2017 Err(ReceiverValidityError::DoesNotDeref)
2018}
2019
2020fn legacy_receiver_is_implemented<'tcx>(
2021 wfcx: &WfCheckingCtxt<'_, 'tcx>,
2022 legacy_receiver_trait_def_id: DefId,
2023 cause: ObligationCause<'tcx>,
2024 receiver_ty: Ty<'tcx>,
2025) -> bool {
2026 let tcx = wfcx.tcx();
2027 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2028
2029 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2030
2031 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2032 true
2033 } else {
2034 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs:2034",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2034u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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!("receiver_is_implemented: type `{0:?}` does not implement `LegacyReceiver` trait",
receiver_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
2035 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2036 receiver_ty
2037 );
2038 false
2039 }
2040}
2041
2042pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2043 match tcx.def_kind(def_id) {
2044 DefKind::Enum | DefKind::Struct | DefKind::Union => {
2045 }
2047 kind => ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
format_args!("cannot compute the variances of {0:?}", kind),
Location::caller())span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
2048 }
2049
2050 let ty_clauses = tcx.clauses_of(def_id);
2051 {
match (&ty_clauses.parent, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(ty_clauses.parent, None);
2052 let variances = tcx.variances_of(def_id);
2053
2054 let mut constrained_parameters: FxHashSet<_> = variances
2055 .iter()
2056 .enumerate()
2057 .filter(|&(_, &variance)| variance != ty::Bivariant)
2058 .map(|(index, _)| Parameter(index as u32))
2059 .collect();
2060
2061 identify_constrained_generic_params(tcx, ty_clauses, None, &mut constrained_parameters);
2062
2063 let explicitly_bounded_params = LazyCell::new(|| {
2065 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2066 tcx.hir_node_by_def_id(def_id)
2067 .generics()
2068 .unwrap()
2069 .predicates
2070 .iter()
2071 .filter_map(|predicate| match predicate.kind {
2072 hir::WherePredicateKind::BoundPredicate(predicate) => {
2073 match icx.lower_ty(predicate.bounded_ty).kind() {
2074 ty::Param(data) => Some(Parameter(data.index)),
2075 _ => None,
2076 }
2077 }
2078 _ => None,
2079 })
2080 .collect::<FxHashSet<_>>()
2081 });
2082
2083 for (index, _) in variances.iter().enumerate() {
2084 let parameter = Parameter(index as u32);
2085
2086 if constrained_parameters.contains(¶meter) {
2087 continue;
2088 }
2089
2090 let node = tcx.hir_node_by_def_id(def_id);
2091 let item = node.expect_item();
2092 let hir_generics = node.generics().unwrap();
2093 let hir_param = &hir_generics.params[index];
2094
2095 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2096
2097 if ty_param.def_id != hir_param.def_id.into() {
2098 tcx.dcx().span_delayed_bug(
2106 hir_param.span,
2107 "hir generics and ty generics in different order",
2108 );
2109 continue;
2110 }
2111
2112 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2114 .type_of(def_id)
2115 .instantiate_identity()
2116 .skip_norm_wip()
2117 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2118 {
2119 continue;
2120 }
2121
2122 match hir_param.name {
2123 hir::ParamName::Error(_) => {
2124 }
2127 _ => {
2128 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2129 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2130 }
2131 }
2132 }
2133}
2134
2135struct HasErrorDeep<'tcx> {
2137 tcx: TyCtxt<'tcx>,
2138 seen: FxHashSet<DefId>,
2139}
2140impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2141 type Result = ControlFlow<ErrorGuaranteed>;
2142
2143 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2144 match *ty.kind() {
2145 ty::Adt(def, _) => {
2146 if self.seen.insert(def.did()) {
2147 for field in def.all_fields() {
2148 self.tcx
2149 .type_of(field.did)
2150 .instantiate_identity()
2151 .skip_norm_wip()
2152 .visit_with(self)?;
2153 }
2154 }
2155 }
2156 ty::Error(guar) => return ControlFlow::Break(guar),
2157 _ => {}
2158 }
2159 ty.super_visit_with(self)
2160 }
2161
2162 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2163 if let Err(guar) = r.error_reported() {
2164 ControlFlow::Break(guar)
2165 } else {
2166 ControlFlow::Continue(())
2167 }
2168 }
2169
2170 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2171 if let Err(guar) = c.error_reported() {
2172 ControlFlow::Break(guar)
2173 } else {
2174 ControlFlow::Continue(())
2175 }
2176 }
2177}
2178
2179fn report_bivariance<'tcx>(
2180 tcx: TyCtxt<'tcx>,
2181 param: &'tcx hir::GenericParam<'tcx>,
2182 has_explicit_bounds: bool,
2183 item: &'tcx hir::Item<'tcx>,
2184) -> ErrorGuaranteed {
2185 let param_name = param.name.ident();
2186
2187 let help = match item.kind {
2188 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2189 if let Some(def_id) = tcx.lang_items().phantom_data() {
2190 diagnostics::UnusedGenericParameterHelp::Adt {
2191 param_name,
2192 phantom_data: tcx.def_path_str(def_id),
2193 }
2194 } else {
2195 diagnostics::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2196 }
2197 }
2198 item_kind => ::rustc_span::macros::bug_impl(None,
format_args!("report_bivariance: unexpected item kind: {0:?}", item_kind),
Location::caller())bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2199 };
2200
2201 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2202 intravisit::walk_item(
2203 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2204 item,
2205 );
2206
2207 if !usage_spans.is_empty() {
2208 let item_def_id = item.owner_id.to_def_id();
2212 let is_probably_cyclical =
2213 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2214 .visit_def(item_def_id)
2215 .is_break();
2216 if is_probably_cyclical {
2225 return tcx.dcx().emit_err(diagnostics::RecursiveGenericParameter {
2226 spans: usage_spans,
2227 param_span: param.span,
2228 param_name,
2229 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2230 help,
2231 note: (),
2232 });
2233 }
2234 }
2235
2236 let const_param_help =
2237 #[allow(non_exhaustive_omitted_patterns)] match param.kind {
hir::GenericParamKind::Type { .. } if !has_explicit_bounds => true,
_ => false,
}matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2238
2239 let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2240 span: param.span,
2241 param_name,
2242 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2243 usage_spans,
2244 help,
2245 const_param_help,
2246 });
2247 diag.code(E0392);
2248 if item.kind.recovered() {
2249 diag.delay_as_bug()
2251 } else {
2252 diag.emit_err()
2253 }
2254}
2255
2256struct IsProbablyCyclical<'tcx> {
2262 tcx: TyCtxt<'tcx>,
2263 item_def_id: DefId,
2264 seen: FxHashSet<DefId>,
2265}
2266
2267impl<'tcx> IsProbablyCyclical<'tcx> {
2268 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2269 match self.tcx.def_kind(def_id) {
2270 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2271 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2272 self.tcx
2273 .type_of(field.did)
2274 .instantiate_identity()
2275 .skip_norm_wip()
2276 .visit_with(self)
2277 })
2278 }
2279 _ => ControlFlow::Continue(()),
2280 }
2281 }
2282}
2283
2284impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2285 type Result = ControlFlow<(), ()>;
2286
2287 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2288 if let Some(adt_def) = ty.ty_adt_def() {
2289 if adt_def.did() == self.item_def_id {
2290 return ControlFlow::Break(());
2291 }
2292 if self.seen.insert(adt_def.did()) {
2293 self.visit_def(adt_def.did())?;
2294 }
2295 }
2296 ty.super_visit_with(self)
2297 }
2298}
2299
2300struct CollectUsageSpans<'a> {
2305 spans: &'a mut Vec<Span>,
2306 param_def_id: DefId,
2307}
2308
2309impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2310 type Result = ();
2311
2312 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2313 }
2315
2316 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2317 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2318 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2319 && def_id == self.param_def_id
2320 {
2321 self.spans.push(t.span);
2322 return;
2323 } else if let Res::SelfTyAlias { .. } = qpath.res {
2324 self.spans.push(t.span);
2325 return;
2326 }
2327 }
2328 intravisit::walk_ty(self, t);
2329 }
2330}
2331
2332impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2333 {}
#[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("check_false_global_bounds",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2335u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::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();
}
#[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;
}
{
let tcx = self.ocx.infcx.tcx;
let mut span = tcx.def_span(self.body_def_id);
let empty_env = ty::ParamEnv::empty();
let clauses_with_span =
tcx.clauses_of(self.body_def_id).clauses.iter().copied();
let implied_obligations =
traits::elaborate(tcx, clauses_with_span);
for (clause, obligation_span) in implied_obligations {
match clause.kind().skip_binder() {
ty::ClauseKind::WellFormed(..) |
ty::ClauseKind::UnstableFeature(..) => continue,
_ => {}
}
if clause.is_global() &&
!clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
let clause =
self.normalize(span, WellFormedLoc::None,
Unnormalized::new_wip(clause));
let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
if let Some(hir::Generics { predicates, .. }) =
hir_node.generics() {
span =
predicates.iter().find(|pred|
pred.span.contains(obligation_span)).map(|pred|
pred.span).unwrap_or(obligation_span);
}
let obligation =
Obligation::new(tcx,
traits::ObligationCause::new(span, self.body_def_id,
ObligationCauseCode::TrivialBound), empty_env, clause);
self.ocx.register_obligation(obligation);
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2336 fn check_false_global_bounds(&mut self) {
2337 let tcx = self.ocx.infcx.tcx;
2338 let mut span = tcx.def_span(self.body_def_id);
2339 let empty_env = ty::ParamEnv::empty();
2340
2341 let clauses_with_span = tcx.clauses_of(self.body_def_id).clauses.iter().copied();
2342 let implied_obligations = traits::elaborate(tcx, clauses_with_span);
2344
2345 for (clause, obligation_span) in implied_obligations {
2346 match clause.kind().skip_binder() {
2347 ty::ClauseKind::WellFormed(..)
2351 | ty::ClauseKind::UnstableFeature(..) => continue,
2353 _ => {}
2354 }
2355
2356 if clause.is_global() && !clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2358 let clause =
2359 self.normalize(span, WellFormedLoc::None, Unnormalized::new_wip(clause));
2360
2361 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2363 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2364 span = predicates
2365 .iter()
2366 .find(|pred| pred.span.contains(obligation_span))
2368 .map(|pred| pred.span)
2369 .unwrap_or(obligation_span);
2370 }
2371
2372 let obligation = Obligation::new(
2373 tcx,
2374 traits::ObligationCause::new(
2375 span,
2376 self.body_def_id,
2377 ObligationCauseCode::TrivialBound,
2378 ),
2379 empty_env,
2380 clause,
2381 );
2382 self.ocx.register_obligation(obligation);
2383 }
2384 }
2385 }
2386
2387 {}
#[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("check_test_binder_body",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2387u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("body")
}> =
::tracing::__macro_support::FieldName::new("body");
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(&body)
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;
}
{
let TestBinderBody { span, items } = body;
for item in items {
match item {
TestBinderItem::Forall(forall) => {
self.check_test_binder_forall(forall);
}
TestBinderItem::Exists(exist) => {
self.check_test_binder_exists(exist);
}
TestBinderItem::Constraint(constraint) => {
let constraint =
match validate(self.tcx(), &constraint) {
Ok(()) => constraint,
Err(_guar) =>
ty::region_constraint::RegionConstraint::new_true(),
};
if constraint.is_false() {
self.tcx().dcx().span_err(span,
"top level false constraints are not supported");
} else {
self.infcx.register_solver_region_constraint(constraint);
}
}
TestBinderItem::Predicate { clause, span } => {
let cause =
traits::ObligationCause::misc(span, self.body_def_id);
let obligation =
Obligation::new(self.tcx(), cause, self.param_env, clause);
self.register_obligation(obligation);
match self.ocx.evaluate_obligations_error_on_ambiguity() {
TraitErrors::NoErrors => (),
TraitErrors::HasErrors(errors) => {
self.infcx.err_ctxt().report_fulfillment_errors(errors);
return;
}
}
}
TestBinderItem::RegionEquality((equality, span)) => {
let cause =
traits::ObligationCause::misc(span, self.body_def_id);
self.infcx.register_region_eq_constraint(equality,
ty::VisibleForLeakCheck::Yes, &cause);
}
}
}
fn validate<'tcx>(tcx: TyCtxt<'tcx>,
constraint: &SolverRegionConstraint<'tcx>)
-> Result<(), ErrorGuaranteed> {
let mut r = Ok(());
let mut validate_and =
|and: &And<TyCtxt<'_>, _>|
{
for c in and.0.iter() {
match c {
LeafRegionConstraint::Ambiguity(_) |
LeafRegionConstraint::RegionOutlives(..) |
LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (),
LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) =>
{
if let ty::Placeholder(_) | ty::Param(_) = ty.kind()
{} else {
let mut err =
tcx.dcx().struct_span_err(*span,
"the lhs of a ty outlives must be a placeholder");
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("it is a {0}", ty))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and here it is `Debug`ged :3 {0:?}",
ty))
}));
r = Err(err.emit_err());
}
}
}
}
};
validate_and(&constraint.and_constraint);
for and in constraint.or_constraint.0.iter() {
validate_and(and);
}
r
}
}
}
}#[instrument(level = "debug", skip(self))]
2388 pub(super) fn check_test_binder_body(&self, body: TestBinderBody<'tcx>) {
2389 let TestBinderBody { span, items } = body;
2390 for item in items {
2391 match item {
2392 TestBinderItem::Forall(forall) => {
2393 self.check_test_binder_forall(forall);
2394 }
2395 TestBinderItem::Exists(exist) => {
2396 self.check_test_binder_exists(exist);
2397 }
2398 TestBinderItem::Constraint(constraint) => {
2399 let constraint = match validate(self.tcx(), &constraint) {
2400 Ok(()) => constraint,
2401 Err(_guar) => ty::region_constraint::RegionConstraint::new_true(),
2402 };
2403 if constraint.is_false() {
2404 self.tcx()
2405 .dcx()
2406 .span_err(span, "top level false constraints are not supported");
2407 } else {
2408 self.infcx.register_solver_region_constraint(constraint);
2409 }
2410 }
2411 TestBinderItem::Predicate { clause, span } => {
2412 let cause = traits::ObligationCause::misc(span, self.body_def_id);
2413 let obligation = Obligation::new(self.tcx(), cause, self.param_env, clause);
2414 self.register_obligation(obligation);
2415
2416 match self.ocx.evaluate_obligations_error_on_ambiguity() {
2417 TraitErrors::NoErrors => (),
2418 TraitErrors::HasErrors(errors) => {
2419 self.infcx.err_ctxt().report_fulfillment_errors(errors);
2420 return;
2421 }
2422 }
2423 }
2424 TestBinderItem::RegionEquality((equality, span)) => {
2425 let cause = traits::ObligationCause::misc(span, self.body_def_id);
2426 self.infcx.register_region_eq_constraint(
2427 equality,
2428 ty::VisibleForLeakCheck::Yes,
2429 &cause,
2430 );
2431 }
2432 }
2433 }
2434 fn validate<'tcx>(
2435 tcx: TyCtxt<'tcx>,
2436 constraint: &SolverRegionConstraint<'tcx>,
2437 ) -> Result<(), ErrorGuaranteed> {
2438 let mut r = Ok(());
2439
2440 let mut validate_and = |and: &And<TyCtxt<'_>, _>| {
2441 for c in and.0.iter() {
2442 match c {
2443 LeafRegionConstraint::Ambiguity(_)
2444 | LeafRegionConstraint::RegionOutlives(..)
2445 | LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (), LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) => {
2447 if let ty::Placeholder(_) | ty::Param(_) = ty.kind() {
2450 } else {
2452 let mut err = tcx.dcx().struct_span_err(
2453 *span,
2454 "the lhs of a ty outlives must be a placeholder",
2455 );
2456 err.note(format!("it is a {ty}"));
2457 err.note(format!("and here it is `Debug`ged :3 {ty:?}"));
2458 r = Err(err.emit_err());
2459 }
2460 }
2461 }
2462 }
2463 };
2464
2465 validate_and(&constraint.and_constraint);
2466 for and in constraint.or_constraint.0.iter() {
2467 validate_and(and);
2468 }
2469
2470 r
2471 }
2472 }
2473
2474 {}
#[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("check_test_binder_forall",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2474u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("forall")
}> =
::tracing::__macro_support::FieldName::new("forall");
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(&forall)
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;
}
{
let prev_u = self.infcx.universe();
self.infcx.enter_forall(forall.binder,
|body|
{
let u =
if prev_u == self.infcx.universe() {
self.infcx.create_next_universe()
} else { self.infcx.universe() };
let assumptions =
self.build_test_binder_assumptions(forall.span,
body.type_outlives, body.region_outlives);
self.infcx.insert_placeholder_assumptions(u, assumptions);
self.check_test_binder_body(body.value);
let solver_region_constraint =
self.infcx.get_solver_region_constraint();
let constraint =
ty::region_constraint::eagerly_handle_placeholders_in_universe(self.infcx,
solver_region_constraint.without_spans(),
u).with_spans(forall.span);
if constraint.is_false() {
self.tcx().dcx().span_err(forall.span,
"forall evaluated to false");
self.infcx.overwrite_solver_region_constraint(ty::region_constraint::RegionConstraint::new_true());
return;
}
if let Some(assert_on_exit) = &forall.assert_on_exit {
self.check_test_binder_region_constraints(forall.span,
assert_on_exit, &constraint);
}
self.infcx.overwrite_solver_region_constraint(constraint);
});
}
}
}#[instrument(level = "debug", skip(self))]
2475 fn check_test_binder_forall(&self, forall: TestBinderForall<'tcx>) {
2476 let prev_u = self.infcx.universe();
2477 self.infcx.enter_forall(forall.binder, |body| {
2478 let u = if prev_u == self.infcx.universe() {
2479 self.infcx.create_next_universe()
2485 } else {
2486 self.infcx.universe()
2487 };
2488
2489 let assumptions = self.build_test_binder_assumptions(
2490 forall.span,
2491 body.type_outlives,
2492 body.region_outlives,
2493 );
2494 self.infcx.insert_placeholder_assumptions(u, assumptions);
2495 self.check_test_binder_body(body.value);
2496 let solver_region_constraint = self.infcx.get_solver_region_constraint();
2497 let constraint = ty::region_constraint::eagerly_handle_placeholders_in_universe(
2498 self.infcx,
2499 solver_region_constraint.without_spans(),
2500 u,
2501 )
2502 .with_spans(forall.span);
2503 if constraint.is_false() {
2504 self.tcx().dcx().span_err(forall.span, "forall evaluated to false");
2505 self.infcx.overwrite_solver_region_constraint(
2506 ty::region_constraint::RegionConstraint::new_true(),
2507 );
2508 return;
2509 }
2510 if let Some(assert_on_exit) = &forall.assert_on_exit {
2511 self.check_test_binder_region_constraints(forall.span, assert_on_exit, &constraint);
2512 }
2513 self.infcx.overwrite_solver_region_constraint(constraint);
2514 });
2515 }
2516
2517 fn build_test_binder_assumptions(
2518 &self,
2519 span: Span,
2520 type_outlives: Vec<ty::PolyTypeOutlivesClause<'tcx>>,
2521 region_outlives: Vec<ty::RegionOutlivesClause<'tcx>>,
2522 ) -> ty::region_constraint::Assumptions<TyCtxt<'tcx>> {
2523 for clause in &type_outlives {
2524 if !#[allow(non_exhaustive_omitted_patterns)] match clause.skip_binder().0.kind()
{
ty::Alias(..) | ty::Param(..) | ty::Placeholder(..) => true,
_ => false,
}matches!(
2525 clause.skip_binder().0.kind(),
2526 ty::Alias(..) | ty::Param(..) | ty::Placeholder(..)
2527 ) {
2528 let mut err = self.tcx().dcx().struct_span_err(
2529 span,
2530 "the lhs of a forall where clause must be \
2531 an alias, placeholder, or lifetime",
2532 );
2533 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the bad clause is {0}", clause))
})format!("the bad clause is {clause}"));
2534 err.emit();
2535 }
2536 }
2537 let ty = type_outlives.iter().map(|c| c.map_bound(ty::ClauseKind::TypeOutlives));
2538 let reg =
2539 region_outlives.iter().map(|&c| ty::Binder::dummy(ty::ClauseKind::RegionOutlives(c)));
2540 let explicit_clauses: Vec<ty::Clause<'tcx>> =
2541 ty.chain(reg).map(|c| c.upcast(self.tcx())).collect();
2542 for elaborated in ty::elaborate::elaborate(self.tcx(), explicit_clauses.iter().copied()) {
2543 if !explicit_clauses.contains(&elaborated) {
2544 let mut err = self.tcx().dcx().struct_span_err(
2545 span,
2546 "all implied bounds of clauses must themselves be \
2547 included in the where clause of a forall",
2548 );
2549 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing clause is {0}",
elaborated))
})format!("missing clause is {elaborated}"));
2550 err.emit();
2551 }
2552 }
2553
2554 let mut builder = TransitiveRelationBuilder::default();
2555 for &ty::OutlivesClause(r1, r2) in ®ion_outlives {
2556 builder.add(r1, r2);
2557 }
2558 ty::region_constraint::Assumptions::new_unelaborated(type_outlives, builder.freeze())
2561 }
2562
2563 {}
#[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("check_test_binder_region_constraints",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2563u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fallback_span")
}> =
::tracing::__macro_support::FieldName::new("fallback_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("actual")
}> =
::tracing::__macro_support::FieldName::new("actual");
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(&fallback_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&actual)
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;
}
{
let span_of_and =
|c: &And<_, _>|
{
c.0.iter().map(|leaf|
leaf.span()).reduce(|span: Span, acc| acc.to(span))
};
let span_of_or =
|c: &Or<_, _>|
{
c.0.iter().flat_map(|and|
span_of_and(and)).reduce(|span, acc| acc.to(span))
};
let check_leaf_constraint =
|expected: &LeafRegionConstraint<_, _>,
actual: &LeafRegionConstraint<_, _>|
{
if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected,
expected_span) = expected &&
let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual,
actual_span) = actual {
let expected_anon =
self.tcx().anonymize_bound_vars(expected.clone());
let actual_anon =
self.tcx().anonymize_bound_vars(actual.clone());
if expected_anon == actual_anon {
Ok(())
} else { Err((Some(*expected_span), Some(*actual_span))) }
} else {
if expected.clone().without_span() ==
actual.clone().without_span() {
Ok(())
} else { Err((Some(expected.span()), Some(actual.span()))) }
}
};
let check_and_constraint =
|expected: &And<_, _>, actual: &And<_, _>|
{
if expected.0.len() != actual.0.len() {
Err((span_of_and(expected), span_of_and(actual)))
} else {
for (expected, actual) in expected.0.iter().zip(&actual.0) {
check_leaf_constraint(expected, actual)?;
}
Ok(())
}
};
let check_or_constraint =
|expected: &Or<_, _>, actual: &Or<_, _>|
{
if expected.0.len() != actual.0.len() {
Err((span_of_or(expected), span_of_or(actual)))
} else {
for (expected, actual) in expected.0.iter().zip(&actual.0) {
check_and_constraint(expected, actual)?;
}
Ok(())
}
};
let check =
|expected: &SolverRegionConstraint<'tcx>,
actual: &SolverRegionConstraint<'tcx>|
{
check_or_constraint(&expected.or_constraint,
&actual.or_constraint)?;
check_and_constraint(&expected.and_constraint,
&actual.and_constraint)?;
Ok(())
};
if let Err((expected_span, actual_span)) = check(expected, actual)
{
let mut err =
self.tcx().dcx().struct_span_err(expected_span.unwrap_or(fallback_span),
"forall expect clause failed");
if let Some(actual_span) = actual_span {
err.span_note(actual_span, "constraint from here");
}
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected: {0:#?}",
expected))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("actual: {0:#?}", actual))
}));
err.emit();
}
}
}
}#[instrument(level = "debug", skip(self))]
2564 fn check_test_binder_region_constraints(
2565 &self,
2566 fallback_span: Span,
2567 expected: &SolverRegionConstraint<'tcx>,
2568 actual: &SolverRegionConstraint<'tcx>,
2569 ) {
2570 let span_of_and = |c: &And<_, _>| {
2571 c.0.iter().map(|leaf| leaf.span()).reduce(|span: Span, acc| acc.to(span))
2572 };
2573
2574 let span_of_or = |c: &Or<_, _>| {
2575 c.0.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc| acc.to(span))
2576 };
2577
2578 let check_leaf_constraint =
2579 |expected: &LeafRegionConstraint<_, _>, actual: &LeafRegionConstraint<_, _>| {
2580 if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected, expected_span) =
2581 expected
2582 && let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual, actual_span) = actual
2583 {
2584 let expected_anon = self.tcx().anonymize_bound_vars(expected.clone());
2585 let actual_anon = self.tcx().anonymize_bound_vars(actual.clone());
2586 if expected_anon == actual_anon {
2587 Ok(())
2588 } else {
2589 Err((Some(*expected_span), Some(*actual_span)))
2590 }
2591 } else {
2592 if expected.clone().without_span() == actual.clone().without_span() {
2593 Ok(())
2594 } else {
2595 Err((Some(expected.span()), Some(actual.span())))
2596 }
2597 }
2598 };
2599
2600 let check_and_constraint = |expected: &And<_, _>, actual: &And<_, _>| {
2601 if expected.0.len() != actual.0.len() {
2602 Err((span_of_and(expected), span_of_and(actual)))
2603 } else {
2604 for (expected, actual) in expected.0.iter().zip(&actual.0) {
2605 check_leaf_constraint(expected, actual)?;
2606 }
2607 Ok(())
2608 }
2609 };
2610
2611 let check_or_constraint = |expected: &Or<_, _>, actual: &Or<_, _>| {
2612 if expected.0.len() != actual.0.len() {
2613 Err((span_of_or(expected), span_of_or(actual)))
2614 } else {
2615 for (expected, actual) in expected.0.iter().zip(&actual.0) {
2616 check_and_constraint(expected, actual)?;
2617 }
2618 Ok(())
2619 }
2620 };
2621
2622 let check = |expected: &SolverRegionConstraint<'tcx>,
2623 actual: &SolverRegionConstraint<'tcx>| {
2624 check_or_constraint(&expected.or_constraint, &actual.or_constraint)?;
2625 check_and_constraint(&expected.and_constraint, &actual.and_constraint)?;
2626 Ok(())
2627 };
2628
2629 if let Err((expected_span, actual_span)) = check(expected, actual) {
2630 let mut err = self.tcx().dcx().struct_span_err(
2631 expected_span.unwrap_or(fallback_span),
2632 "forall expect clause failed",
2633 );
2634 if let Some(actual_span) = actual_span {
2635 err.span_note(actual_span, "constraint from here");
2636 }
2637 err.note(format!("expected: {expected:#?}"));
2638 err.note(format!("actual: {actual:#?}"));
2639 err.emit();
2640 }
2641 }
2642
2643 {}
#[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("check_test_binder_exists",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/708c94ef093ecc42fb8851e17d8383d999727abc/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2643u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("exists")
}> =
::tracing::__macro_support::FieldName::new("exists");
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(&exists)
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;
}
{
let body =
self.infcx.instantiate_binder_with_fresh_vars(exists.span,
BoundRegionConversionTime::HigherRankedType, exists.binder);
self.check_test_binder_body(body);
}
}
}#[instrument(level = "debug", skip(self))]
2644 fn check_test_binder_exists(&self, exists: TestBinderExists<'tcx>) {
2645 let body = self.infcx.instantiate_binder_with_fresh_vars(
2646 exists.span,
2647 BoundRegionConversionTime::HigherRankedType,
2648 exists.binder,
2649 );
2650 self.check_test_binder_body(body);
2651 }
2652}
2653
2654pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2655 let items = tcx.hir_crate_items(());
2656 let res =
2657 items
2658 .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2659 .and(
2660 items.par_impl_items(|item| {
2661 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2662 }),
2663 )
2664 .and(items.par_trait_items(|item| {
2665 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2666 }))
2667 .and(items.par_foreign_items(|item| {
2668 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2669 }))
2670 .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2671 .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2672
2673 super::entry::check_for_entry_fn(tcx)?;
2674
2675 res
2676}
2677
2678fn lint_redundant_lifetimes<'tcx>(
2679 tcx: TyCtxt<'tcx>,
2680 owner_id: LocalDefId,
2681 outlives_env: &OutlivesEnvironment<'tcx>,
2682) {
2683 let def_kind = tcx.def_kind(owner_id);
2684 match def_kind {
2685 DefKind::Struct
2686 | DefKind::Union
2687 | DefKind::Enum
2688 | DefKind::Trait
2689 | DefKind::TraitAlias
2690 | DefKind::Fn
2691 | DefKind::Const
2692 | DefKind::Impl { of_trait: _ }
2693 | DefKind::TestBinderConstraints => {
2694 }
2696 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2697 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2698 return;
2703 }
2704 }
2705 DefKind::Mod
2706 | DefKind::Variant
2707 | DefKind::TyAlias
2708 | DefKind::ForeignTy
2709 | DefKind::TyParam
2710 | DefKind::ConstParam
2711 | DefKind::Static { .. }
2712 | DefKind::Ctor(_, _)
2713 | DefKind::Macro(_)
2714 | DefKind::ExternCrate
2715 | DefKind::Use
2716 | DefKind::ForeignMod
2717 | DefKind::AnonConst
2718 | DefKind::OpaqueTy
2719 | DefKind::Field
2720 | DefKind::LifetimeParam
2721 | DefKind::GlobalAsm
2722 | DefKind::Closure
2723 | DefKind::SyntheticCoroutineBody => return,
2724 }
2725
2726 let mut lifetimes = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[tcx.lifetimes.re_static]))vec![tcx.lifetimes.re_static];
2735 lifetimes.extend(
2736 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2737 );
2738 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2740 for (idx, var) in tcx
2741 .fn_sig(owner_id)
2742 .instantiate_identity()
2743 .skip_norm_wip()
2744 .bound_vars()
2745 .iter()
2746 .enumerate()
2747 {
2748 let ty::BoundVariableKind::Region(kind) = var else { continue };
2749 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2750 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2751 }
2752 }
2753 lifetimes.retain(|candidate| candidate.is_named(tcx));
2754
2755 let mut shadowed = FxHashSet::default();
2759
2760 for (idx, &candidate) in lifetimes.iter().enumerate() {
2761 if shadowed.contains(&candidate) {
2766 continue;
2767 }
2768
2769 for &victim in &lifetimes[(idx + 1)..] {
2770 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2778 continue;
2779 };
2780
2781 if tcx.parent(def_id) != owner_id.to_def_id() {
2786 continue;
2787 }
2788
2789 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2791 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2792 {
2793 shadowed.insert(victim);
2794 tcx.emit_node_span_lint(
2795 REDUNDANT_LIFETIMES,
2796 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2797 tcx.def_span(def_id),
2798 RedundantLifetimeArgsLint { candidate, victim },
2799 );
2800 }
2801 }
2802 }
2803}
2804
2805#[derive(const _: () =
{
impl<'_sess, 'tcx> rustc_errors::Diagnostic<'_sess> for
RedundantLifetimeArgsLint<'tcx> {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
match self {
RedundantLifetimeArgsLint {
victim: __binding_0, candidate: __binding_1 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unnecessary lifetime parameter `{$victim}`")));
diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")));
;
diag.arg("victim", __binding_0);
diag.arg("candidate", __binding_1);
diag
}
}
}
}
};Diagnostic)]
2806#[diag("unnecessary lifetime parameter `{$victim}`")]
2807#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2808struct RedundantLifetimeArgsLint<'tcx> {
2809 victim: ty::Region<'tcx>,
2811 candidate: ty::Region<'tcx>,
2813}
2814
2815#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TestBinderBody<'tcx> {
#[inline]
fn clone(&self) -> Self {
TestBinderBody {
span: ::core::clone::Clone::clone(&self.span),
items: ::core::clone::Clone::clone(&self.items),
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for TestBinderBody<'tcx>
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TestBinderBody span items", &self.span, &&self.items)
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderBody<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
TestBinderBody { span: __binding_0, items: __binding_1 } =>
{
TestBinderBody {
span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
items: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
TestBinderBody { span: __binding_0, items: __binding_1 } =>
{
TestBinderBody {
span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
items: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderBody<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TestBinderBody {
span: ref __binding_0, items: 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);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
2816pub(crate) struct TestBinderBody<'tcx> {
2817 pub span: Span,
2818 pub items: Vec<TestBinderItem<'tcx>>,
2819}
2820
2821#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TestBinderItem<'tcx> {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Forall(__self_0) =>
TestBinderItem::Forall(::core::clone::Clone::clone(__self_0)),
Self::Exists(__self_0) =>
TestBinderItem::Exists(::core::clone::Clone::clone(__self_0)),
Self::RegionEquality(__self_0) =>
TestBinderItem::RegionEquality(::core::clone::Clone::clone(__self_0)),
Self::Constraint(__self_0) =>
TestBinderItem::Constraint(::core::clone::Clone::clone(__self_0)),
Self::Predicate { clause: __self_0, span: __self_1 } =>
TestBinderItem::Predicate {
clause: ::core::clone::Clone::clone(__self_0),
span: ::core::clone::Clone::clone(__self_1),
},
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for TestBinderItem<'tcx>
{
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Forall(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Forall", &__self_0),
Self::Exists(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Exists", &__self_0),
Self::RegionEquality(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"RegionEquality", &__self_0),
Self::Constraint(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"Constraint", &__self_0),
Self::Predicate { clause: __self_0, span: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Predicate clause span", __self_0, &__self_1),
}
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderItem<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
TestBinderItem::Forall(__binding_0) => {
TestBinderItem::Forall(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
TestBinderItem::Exists(__binding_0) => {
TestBinderItem::Exists(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
TestBinderItem::RegionEquality(__binding_0) => {
TestBinderItem::RegionEquality(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
TestBinderItem::Constraint(__binding_0) => {
TestBinderItem::Constraint(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?)
}
TestBinderItem::Predicate {
clause: __binding_0, span: __binding_1 } => {
TestBinderItem::Predicate {
clause: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
TestBinderItem::Forall(__binding_0) => {
TestBinderItem::Forall(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
TestBinderItem::Exists(__binding_0) => {
TestBinderItem::Exists(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
TestBinderItem::RegionEquality(__binding_0) => {
TestBinderItem::RegionEquality(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
TestBinderItem::Constraint(__binding_0) => {
TestBinderItem::Constraint(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder))
}
TestBinderItem::Predicate {
clause: __binding_0, span: __binding_1 } => {
TestBinderItem::Predicate {
clause: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderItem<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TestBinderItem::Forall(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);
}
}
}
}
TestBinderItem::Exists(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);
}
}
}
}
TestBinderItem::RegionEquality(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);
}
}
}
}
TestBinderItem::Constraint(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);
}
}
}
}
TestBinderItem::Predicate {
clause: ref __binding_0, span: 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);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
2822pub(crate) enum TestBinderItem<'tcx> {
2823 Forall(TestBinderForall<'tcx>),
2824 Exists(TestBinderExists<'tcx>),
2825 RegionEquality((ty::RegionEqPredicate<'tcx>, Span)),
2826 Constraint(SolverRegionConstraint<'tcx>),
2828 Predicate {
2830 clause: ty::Clause<'tcx>,
2831 span: Span,
2832 },
2833}
2834
2835#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TestBinderForall<'tcx> {
#[inline]
fn clone(&self) -> Self {
TestBinderForall {
span: ::core::clone::Clone::clone(&self.span),
binder: ::core::clone::Clone::clone(&self.binder),
assert_on_exit: ::core::clone::Clone::clone(&self.assert_on_exit),
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
TestBinderForall<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TestBinderForall span binder assert_on_exit", &self.span,
&self.binder, &&self.assert_on_exit)
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderForall<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
TestBinderForall {
span: __binding_0,
binder: __binding_1,
assert_on_exit: __binding_2 } => {
TestBinderForall {
span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
assert_on_exit: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
TestBinderForall {
span: __binding_0,
binder: __binding_1,
assert_on_exit: __binding_2 } => {
TestBinderForall {
span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
assert_on_exit: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderForall<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TestBinderForall {
span: ref __binding_0,
binder: ref __binding_1,
assert_on_exit: 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)]
2836pub(crate) struct TestBinderForall<'tcx> {
2837 pub span: Span,
2838 pub binder: ty::Binder<'tcx, WithWhereClauses<'tcx, TestBinderBody<'tcx>>>,
2839 pub assert_on_exit: Option<SolverRegionConstraint<'tcx>>,
2840}
2841
2842#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for
TestBinderExists<'tcx> {
#[inline]
fn clone(&self) -> Self {
TestBinderExists {
span: ::core::clone::Clone::clone(&self.span),
binder: ::core::clone::Clone::clone(&self.binder),
}
}
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for
TestBinderExists<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TestBinderExists span binder", &self.span, &&self.binder)
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderExists<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
TestBinderExists { span: __binding_0, binder: __binding_1 }
=> {
TestBinderExists {
span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
TestBinderExists { span: __binding_0, binder: __binding_1 }
=> {
TestBinderExists {
span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderExists<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TestBinderExists {
span: ref __binding_0, binder: 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);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
2843pub(crate) struct TestBinderExists<'tcx> {
2844 pub span: Span,
2845 pub binder: ty::Binder<'tcx, TestBinderBody<'tcx>>,
2846}
2847
2848#[derive(#[automatically_derived]impl<'tcx, T: ::core::clone::Clone>
::core::clone::Clone for WithWhereClauses<'tcx, T> {
#[inline]
fn clone(&self) -> Self {
WithWhereClauses {
value: ::core::clone::Clone::clone(&self.value),
type_outlives: ::core::clone::Clone::clone(&self.type_outlives),
region_outlives: ::core::clone::Clone::clone(&self.region_outlives),
}
}
}Clone, #[automatically_derived]impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug
for WithWhereClauses<'tcx, T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"WithWhereClauses value type_outlives region_outlives",
&self.value, &self.type_outlives, &&self.region_outlives)
}
}Debug, const _: () =
{
impl<'tcx, T>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for WithWhereClauses<'tcx, T> where
T: ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
{
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
WithWhereClauses {
value: __binding_0,
type_outlives: __binding_1,
region_outlives: __binding_2 } => {
WithWhereClauses {
value: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
type_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
region_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
WithWhereClauses {
value: __binding_0,
type_outlives: __binding_1,
region_outlives: __binding_2 } => {
WithWhereClauses {
value: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
type_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
region_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx, T>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for WithWhereClauses<'tcx, T> where
T: ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
{
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
WithWhereClauses {
value: ref __binding_0,
type_outlives: ref __binding_1,
region_outlives: 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)]
2849pub(crate) struct WithWhereClauses<'tcx, T> {
2850 pub value: T,
2851
2852 pub type_outlives: Vec<ty::PolyTypeOutlivesClause<'tcx>>,
2855 pub region_outlives: Vec<ty::RegionOutlivesClause<'tcx>>,
2856}