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_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
8use rustc_errors::codes::*;
9use rustc_errors::{Applicability, ErrorGuaranteed, msg, pluralize, struct_span_code_err};
10use rustc_hir as hir;
11use rustc_hir::attrs::{EiiDecl, EiiImpl, EiiImplResolution};
12use rustc_hir::def::{DefKind, Res};
13use rustc_hir::def_id::{DefId, LocalDefId};
14use rustc_hir::lang_items::LangItem;
15use rustc_hir::{AmbigArg, ItemKind, find_attr};
16use rustc_infer::infer::outlives::env::OutlivesEnvironment;
17use rustc_infer::infer::{self, InferCtxt, SubregionOrigin, TyCtxtInferExt};
18use rustc_infer::traits::PredicateObligations;
19use rustc_lint_defs::builtin::SHADOWING_SUPERTRAIT_ITEMS;
20use rustc_macros::Diagnostic;
21use rustc_middle::mir::interpret::ErrorHandled;
22use rustc_middle::traits::solve::NoSolution;
23use rustc_middle::ty::trait_def::TraitSpecializationKind;
24use rustc_middle::ty::{
25 self, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags, TypeFoldable,
26 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
27 Upcast,
28};
29use rustc_middle::{bug, span_bug};
30use rustc_session::errors::feature_err;
31use rustc_span::{DUMMY_SP, Span, sym};
32use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
33use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
34use rustc_trait_selection::traits::misc::{
35 ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
36};
37use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
38use rustc_trait_selection::traits::{
39 self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
40 WellFormedLoc,
41};
42use tracing::{debug, instrument};
43
44use super::compare_eii::{compare_eii_function_types, compare_eii_statics};
45use crate::autoderef::Autoderef;
46use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
47use crate::diagnostics;
48use crate::diagnostics::InvalidReceiverTyHint;
49
50pub(super) struct WfCheckingCtxt<'a, 'tcx> {
51 pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
52 body_def_id: LocalDefId,
53 param_env: ty::ParamEnv<'tcx>,
54}
55impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
56 type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
57 fn deref(&self) -> &Self::Target {
58 &self.ocx
59 }
60}
61
62impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
63 fn tcx(&self) -> TyCtxt<'tcx> {
64 self.ocx.infcx.tcx
65 }
66
67 fn normalize<T>(
70 &self,
71 span: Span,
72 loc: Option<WellFormedLoc>,
73 value: Unnormalized<'tcx, T>,
74 ) -> T
75 where
76 T: TypeFoldable<TyCtxt<'tcx>>,
77 {
78 self.ocx.normalize(
79 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
80 self.param_env,
81 value,
82 )
83 }
84
85 pub(super) fn deeply_normalize<T>(
95 &self,
96 span: Span,
97 loc: Option<WellFormedLoc>,
98 value: Unnormalized<'tcx, T>,
99 ) -> T
100 where
101 T: TypeFoldable<TyCtxt<'tcx>>,
102 {
103 if self.infcx.next_trait_solver() {
104 match self.ocx.deeply_normalize(
105 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
106 self.param_env,
107 value.clone(),
108 ) {
109 Ok(value) => value,
110 Err(errors) => {
111 self.infcx.err_ctxt().report_fulfillment_errors(errors);
112 value.skip_norm_wip()
113 }
114 }
115 } else {
116 self.normalize(span, loc, value)
117 }
118 }
119
120 pub(super) fn register_wf_obligation(
121 &self,
122 span: Span,
123 loc: Option<WellFormedLoc>,
124 term: ty::Term<'tcx>,
125 ) {
126 let cause = traits::ObligationCause::new(
127 span,
128 self.body_def_id,
129 ObligationCauseCode::WellFormed(loc),
130 );
131 self.ocx.register_obligation(Obligation::new(
132 self.tcx(),
133 cause,
134 self.param_env,
135 ty::ClauseKind::WellFormed(term),
136 ));
137 }
138
139 pub(super) fn unnormalized_obligations(
140 &self,
141 span: Span,
142 ty: Ty<'tcx>,
143 ) -> Option<PredicateObligations<'tcx>> {
144 traits::wf::unnormalized_obligations(
145 self.ocx.infcx,
146 self.param_env,
147 ty.into(),
148 span,
149 self.body_def_id,
150 )
151 }
152}
153
154pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
155 tcx: TyCtxt<'tcx>,
156 body_def_id: LocalDefId,
157 f: F,
158) -> Result<(), ErrorGuaranteed>
159where
160 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
161{
162 let param_env = tcx.param_env(body_def_id);
163 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
164 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
165
166 let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
167
168 let ignore_bounds =
171 tcx.def_kind(body_def_id) == DefKind::TyAlias && !tcx.type_alias_is_lazy(body_def_id);
172
173 if !ignore_bounds && !tcx.features().trivial_bounds() {
174 wfcx.check_false_global_bounds()
175 }
176 f(&mut wfcx)?;
177
178 let errors = wfcx.evaluate_obligations_error_on_ambiguity();
179 if !errors.is_empty() {
180 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
181 }
182
183 let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
184 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:184",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(184u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["assumed_wf_types"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&assumed_wf_types)
as &dyn Value))])
});
} else { ; }
};debug!(?assumed_wf_types);
185
186 let infcx_compat = infcx.fork();
187
188 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
191 &infcx,
192 body_def_id,
193 param_env,
194 assumed_wf_types.iter().copied(),
195 true,
196 );
197
198 lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
199
200 let errors = infcx.resolve_regions_with_outlives_env(&outlives_env, tcx.def_span(body_def_id));
201 if errors.is_empty() {
202 return Ok(());
203 }
204
205 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
206 &infcx_compat,
207 body_def_id,
208 param_env,
209 assumed_wf_types,
210 false,
213 );
214 let errors_compat =
215 infcx_compat.resolve_regions_with_outlives_env(&outlives_env, tcx.def_span(body_def_id));
216 if errors_compat.is_empty() {
217 Ok(())
220 } else {
221 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
222 }
223}
224
225pub(super) fn check_well_formed(
226 tcx: TyCtxt<'_>,
227 def_id: LocalDefId,
228) -> Result<(), ErrorGuaranteed> {
229 let mut res = crate::check::check::check_item_type(tcx, def_id);
230
231 for param in &tcx.generics_of(def_id).own_params {
232 res = res.and(check_param_wf(tcx, param));
233 }
234
235 res
236}
237
238#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(251u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["item"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), 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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:258",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(258u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["item.owner_id",
"item.name"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&item.owner_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&tcx.def_path_str(def_id))
as &dyn 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());
}
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_middle::util::bug::bug_fmt(format_args!("impl_polarity query disagrees with impl\'s polarity in HIR"));
};
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());
}
}
ty::ImplPolarity::Reservation => {}
}
} else { res = res.and(check_impl(tcx, item, impl_)); }
res
}
hir::ItemKind::Fn { sig, .. } =>
check_item_fn(tcx, def_id, sig.decl),
_ =>
::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("should have been handled by the type based wf check: {0:?}",
item)),
}
}
}
}#[instrument(skip(tcx), level = "debug")]
252pub(super) fn check_item<'tcx>(
253 tcx: TyCtxt<'tcx>,
254 item: &'tcx hir::Item<'tcx>,
255) -> Result<(), ErrorGuaranteed> {
256 let def_id = item.owner_id.def_id;
257
258 debug!(
259 ?item.owner_id,
260 item.name = ? tcx.def_path_str(def_id)
261 );
262
263 match item.kind {
264 hir::ItemKind::Impl(ref impl_) => {
282 crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
283 let mut res = Ok(());
284 if let Some(of_trait) = impl_.of_trait {
285 let header = tcx.impl_trait_header(def_id);
286 let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
287 if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
288 let sp = of_trait.trait_ref.path.span;
289 res = Err(tcx
290 .dcx()
291 .struct_span_err(sp, "impls of auto traits cannot be default")
292 .with_span_labels(of_trait.defaultness_span, "default because of this")
293 .with_span_label(sp, "auto trait")
294 .emit());
295 }
296 match header.polarity {
297 ty::ImplPolarity::Positive => {
298 res = res.and(check_impl(tcx, item, impl_));
299 }
300 ty::ImplPolarity::Negative => {
301 let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
302 bug!("impl_polarity query disagrees with impl's polarity in HIR");
303 };
304 if let hir::Defaultness::Default { .. } = of_trait.defaultness {
306 let mut spans = vec![span];
307 spans.extend(of_trait.defaultness_span);
308 res = Err(struct_span_code_err!(
309 tcx.dcx(),
310 spans,
311 E0750,
312 "negative impls cannot be default impls"
313 )
314 .emit());
315 }
316 }
317 ty::ImplPolarity::Reservation => {
318 }
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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:338",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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(&["item.owner_id",
"item.name"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&item.owner_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&tcx.def_path_str(def_id))
as &dyn 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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:505",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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(&["required_bounds"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&required_bounds)
as &dyn 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::OutlivesPredicate(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::OutlivesPredicate(a, b)) => {
522 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
523 }
524 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected ClauseKind"))bug!("Unexpected ClauseKind"),
525 })
526 .map(|clause| clause.to_string())
527 .collect();
528
529 if !unsatisfied_bounds.is_empty() {
530 let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
531 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!(
532 "{} {}",
533 gat_item_hir.generics.add_where_or_trailing_comma(),
534 unsatisfied_bounds.join(", "),
535 );
536 let bound =
537 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
538 tcx.dcx()
539 .struct_span_err(
540 gat_item_hir.span,
541 ::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),
542 )
543 .with_span_suggestion(
544 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
545 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add the required where clause{0}",
plural))
})format!("add the required where clause{plural}"),
546 suggestion,
547 Applicability::MachineApplicable,
548 )
549 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
bound))
})format!(
550 "{bound} currently required to ensure that impls have maximum flexibility"
551 ))
552 .with_note(
553 "we are soliciting feedback, see issue #87479 \
554 <https://github.com/rust-lang/rust/issues/87479> for more information",
555 )
556 .emit();
557 }
558 }
559}
560
561fn augment_param_env<'tcx>(
563 tcx: TyCtxt<'tcx>,
564 param_env: ty::ParamEnv<'tcx>,
565 new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
566) -> ty::ParamEnv<'tcx> {
567 let Some(new_predicates) = new_predicates else {
568 return param_env;
569 };
570
571 if new_predicates.is_empty() {
572 return param_env;
573 }
574
575 let bounds = tcx.mk_clauses_from_iter(
576 param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
577 );
578 ty::ParamEnv::new(bounds)
581}
582
583fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
594 tcx: TyCtxt<'tcx>,
595 param_env: ty::ParamEnv<'tcx>,
596 item_def_id: LocalDefId,
597 to_check: T,
598 wf_tys: &FxIndexSet<Ty<'tcx>>,
599 gat_def_id: LocalDefId,
600 gat_generics: &'tcx ty::Generics,
601) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
602 let mut bounds = FxIndexSet::default();
604
605 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
606
607 if types.is_empty() && regions.is_empty() {
613 return None;
614 }
615
616 for (region_a, region_a_idx) in ®ions {
617 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
621 continue;
622 }
623 for (ty, ty_idx) in &types {
628 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
630 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:630",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(630u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["ty_idx",
"region_a_idx"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty_idx) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(®ion_a_idx)
as &dyn Value))])
});
} else { ; }
};debug!(?ty_idx, ?region_a_idx);
631 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:631",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(631u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
ty, region_a) as &dyn Value))])
});
} else { ; }
};debug!("required clause: {ty} must outlive {region_a}");
632 let ty_param = gat_generics.param_at(*ty_idx, tcx);
636 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
637 let region_param = gat_generics.param_at(*region_a_idx, tcx);
640 let region_param = ty::Region::new_early_param(
641 tcx,
642 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
643 );
644 bounds.insert(
647 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
648 .upcast(tcx),
649 );
650 }
651 }
652
653 for (region_b, region_b_idx) in ®ions {
658 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 {
662 continue;
663 }
664 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
665 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:665",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(665u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["region_a_idx",
"region_b_idx"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(®ion_a_idx)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(®ion_b_idx)
as &dyn Value))])
});
} else { ; }
};debug!(?region_a_idx, ?region_b_idx);
666 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:666",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(666u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
region_a, region_b) as &dyn Value))])
});
} else { ; }
};debug!("required clause: {region_a} must outlive {region_b}");
667 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
669 let region_a_param = ty::Region::new_early_param(
670 tcx,
671 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
672 );
673 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
675 let region_b_param = ty::Region::new_early_param(
676 tcx,
677 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
678 );
679 bounds.insert(
681 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
682 region_a_param,
683 region_b_param,
684 ))
685 .upcast(tcx),
686 );
687 }
688 }
689 }
690
691 Some(bounds)
692}
693
694fn ty_known_to_outlive<'tcx>(
697 tcx: TyCtxt<'tcx>,
698 id: LocalDefId,
699 param_env: ty::ParamEnv<'tcx>,
700 wf_tys: &FxIndexSet<Ty<'tcx>>,
701 ty: Ty<'tcx>,
702 region: ty::Region<'tcx>,
703) -> bool {
704 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
705 infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
706 sub_region: region,
707 sup_type: ty,
708 origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
709 });
710 })
711}
712
713fn region_known_to_outlive<'tcx>(
716 tcx: TyCtxt<'tcx>,
717 id: LocalDefId,
718 param_env: ty::ParamEnv<'tcx>,
719 wf_tys: &FxIndexSet<Ty<'tcx>>,
720 region_a: ty::Region<'tcx>,
721 region_b: ty::Region<'tcx>,
722) -> bool {
723 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
724 infcx.sub_regions(
725 SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
726 region_b,
727 region_a,
728 ty::VisibleForLeakCheck::Unreachable,
729 );
730 })
731}
732
733fn test_region_obligations<'tcx>(
737 tcx: TyCtxt<'tcx>,
738 id: LocalDefId,
739 param_env: ty::ParamEnv<'tcx>,
740 wf_tys: &FxIndexSet<Ty<'tcx>>,
741 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
742) -> bool {
743 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
747
748 add_constraints(&infcx);
749
750 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
751 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:751",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(751u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["message", "errors"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("errors")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&errors) as
&dyn Value))])
});
} else { ; }
};debug!(?errors, "errors");
752
753 errors.is_empty()
756}
757
758struct GATArgsCollector<'tcx> {
763 gat: DefId,
764 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
766 types: FxIndexSet<(Ty<'tcx>, usize)>,
768}
769
770impl<'tcx> GATArgsCollector<'tcx> {
771 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
772 gat: DefId,
773 t: T,
774 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
775 let mut visitor =
776 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
777 t.visit_with(&mut visitor);
778 (visitor.regions, visitor.types)
779 }
780}
781
782impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
783 fn visit_ty(&mut self, t: Ty<'tcx>) {
784 match t.kind() {
785 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
786 if def_id == self.gat =>
787 {
788 for (idx, arg) in args.iter().enumerate() {
789 match arg.kind() {
790 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
791 self.regions.insert((lt, idx));
792 }
793 GenericArgKind::Type(t) => {
794 self.types.insert((t, idx));
795 }
796 _ => {}
797 }
798 }
799 }
800 _ => {}
801 }
802 t.super_visit_with(self)
803 }
804}
805
806fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
807 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
808 let trait_def_id = tcx.local_parent(trait_item_def_id);
809
810 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
811 .skip(1)
812 .flat_map(|supertrait_def_id| {
813 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
814 })
815 .collect();
816 if !shadowed.is_empty() {
817 let shadowee = if let [shadowed] = shadowed[..] {
818 diagnostics::SupertraitItemShadowee::Labeled {
819 span: tcx.def_span(shadowed.def_id),
820 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
821 }
822 } else {
823 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
824 .iter()
825 .map(|item| {
826 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
827 })
828 .unzip();
829 diagnostics::SupertraitItemShadowee::Several {
830 traits: traits.into(),
831 spans: spans.into(),
832 }
833 };
834
835 tcx.emit_node_span_lint(
836 SHADOWING_SUPERTRAIT_ITEMS,
837 tcx.local_def_id_to_hir_id(trait_item_def_id),
838 tcx.def_span(trait_item_def_id),
839 diagnostics::SupertraitItemShadowing {
840 item: item_name,
841 subtrait: tcx.item_name(trait_def_id.to_def_id()),
842 shadowee,
843 },
844 );
845 }
846}
847
848fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
849 match param.kind {
850 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
852
853 ty::GenericParamDefKind::Const { .. } => {
855 let ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
856 let span = tcx.def_span(param.def_id);
857 let def_id = param.def_id.expect_local();
858
859 if tcx.features().const_param_ty_unchecked() {
860 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
861 wfcx.register_wf_obligation(span, None, ty.into());
862 Ok(())
863 })
864 } else if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
865 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
866 wfcx.register_bound(
867 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
868 wfcx.param_env,
869 ty,
870 tcx.require_lang_item(LangItem::ConstParamTy, span),
871 );
872 Ok(())
873 })
874 } else {
875 let span = || {
876 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
877 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
878 else {
879 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
880 };
881 span
882 };
883 let mut diag = match ty.kind() {
884 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
885 ty::FnPtr(..) => tcx.dcx().struct_span_err(
886 span(),
887 "using function pointers as const generic parameters is forbidden",
888 ),
889 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
890 span(),
891 "using raw pointers as const generic parameters is forbidden",
892 ),
893 _ => {
894 ty.error_reported()?;
896
897 tcx.dcx().struct_span_err(
898 span(),
899 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
900 "`{ty}` is forbidden as the type of a const generic parameter",
901 ),
902 )
903 }
904 };
905
906 diag.note("the only supported types are integers, `bool`, and `char`");
907
908 let cause = ObligationCause::misc(span(), def_id);
909 let adt_const_params_feature_string =
910 " more complex and user defined types".to_string();
911 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
912 tcx,
913 tcx.param_env(param.def_id),
914 ty,
915 cause,
916 ) {
917 Err(
919 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
920 | ConstParamTyImplementationError::NonExhaustive(..)
921 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
922 ) => None,
923 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
924 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![
925 (adt_const_params_feature_string, sym::min_adt_const_params),
926 (
927 " references to implement the `ConstParamTy` trait".into(),
928 sym::unsized_const_params,
929 ),
930 ])
931 }
932 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
935 fn ty_is_local(ty: Ty<'_>) -> bool {
936 match ty.kind() {
937 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
938 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
940 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
943 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
946 _ => false,
947 }
948 }
949
950 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![(
951 adt_const_params_feature_string,
952 sym::min_adt_const_params,
953 )])
954 }
955 Ok(..) => {
957 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)])
958 }
959 };
960 if let Some(features) = may_suggest_feature {
961 tcx.disabled_nightly_features(&mut diag, features);
962 }
963
964 Err(diag.emit())
965 }
966 }
967 }
968}
969
970#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(970u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let loc = Some(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, Some(WellFormedLoc::Ty(def_id)),
ty);
wfcx.register_wf_obligation(span, loc, ty.into());
let has_value = item.defaultness(tcx).has_value();
if tcx.is_type_const(def_id) {
check_type_const(wfcx, def_id, ty, has_value)?;
}
if 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));
}
Ok(())
}
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, Some(WellFormedLoc::Ty(def_id)),
ty);
wfcx.register_wf_obligation(span, loc, ty.into());
}
Ok(())
}
}
})
}
}
}#[instrument(level = "debug", skip(tcx))]
971pub(crate) fn check_associated_item(
972 tcx: TyCtxt<'_>,
973 def_id: LocalDefId,
974) -> Result<(), ErrorGuaranteed> {
975 let loc = Some(WellFormedLoc::Ty(def_id));
976 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
977 let item = tcx.associated_item(def_id);
978
979 tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
982
983 let self_ty = match item.container {
984 ty::AssocContainer::Trait => tcx.types.self_param,
985 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
986 tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
987 }
988 };
989
990 let span = tcx.def_span(def_id);
991
992 match item.kind {
993 ty::AssocKind::Const { .. } => {
994 let ty = tcx.type_of(def_id).instantiate_identity();
995 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
996 wfcx.register_wf_obligation(span, loc, ty.into());
997
998 let has_value = item.defaultness(tcx).has_value();
999 if tcx.is_type_const(def_id) {
1000 check_type_const(wfcx, def_id, ty, has_value)?;
1001 }
1002
1003 if has_value {
1004 let code = ObligationCauseCode::SizedConstOrStatic;
1005 wfcx.register_bound(
1006 ObligationCause::new(span, def_id, code),
1007 wfcx.param_env,
1008 ty,
1009 tcx.require_lang_item(LangItem::Sized, span),
1010 );
1011 }
1012
1013 Ok(())
1014 }
1015 ty::AssocKind::Fn { .. } => {
1016 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1017 let hir_sig =
1018 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
1019 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1020 check_method_receiver(wfcx, hir_sig, item, self_ty)
1021 }
1022 ty::AssocKind::Type { .. } => {
1023 if let ty::AssocContainer::Trait = item.container {
1024 check_associated_type_bounds(wfcx, item, span)
1025 }
1026 if item.defaultness(tcx).has_value() {
1027 let ty = tcx.type_of(def_id).instantiate_identity();
1028 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1029 wfcx.register_wf_obligation(span, loc, ty.into());
1030 }
1031 Ok(())
1032 }
1033 }
1034 })
1035}
1036
1037pub(crate) fn check_type_defn<'tcx>(
1039 tcx: TyCtxt<'tcx>,
1040 item: LocalDefId,
1041 all_sized: bool,
1042) -> Result<(), ErrorGuaranteed> {
1043 tcx.ensure_ok().check_representability(item);
1044 let adt_def = tcx.adt_def(item);
1045
1046 enter_wf_checking_ctxt(tcx, item, |wfcx| {
1047 let variants = adt_def.variants();
1048 let packed = adt_def.repr().packed();
1049
1050 for variant in variants.iter() {
1051 for field in &variant.fields {
1053 if let Some(def_id) = field.value
1054 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1055 {
1056 if let Some(def_id) = def_id.as_local()
1059 && let DefKind::AnonConst = tcx.def_kind(def_id)
1060 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1061 && let expr = &tcx.hir_body(anon.body).value
1062 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1063 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1064 {
1065 } else {
1068 let _ = tcx.const_eval_poly(def_id);
1071 }
1072 }
1073 let field_id = field.did.expect_local();
1074 let span = tcx.ty_span(field_id);
1075 let ty = wfcx.deeply_normalize(
1076 span,
1077 None,
1078 tcx.type_of(field.did).instantiate_identity(),
1079 );
1080 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(field_id)), ty.into());
1081
1082 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())
1083 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1084 {
1085 tcx.dcx().span_err(
1088 span,
1089 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1090 "scalable vectors cannot be fields of a {}",
1091 adt_def.variant_descr()
1092 ),
1093 );
1094 }
1095 }
1096
1097 let needs_drop_copy = || {
1100 packed && {
1101 let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1102 let ty = tcx.erase_and_anonymize_regions(ty);
1103 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1104 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1105 }
1106 };
1107 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1109 let unsized_len = if all_sized { 0 } else { 1 };
1110 for (idx, field) in
1111 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1112 {
1113 let last = idx == variant.fields.len() - 1;
1114 let span = tcx.ty_span(field.did.expect_local());
1115 let ty = wfcx.normalize(span, None, tcx.type_of(field.did).instantiate_identity());
1116 wfcx.register_bound(
1117 traits::ObligationCause::new(
1118 span,
1119 wfcx.body_def_id,
1120 ObligationCauseCode::FieldSized {
1121 adt_kind: adt_def.adt_kind(),
1122 span,
1123 last,
1124 },
1125 ),
1126 wfcx.param_env,
1127 ty,
1128 tcx.require_lang_item(LangItem::Sized, span),
1129 );
1130 }
1131
1132 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1134 match tcx.const_eval_poly(discr_def_id) {
1135 Ok(_) => {}
1136 Err(ErrorHandled::Reported(..)) => {}
1137 Err(ErrorHandled::TooGeneric(sp)) => {
1138 ::rustc_middle::util::bug::span_bug_fmt(sp,
format_args!("enum variant discr was too generic to eval"))span_bug!(sp, "enum variant discr was too generic to eval")
1139 }
1140 }
1141 }
1142 }
1143
1144 check_where_clauses(wfcx, item);
1145 Ok(())
1146 })
1147}
1148
1149#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1149u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["def_id"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), 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)
}.emit();
}
}
let res =
enter_wf_checking_ctxt(tcx, def_id,
|wfcx| { check_where_clauses(wfcx, def_id); Ok(()) });
res
}
}
}#[instrument(skip(tcx))]
1150pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1151 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1152 return Ok(());
1154 }
1155
1156 let trait_def = tcx.trait_def(def_id);
1157 if trait_def.is_marker
1158 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1159 {
1160 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1161 struct_span_code_err!(
1162 tcx.dcx(),
1163 tcx.def_span(*associated_def_id),
1164 E0714,
1165 "marker traits cannot have associated items",
1166 )
1167 .emit();
1168 }
1169 }
1170
1171 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1172 check_where_clauses(wfcx, def_id);
1173 Ok(())
1174 });
1175
1176 res
1177}
1178
1179fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1184 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1185
1186 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1186",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1186u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_associated_type_bounds: bounds={0:?}",
bounds) as &dyn Value))])
});
} else { ; }
};debug!("check_associated_type_bounds: bounds={:?}", bounds);
1187 let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1188 |(bound, bound_span)| {
1189 traits::wf::clause_obligations(
1190 wfcx.infcx,
1191 wfcx.param_env,
1192 wfcx.body_def_id,
1193 bound,
1194 bound_span,
1195 )
1196 },
1197 );
1198
1199 wfcx.register_obligations(wf_obligations);
1200}
1201
1202fn check_item_fn(
1203 tcx: TyCtxt<'_>,
1204 def_id: LocalDefId,
1205 decl: &hir::FnDecl<'_>,
1206) -> Result<(), ErrorGuaranteed> {
1207 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1208 check_eiis_fn(tcx, def_id);
1209
1210 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1211 check_fn_or_method(wfcx, sig, decl, def_id);
1212 Ok(())
1213 })
1214}
1215
1216fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1217 for EiiImpl { resolution, span, .. } in
1220 {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
break 'done Some(impls);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten()
1221 {
1222 let (foreign_item, name) = match resolution {
1223 EiiImplResolution::Macro(def_id) => {
1224 if let Some(foreign_item) =
1227 {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(*def_id, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(EiiDeclaration(EiiDecl {
foreign_item: t, .. })) => {
break 'done Some(*t);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1228 {
1229 (foreign_item, tcx.item_name(*def_id))
1230 } else {
1231 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1232 continue;
1233 }
1234 }
1235 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1236 EiiImplResolution::Error(_eg) => continue,
1237 };
1238
1239 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1240 }
1241}
1242
1243fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1244 for EiiImpl { resolution, span, .. } in
1247 {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(EiiImpls(impls)) => {
break 'done Some(impls);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiImpls(impls) => impls).into_iter().flatten()
1248 {
1249 let (foreign_item, name) = match resolution {
1250 EiiImplResolution::Macro(def_id) => {
1251 if let Some(foreign_item) =
1254 {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(*def_id, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(EiiDeclaration(EiiDecl {
foreign_item: t, .. })) => {
break 'done Some(*t);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1255 {
1256 (foreign_item, tcx.item_name(*def_id))
1257 } else {
1258 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1259 continue;
1260 }
1261 }
1262 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1263 EiiImplResolution::Error(_eg) => continue,
1264 };
1265
1266 let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1267 }
1268}
1269
1270#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1270u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["item_id", "ty",
"should_check_for_sync"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&should_check_for_sync
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), 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 = Some(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,
Some(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))]
1271pub(crate) fn check_static_item<'tcx>(
1272 tcx: TyCtxt<'tcx>,
1273 item_id: LocalDefId,
1274 ty: Ty<'tcx>,
1275 should_check_for_sync: bool,
1276) -> Result<(), ErrorGuaranteed> {
1277 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1278 if should_check_for_sync {
1279 check_eiis_static(tcx, item_id, ty);
1280 }
1281
1282 let span = tcx.ty_span(item_id);
1283 let loc = Some(WellFormedLoc::Ty(item_id));
1284 let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1285
1286 let is_foreign_item = tcx.is_foreign_item(item_id);
1287 let is_structurally_foreign_item = || {
1288 let tail = tcx.struct_tail_raw(
1289 item_ty,
1290 &ObligationCause::dummy(),
1291 |ty| wfcx.deeply_normalize(span, loc, ty),
1292 || {},
1293 );
1294
1295 matches!(tail.kind(), ty::Foreign(_))
1296 };
1297 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1298
1299 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1300 if forbid_unsized {
1301 let span = tcx.def_span(item_id);
1302 wfcx.register_bound(
1303 traits::ObligationCause::new(
1304 span,
1305 wfcx.body_def_id,
1306 ObligationCauseCode::SizedConstOrStatic,
1307 ),
1308 wfcx.param_env,
1309 item_ty,
1310 tcx.require_lang_item(LangItem::Sized, span),
1311 );
1312 }
1313
1314 let should_check_for_sync = should_check_for_sync
1316 && !is_foreign_item
1317 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1318 && !tcx.is_thread_local_static(item_id.to_def_id());
1319
1320 if should_check_for_sync {
1321 wfcx.register_bound(
1322 traits::ObligationCause::new(
1323 span,
1324 wfcx.body_def_id,
1325 ObligationCauseCode::SharedStatic,
1326 ),
1327 wfcx.param_env,
1328 item_ty,
1329 tcx.require_lang_item(LangItem::Sync, span),
1330 );
1331 }
1332 Ok(())
1333 })
1334}
1335
1336#[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_type_const",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1336u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["def_id", "item_ty",
"has_value"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&has_value as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = wfcx.tcx();
let span = tcx.def_span(def_id);
if !tcx.features().const_param_ty_unchecked() {
wfcx.register_bound(ObligationCause::new(span, def_id,
ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
item_ty,
tcx.require_lang_item(LangItem::ConstParamTy, span));
}
if has_value {
let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
let norm_ct =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
raw_ct);
wfcx.register_wf_obligation(span,
Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
wfcx.register_obligation(Obligation::new(tcx,
ObligationCause::new(span, def_id,
ObligationCauseCode::WellFormed(None)), wfcx.param_env,
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct,
item_ty))));
}
Ok(())
}
}
}#[instrument(level = "debug", skip(wfcx))]
1337pub(super) fn check_type_const<'tcx>(
1338 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1339 def_id: LocalDefId,
1340 item_ty: Ty<'tcx>,
1341 has_value: bool,
1342) -> Result<(), ErrorGuaranteed> {
1343 let tcx = wfcx.tcx();
1344 let span = tcx.def_span(def_id);
1345
1346 if !tcx.features().const_param_ty_unchecked() {
1347 wfcx.register_bound(
1348 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1349 wfcx.param_env,
1350 item_ty,
1351 tcx.require_lang_item(LangItem::ConstParamTy, span),
1352 );
1353 }
1354
1355 if has_value {
1356 let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1357 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1358 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1359
1360 wfcx.register_obligation(Obligation::new(
1361 tcx,
1362 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1363 wfcx.param_env,
1364 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1365 ));
1366 }
1367 Ok(())
1368}
1369
1370#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1370u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["item"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), 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,
Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
trait_ref);
let trait_pred =
ty::TraitPredicate {
trait_ref,
polarity: ty::PredicatePolarity::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,
Some(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(None)), 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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:1442",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1442u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["obligations"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&obligations)
as &dyn 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,
Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
Unnormalized::new_wip(self_ty));
wfcx.register_wf_obligation(impl_.self_ty.span,
Some(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_))]
1371fn check_impl<'tcx>(
1372 tcx: TyCtxt<'tcx>,
1373 item: &'tcx hir::Item<'tcx>,
1374 impl_: &hir::Impl<'_>,
1375) -> Result<(), ErrorGuaranteed> {
1376 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1377 match impl_.of_trait {
1378 Some(of_trait) => {
1379 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1383 tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1386 let trait_span = of_trait.trait_ref.path.span;
1387 let trait_ref = wfcx.deeply_normalize(
1388 trait_span,
1389 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1390 trait_ref,
1391 );
1392 let trait_pred =
1393 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1394 let mut obligations = traits::wf::trait_obligations(
1395 wfcx.infcx,
1396 wfcx.param_env,
1397 wfcx.body_def_id,
1398 trait_pred,
1399 trait_span,
1400 item,
1401 );
1402 for obligation in &mut obligations {
1403 if obligation.cause.span != trait_span {
1404 continue;
1406 }
1407 if let Some(pred) = obligation.predicate.as_trait_clause()
1408 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1409 {
1410 obligation.cause.span = impl_.self_ty.span;
1411 }
1412 if let Some(pred) = obligation.predicate.as_projection_clause()
1413 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1414 {
1415 obligation.cause.span = impl_.self_ty.span;
1416 }
1417 }
1418
1419 if tcx.is_conditionally_const(item.owner_id.def_id) {
1421 for (bound, _) in
1422 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1423 {
1424 let bound = wfcx.normalize(
1425 item.span,
1426 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1427 bound,
1428 );
1429 wfcx.register_obligation(Obligation::new(
1430 tcx,
1431 ObligationCause::new(
1432 impl_.self_ty.span,
1433 wfcx.body_def_id,
1434 ObligationCauseCode::WellFormed(None),
1435 ),
1436 wfcx.param_env,
1437 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1438 ))
1439 }
1440 }
1441
1442 debug!(?obligations);
1443 wfcx.register_obligations(obligations);
1444 }
1445 None => {
1446 let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1447 let self_ty = wfcx.deeply_normalize(
1448 item.span,
1449 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1450 Unnormalized::new_wip(self_ty),
1451 );
1452 wfcx.register_wf_obligation(
1453 impl_.self_ty.span,
1454 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1455 self_ty.into(),
1456 );
1457 }
1458 }
1459
1460 check_where_clauses(wfcx, item.owner_id.def_id);
1461 Ok(())
1462 })
1463}
1464
1465#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1466u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let infcx = wfcx.infcx;
let tcx = wfcx.tcx();
let predicates = tcx.predicates_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())),
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::panic("internal error: entered unreachable code"),
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(None));
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 =
predicates.predicates.iter().flat_map(|&(pred, sp)|
{
struct CountParams {
params: FxHashSet<u32>,
}
#[automatically_derived]
impl ::core::default::Default for CountParams {
#[inline]
fn default() -> CountParams {
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 =
pred.visit_with(&mut param_count).is_break();
let instantiated_pred =
ty::EarlyBinder::bind(tcx, pred).instantiate(tcx, args);
if instantiated_pred.skip_normalization().has_non_region_param()
|| param_count.params.len() > 1 || has_region {
None
} else if predicates.predicates.iter().any(|&(p, _)|
Unnormalized::new_wip(p) == instantiated_pred) {
None
} else { Some((instantiated_pred, sp)) }
}).map(|(pred, sp)|
{
let pred = wfcx.normalize(sp, None, pred);
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)
});
let predicates = predicates.instantiate_identity(tcx);
let assoc_const_obligations: Vec<_> =
predicates.predicates.iter().copied().zip(predicates.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 (&predicates.predicates.len(), &predicates.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 =
predicates.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))]
1467pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1468 let infcx = wfcx.infcx;
1469 let tcx = wfcx.tcx();
1470
1471 let predicates = tcx.predicates_of(def_id.to_def_id());
1472 let generics = tcx.generics_of(def_id);
1473
1474 for param in &generics.own_params {
1481 if let Some(default) = param
1482 .default_value(tcx)
1483 .map(ty::EarlyBinder::instantiate_identity)
1484 .map(Unnormalized::skip_norm_wip)
1485 {
1486 if !default.has_param() {
1493 wfcx.register_wf_obligation(
1494 tcx.def_span(param.def_id),
1495 matches!(param.kind, GenericParamDefKind::Type { .. })
1496 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1497 default.as_term().unwrap(),
1498 );
1499 } else {
1500 let GenericArgKind::Const(ct) = default.kind() else {
1503 continue;
1504 };
1505
1506 let ct_ty = match ct.kind() {
1507 ty::ConstKind::Infer(_)
1508 | ty::ConstKind::Placeholder(_)
1509 | ty::ConstKind::Bound(_, _) => unreachable!(),
1510 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1511 ty::ConstKind::Value(cv) => cv.ty,
1512 ty::ConstKind::Alias(_, alias_const) => {
1513 alias_const.type_of(infcx.tcx).skip_norm_wip()
1514 }
1515 ty::ConstKind::Param(param_ct) => {
1516 param_ct.find_const_ty_from_env(wfcx.param_env)
1517 }
1518 };
1519
1520 let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1521 if !ct_ty.has_param() && !param_ty.has_param() {
1522 let cause = traits::ObligationCause::new(
1523 tcx.def_span(param.def_id),
1524 wfcx.body_def_id,
1525 ObligationCauseCode::WellFormed(None),
1526 );
1527 wfcx.register_obligation(Obligation::new(
1528 tcx,
1529 cause,
1530 wfcx.param_env,
1531 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1532 ));
1533 }
1534 }
1535 }
1536 }
1537
1538 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1547 if param.index >= generics.parent_count as u32
1548 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1550 && !default.has_param()
1552 {
1553 return default;
1555 }
1556 tcx.mk_param_from_def(param)
1557 });
1558
1559 let default_obligations = predicates
1561 .predicates
1562 .iter()
1563 .flat_map(|&(pred, sp)| {
1564 #[derive(Default)]
1565 struct CountParams {
1566 params: FxHashSet<u32>,
1567 }
1568 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1569 type Result = ControlFlow<()>;
1570 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1571 if let ty::Param(param) = t.kind() {
1572 self.params.insert(param.index);
1573 }
1574 t.super_visit_with(self)
1575 }
1576
1577 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1578 ControlFlow::Break(())
1579 }
1580
1581 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1582 if let ty::ConstKind::Param(param) = c.kind() {
1583 self.params.insert(param.index);
1584 }
1585 c.super_visit_with(self)
1586 }
1587 }
1588 let mut param_count = CountParams::default();
1589 let has_region = pred.visit_with(&mut param_count).is_break();
1590 let instantiated_pred = ty::EarlyBinder::bind(tcx, pred).instantiate(tcx, args);
1591 if instantiated_pred.skip_normalization().has_non_region_param()
1594 || param_count.params.len() > 1
1595 || has_region
1596 {
1597 None
1598 } else if predicates
1599 .predicates
1600 .iter()
1601 .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_pred)
1602 {
1603 None
1605 } else {
1606 Some((instantiated_pred, sp))
1607 }
1608 })
1609 .map(|(pred, sp)| {
1610 let pred = wfcx.normalize(sp, None, pred);
1620 let cause = traits::ObligationCause::new(
1621 sp,
1622 wfcx.body_def_id,
1623 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1624 );
1625 Obligation::new(tcx, cause, wfcx.param_env, pred)
1626 });
1627
1628 let predicates = predicates.instantiate_identity(tcx);
1629
1630 let assoc_const_obligations: Vec<_> = predicates
1631 .predicates
1632 .iter()
1633 .copied()
1634 .zip(predicates.spans.iter().copied())
1635 .filter_map(|(clause, sp)| {
1636 let clause = clause.skip_norm_wip();
1637 let proj = clause.as_projection_clause()?;
1638 let pred_binder = proj
1639 .map_bound(|pred| {
1640 pred.term.as_const().map(|ct| {
1641 let assoc_const_ty =
1642 pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
1643 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1644 })
1645 })
1646 .transpose();
1647 pred_binder.map(|pred_binder| {
1648 let cause = traits::ObligationCause::new(
1649 sp,
1650 wfcx.body_def_id,
1651 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1652 );
1653 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1654 })
1655 })
1656 .collect();
1657
1658 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1659 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1660 traits::wf::clause_obligations(
1661 infcx,
1662 wfcx.param_env,
1663 wfcx.body_def_id,
1664 p.skip_norm_wip(),
1665 sp,
1666 )
1667 });
1668 let obligations: Vec<_> =
1669 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1670 wfcx.register_obligations(obligations);
1671}
1672
1673#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1673u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["sig", "def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
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),
Some(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),
Some(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(mut splatted_arg_index) = sig.splatted() {
let mut inputs_count = sig.inputs().len();
if has_implicit_self {
splatted_arg_index = splatted_arg_index.strict_sub(1);
inputs_count = inputs_count.strict_sub(1);
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1726",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1726u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["splatted_arg_index",
"inputs_count", "has_implicit_self", "sig"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&splatted_arg_index)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&inputs_count)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&has_implicit_self)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&sig) as
&dyn Value))])
});
} else { ; }
};
sig =
sig.set_splatted(Some(splatted_arg_index),
inputs_count).unwrap();
}
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(hir::LangItem::Tuple, span));
wfcx.register_bound(ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::RustCall),
wfcx.param_env, *ty,
tcx.require_lang_item(hir::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))]
1674fn check_fn_or_method<'tcx>(
1675 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1676 sig: ty::PolyFnSig<'tcx>,
1677 hir_decl: &hir::FnDecl<'_>,
1678 def_id: LocalDefId,
1679) {
1680 let tcx = wfcx.tcx();
1681 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1682
1683 let arg_span =
1689 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1690
1691 sig.inputs_and_output =
1692 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1693 wfcx.deeply_normalize(
1694 arg_span(idx),
1695 Some(WellFormedLoc::Param {
1696 function: def_id,
1697 param_idx: idx,
1700 }),
1701 Unnormalized::new_wip(ty),
1702 )
1703 }));
1704
1705 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1706 wfcx.register_wf_obligation(
1707 arg_span(idx),
1708 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1709 ty.into(),
1710 );
1711 }
1712
1713 check_where_clauses(wfcx, def_id);
1714
1715 if sig.abi() == ExternAbi::RustCall {
1716 let span = tcx.def_span(def_id);
1717 let has_implicit_self = hir_decl.implicit_self().has_implicit_self();
1718 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1719 if let Some(mut splatted_arg_index) = sig.splatted() {
1721 let mut inputs_count = sig.inputs().len();
1722 if has_implicit_self {
1723 splatted_arg_index = splatted_arg_index.strict_sub(1);
1724 inputs_count = inputs_count.strict_sub(1);
1725 }
1726 debug!(?splatted_arg_index, ?inputs_count, ?has_implicit_self, ?sig);
1727 sig = sig.set_splatted(Some(splatted_arg_index), inputs_count).unwrap();
1728 }
1729 if let Some(ty) = inputs.next() {
1731 wfcx.register_bound(
1732 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1733 wfcx.param_env,
1734 *ty,
1735 tcx.require_lang_item(hir::LangItem::Tuple, span),
1736 );
1737 wfcx.register_bound(
1738 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1739 wfcx.param_env,
1740 *ty,
1741 tcx.require_lang_item(hir::LangItem::Sized, span),
1742 );
1743 } else {
1744 tcx.dcx().span_err(
1745 hir_decl.inputs.last().map_or(span, |input| input.span),
1746 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1747 );
1748 }
1749 if inputs.next().is_some() {
1751 tcx.dcx().span_err(
1752 hir_decl.inputs.last().map_or(span, |input| input.span),
1753 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1754 );
1755 }
1756 }
1757
1758 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1760 let span = match hir_decl.output {
1761 hir::FnRetTy::Return(ty) => ty.span,
1762 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1763 };
1764
1765 wfcx.register_bound(
1766 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1767 wfcx.param_env,
1768 sig.output(),
1769 tcx.require_lang_item(LangItem::Sized, span),
1770 );
1771 }
1772}
1773
1774#[derive(#[automatically_derived]
impl ::core::clone::Clone for ArbitrarySelfTypesLevel {
#[inline]
fn clone(&self) -> ArbitrarySelfTypesLevel { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ArbitrarySelfTypesLevel { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for ArbitrarySelfTypesLevel {
#[inline]
fn eq(&self, other: &ArbitrarySelfTypesLevel) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1776enum ArbitrarySelfTypesLevel {
1777 Basic, WithPointers, }
1780
1781#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1781u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["fn_sig", "method",
"self_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), 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 =
Some(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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:1801",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1801u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("check_method_receiver: sig={0:?}",
sig) as &dyn 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()
}
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()
}
_ => {
match receiver_validity_err {
ReceiverValidityError::DoesNotDeref if
arbitrary_self_types_level.is_some() => {
let hint =
match receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def().and_then(|adt_def|
tcx.get_diagnostic_name(adt_def.did())) {
Some(sym::RcWeak | sym::ArcWeak) =>
Some(InvalidReceiverTyHint::Weak),
Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
_ => 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))]
1782fn check_method_receiver<'tcx>(
1783 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1784 fn_sig: &hir::FnSig<'_>,
1785 method: ty::AssocItem,
1786 self_ty: Ty<'tcx>,
1787) -> Result<(), ErrorGuaranteed> {
1788 let tcx = wfcx.tcx();
1789
1790 if !method.is_method() {
1791 return Ok(());
1792 }
1793
1794 let span = fn_sig.decl.inputs[0].span;
1795 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1796
1797 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1798 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1799 let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1800
1801 debug!("check_method_receiver: sig={:?}", sig);
1802
1803 let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1804
1805 let receiver_ty = sig.inputs()[0];
1806 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1807
1808 receiver_ty.error_reported()?;
1811
1812 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1813 Some(ArbitrarySelfTypesLevel::WithPointers)
1814 } else if tcx.features().arbitrary_self_types() {
1815 Some(ArbitrarySelfTypesLevel::Basic)
1816 } else {
1817 None
1818 };
1819 let generics = tcx.generics_of(method.def_id);
1820
1821 let receiver_validity =
1822 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1823 if let Err(receiver_validity_err) = receiver_validity {
1824 return Err(match arbitrary_self_types_level {
1825 None if receiver_is_valid(
1829 wfcx,
1830 span,
1831 receiver_ty,
1832 self_ty,
1833 Some(ArbitrarySelfTypesLevel::Basic),
1834 generics,
1835 )
1836 .is_ok() =>
1837 {
1838 feature_err(
1840 &tcx.sess,
1841 sym::arbitrary_self_types,
1842 span,
1843 format!(
1844 "`{receiver_ty}` cannot be used as the type of `self` without \
1845 the `arbitrary_self_types` feature",
1846 ),
1847 )
1848 .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>`"))
1849 .emit()
1850 }
1851 None | Some(ArbitrarySelfTypesLevel::Basic)
1852 if receiver_is_valid(
1853 wfcx,
1854 span,
1855 receiver_ty,
1856 self_ty,
1857 Some(ArbitrarySelfTypesLevel::WithPointers),
1858 generics,
1859 )
1860 .is_ok() =>
1861 {
1862 feature_err(
1864 &tcx.sess,
1865 sym::arbitrary_self_types_pointers,
1866 span,
1867 format!(
1868 "`{receiver_ty}` cannot be used as the type of `self` without \
1869 the `arbitrary_self_types_pointers` feature",
1870 ),
1871 )
1872 .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>`"))
1873 .emit()
1874 }
1875 _ =>
1876 {
1878 match receiver_validity_err {
1879 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1880 let hint = match receiver_ty
1881 .builtin_deref(false)
1882 .unwrap_or(receiver_ty)
1883 .ty_adt_def()
1884 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1885 {
1886 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1887 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1888 _ => None,
1889 };
1890
1891 tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
1892 span,
1893 receiver_ty,
1894 hint,
1895 })
1896 }
1897 ReceiverValidityError::DoesNotDeref => {
1898 tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
1899 span,
1900 receiver_ty,
1901 })
1902 }
1903 ReceiverValidityError::MethodGenericParamUsed => tcx
1904 .dcx()
1905 .emit_err(diagnostics::InvalidGenericReceiverTy { span, receiver_ty }),
1906 }
1907 }
1908 });
1909 }
1910 Ok(())
1911}
1912
1913enum ReceiverValidityError {
1917 DoesNotDeref,
1920 MethodGenericParamUsed,
1922}
1923
1924fn confirm_type_is_not_a_method_generic_param(
1927 ty: Ty<'_>,
1928 method_generics: &ty::Generics,
1929) -> Result<(), ReceiverValidityError> {
1930 if let ty::Param(param) = ty.kind() {
1931 if (param.index as usize) >= method_generics.parent_count {
1932 return Err(ReceiverValidityError::MethodGenericParamUsed);
1933 }
1934 }
1935 Ok(())
1936}
1937
1938fn receiver_is_valid<'tcx>(
1948 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1949 span: Span,
1950 receiver_ty: Ty<'tcx>,
1951 self_ty: Ty<'tcx>,
1952 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1953 method_generics: &ty::Generics,
1954) -> Result<(), ReceiverValidityError> {
1955 let infcx = wfcx.infcx;
1956 let tcx = wfcx.tcx();
1957 let cause =
1958 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1959
1960 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1962 let ocx = ObligationCtxt::new(wfcx.infcx);
1963 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1964 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1965 Ok(())
1966 } else {
1967 Err(NoSolution)
1968 }
1969 }) {
1970 return Ok(());
1971 }
1972
1973 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1974
1975 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1976
1977 if arbitrary_self_types_enabled.is_some() {
1981 autoderef = autoderef.use_receiver_trait();
1982 }
1983
1984 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1986 autoderef = autoderef.include_raw_pointers();
1987 }
1988
1989 while let Some((potential_self_ty, _)) = autoderef.next() {
1991 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1991",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1991u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: potential self type `{0:?}` to match `{1:?}`",
potential_self_ty, self_ty) as &dyn Value))])
});
} else { ; }
};debug!(
1992 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1993 potential_self_ty, self_ty
1994 );
1995
1996 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1997
1998 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
2001 let ocx = ObligationCtxt::new(wfcx.infcx);
2002 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
2003 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
2004 Ok(())
2005 } else {
2006 Err(NoSolution)
2007 }
2008 }) {
2009 wfcx.register_obligations(autoderef.into_obligations());
2010 return Ok(());
2011 }
2012
2013 if arbitrary_self_types_enabled.is_none() {
2016 let legacy_receiver_trait_def_id =
2017 tcx.require_lang_item(LangItem::LegacyReceiver, span);
2018 if !legacy_receiver_is_implemented(
2019 wfcx,
2020 legacy_receiver_trait_def_id,
2021 cause.clone(),
2022 potential_self_ty,
2023 ) {
2024 break;
2026 }
2027
2028 wfcx.register_bound(
2030 cause.clone(),
2031 wfcx.param_env,
2032 potential_self_ty,
2033 legacy_receiver_trait_def_id,
2034 );
2035 }
2036 }
2037
2038 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:2038",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2038u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: type `{0:?}` does not deref to `{1:?}`",
receiver_ty, self_ty) as &dyn Value))])
});
} else { ; }
};debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
2039 Err(ReceiverValidityError::DoesNotDeref)
2040}
2041
2042fn legacy_receiver_is_implemented<'tcx>(
2043 wfcx: &WfCheckingCtxt<'_, 'tcx>,
2044 legacy_receiver_trait_def_id: DefId,
2045 cause: ObligationCause<'tcx>,
2046 receiver_ty: Ty<'tcx>,
2047) -> bool {
2048 let tcx = wfcx.tcx();
2049 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2050
2051 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2052
2053 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2054 true
2055 } else {
2056 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:2056",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2056u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("receiver_is_implemented: type `{0:?}` does not implement `LegacyReceiver` trait",
receiver_ty) as &dyn Value))])
});
} else { ; }
};debug!(
2057 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2058 receiver_ty
2059 );
2060 false
2061 }
2062}
2063
2064pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2065 match tcx.def_kind(def_id) {
2066 DefKind::Enum | DefKind::Struct | DefKind::Union => {
2067 }
2069 kind => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
format_args!("cannot compute the variances of {0:?}", kind))span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
2070 }
2071
2072 let ty_predicates = tcx.predicates_of(def_id);
2073 {
match (&ty_predicates.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_predicates.parent, None);
2074 let variances = tcx.variances_of(def_id);
2075
2076 let mut constrained_parameters: FxHashSet<_> = variances
2077 .iter()
2078 .enumerate()
2079 .filter(|&(_, &variance)| variance != ty::Bivariant)
2080 .map(|(index, _)| Parameter(index as u32))
2081 .collect();
2082
2083 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2084
2085 let explicitly_bounded_params = LazyCell::new(|| {
2087 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2088 tcx.hir_node_by_def_id(def_id)
2089 .generics()
2090 .unwrap()
2091 .predicates
2092 .iter()
2093 .filter_map(|predicate| match predicate.kind {
2094 hir::WherePredicateKind::BoundPredicate(predicate) => {
2095 match icx.lower_ty(predicate.bounded_ty).kind() {
2096 ty::Param(data) => Some(Parameter(data.index)),
2097 _ => None,
2098 }
2099 }
2100 _ => None,
2101 })
2102 .collect::<FxHashSet<_>>()
2103 });
2104
2105 for (index, _) in variances.iter().enumerate() {
2106 let parameter = Parameter(index as u32);
2107
2108 if constrained_parameters.contains(¶meter) {
2109 continue;
2110 }
2111
2112 let node = tcx.hir_node_by_def_id(def_id);
2113 let item = node.expect_item();
2114 let hir_generics = node.generics().unwrap();
2115 let hir_param = &hir_generics.params[index];
2116
2117 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2118
2119 if ty_param.def_id != hir_param.def_id.into() {
2120 tcx.dcx().span_delayed_bug(
2128 hir_param.span,
2129 "hir generics and ty generics in different order",
2130 );
2131 continue;
2132 }
2133
2134 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2136 .type_of(def_id)
2137 .instantiate_identity()
2138 .skip_norm_wip()
2139 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2140 {
2141 continue;
2142 }
2143
2144 match hir_param.name {
2145 hir::ParamName::Error(_) => {
2146 }
2149 _ => {
2150 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2151 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2152 }
2153 }
2154 }
2155}
2156
2157struct HasErrorDeep<'tcx> {
2159 tcx: TyCtxt<'tcx>,
2160 seen: FxHashSet<DefId>,
2161}
2162impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2163 type Result = ControlFlow<ErrorGuaranteed>;
2164
2165 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2166 match *ty.kind() {
2167 ty::Adt(def, _) => {
2168 if self.seen.insert(def.did()) {
2169 for field in def.all_fields() {
2170 self.tcx
2171 .type_of(field.did)
2172 .instantiate_identity()
2173 .skip_norm_wip()
2174 .visit_with(self)?;
2175 }
2176 }
2177 }
2178 ty::Error(guar) => return ControlFlow::Break(guar),
2179 _ => {}
2180 }
2181 ty.super_visit_with(self)
2182 }
2183
2184 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2185 if let Err(guar) = r.error_reported() {
2186 ControlFlow::Break(guar)
2187 } else {
2188 ControlFlow::Continue(())
2189 }
2190 }
2191
2192 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2193 if let Err(guar) = c.error_reported() {
2194 ControlFlow::Break(guar)
2195 } else {
2196 ControlFlow::Continue(())
2197 }
2198 }
2199}
2200
2201fn report_bivariance<'tcx>(
2202 tcx: TyCtxt<'tcx>,
2203 param: &'tcx hir::GenericParam<'tcx>,
2204 has_explicit_bounds: bool,
2205 item: &'tcx hir::Item<'tcx>,
2206) -> ErrorGuaranteed {
2207 let param_name = param.name.ident();
2208
2209 let help = match item.kind {
2210 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2211 if let Some(def_id) = tcx.lang_items().phantom_data() {
2212 diagnostics::UnusedGenericParameterHelp::Adt {
2213 param_name,
2214 phantom_data: tcx.def_path_str(def_id),
2215 }
2216 } else {
2217 diagnostics::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2218 }
2219 }
2220 item_kind => ::rustc_middle::util::bug::bug_fmt(format_args!("report_bivariance: unexpected item kind: {0:?}",
item_kind))bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2221 };
2222
2223 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2224 intravisit::walk_item(
2225 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2226 item,
2227 );
2228
2229 if !usage_spans.is_empty() {
2230 let item_def_id = item.owner_id.to_def_id();
2234 let is_probably_cyclical =
2235 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2236 .visit_def(item_def_id)
2237 .is_break();
2238 if is_probably_cyclical {
2247 return tcx.dcx().emit_err(diagnostics::RecursiveGenericParameter {
2248 spans: usage_spans,
2249 param_span: param.span,
2250 param_name,
2251 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2252 help,
2253 note: (),
2254 });
2255 }
2256 }
2257
2258 let const_param_help =
2259 #[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);
2260
2261 let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2262 span: param.span,
2263 param_name,
2264 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2265 usage_spans,
2266 help,
2267 const_param_help,
2268 });
2269 diag.code(E0392);
2270 if item.kind.recovered() {
2271 diag.delay_as_bug()
2273 } else {
2274 diag.emit()
2275 }
2276}
2277
2278struct IsProbablyCyclical<'tcx> {
2284 tcx: TyCtxt<'tcx>,
2285 item_def_id: DefId,
2286 seen: FxHashSet<DefId>,
2287}
2288
2289impl<'tcx> IsProbablyCyclical<'tcx> {
2290 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2291 match self.tcx.def_kind(def_id) {
2292 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2293 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2294 self.tcx
2295 .type_of(field.did)
2296 .instantiate_identity()
2297 .skip_norm_wip()
2298 .visit_with(self)
2299 })
2300 }
2301 _ => ControlFlow::Continue(()),
2302 }
2303 }
2304}
2305
2306impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2307 type Result = ControlFlow<(), ()>;
2308
2309 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2310 if let Some(adt_def) = ty.ty_adt_def() {
2311 if adt_def.did() == self.item_def_id {
2312 return ControlFlow::Break(());
2313 }
2314 if self.seen.insert(adt_def.did()) {
2315 self.visit_def(adt_def.did())?;
2316 }
2317 }
2318 ty.super_visit_with(self)
2319 }
2320}
2321
2322struct CollectUsageSpans<'a> {
2327 spans: &'a mut Vec<Span>,
2328 param_def_id: DefId,
2329}
2330
2331impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2332 type Result = ();
2333
2334 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2335 }
2337
2338 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2339 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2340 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2341 && def_id == self.param_def_id
2342 {
2343 self.spans.push(t.span);
2344 return;
2345 } else if let Res::SelfTyAlias { .. } = qpath.res {
2346 self.spans.push(t.span);
2347 return;
2348 }
2349 }
2350 intravisit::walk_ty(self, t);
2351 }
2352}
2353
2354impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2355 #[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2357u32),
::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(&[]) })
} 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 predicates_with_span =
tcx.predicates_of(self.body_def_id).predicates.iter().copied();
let implied_obligations =
traits::elaborate(tcx, predicates_with_span);
for (pred, obligation_span) in implied_obligations {
match pred.kind().skip_binder() {
ty::ClauseKind::WellFormed(..) |
ty::ClauseKind::UnstableFeature(..) => continue,
_ => {}
}
if pred.is_global() &&
!pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
let pred =
self.normalize(span, None, Unnormalized::new_wip(pred));
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, pred);
self.ocx.register_obligation(obligation);
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2358 fn check_false_global_bounds(&mut self) {
2359 let tcx = self.ocx.infcx.tcx;
2360 let mut span = tcx.def_span(self.body_def_id);
2361 let empty_env = ty::ParamEnv::empty();
2362
2363 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2364 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2366
2367 for (pred, obligation_span) in implied_obligations {
2368 match pred.kind().skip_binder() {
2369 ty::ClauseKind::WellFormed(..)
2373 | ty::ClauseKind::UnstableFeature(..) => continue,
2375 _ => {}
2376 }
2377
2378 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2380 let pred = self.normalize(span, None, Unnormalized::new_wip(pred));
2381
2382 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2384 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2385 span = predicates
2386 .iter()
2387 .find(|pred| pred.span.contains(obligation_span))
2389 .map(|pred| pred.span)
2390 .unwrap_or(obligation_span);
2391 }
2392
2393 let obligation = Obligation::new(
2394 tcx,
2395 traits::ObligationCause::new(
2396 span,
2397 self.body_def_id,
2398 ObligationCauseCode::TrivialBound,
2399 ),
2400 empty_env,
2401 pred,
2402 );
2403 self.ocx.register_obligation(obligation);
2404 }
2405 }
2406 }
2407}
2408
2409pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2410 let items = tcx.hir_crate_items(());
2411 let res =
2412 items
2413 .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2414 .and(
2415 items.par_impl_items(|item| {
2416 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2417 }),
2418 )
2419 .and(items.par_trait_items(|item| {
2420 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2421 }))
2422 .and(items.par_foreign_items(|item| {
2423 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2424 }))
2425 .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2426 .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2427
2428 super::entry::check_for_entry_fn(tcx)?;
2429
2430 res
2431}
2432
2433fn lint_redundant_lifetimes<'tcx>(
2434 tcx: TyCtxt<'tcx>,
2435 owner_id: LocalDefId,
2436 outlives_env: &OutlivesEnvironment<'tcx>,
2437) {
2438 let def_kind = tcx.def_kind(owner_id);
2439 match def_kind {
2440 DefKind::Struct
2441 | DefKind::Union
2442 | DefKind::Enum
2443 | DefKind::Trait
2444 | DefKind::TraitAlias
2445 | DefKind::Fn
2446 | DefKind::Const { .. }
2447 | DefKind::Impl { of_trait: _ } => {
2448 }
2450 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2451 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2452 return;
2457 }
2458 }
2459 DefKind::Mod
2460 | DefKind::Variant
2461 | DefKind::TyAlias
2462 | DefKind::ForeignTy
2463 | DefKind::TyParam
2464 | DefKind::ConstParam
2465 | DefKind::Static { .. }
2466 | DefKind::Ctor(_, _)
2467 | DefKind::Macro(_)
2468 | DefKind::ExternCrate
2469 | DefKind::Use
2470 | DefKind::ForeignMod
2471 | DefKind::AnonConst
2472 | DefKind::InlineConst
2473 | DefKind::OpaqueTy
2474 | DefKind::Field
2475 | DefKind::LifetimeParam
2476 | DefKind::GlobalAsm
2477 | DefKind::Closure
2478 | DefKind::SyntheticCoroutineBody => return,
2479 }
2480
2481 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];
2490 lifetimes.extend(
2491 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2492 );
2493 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2495 for (idx, var) in tcx
2496 .fn_sig(owner_id)
2497 .instantiate_identity()
2498 .skip_norm_wip()
2499 .bound_vars()
2500 .iter()
2501 .enumerate()
2502 {
2503 let ty::BoundVariableKind::Region(kind) = var else { continue };
2504 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2505 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2506 }
2507 }
2508 lifetimes.retain(|candidate| candidate.is_named(tcx));
2509
2510 let mut shadowed = FxHashSet::default();
2514
2515 for (idx, &candidate) in lifetimes.iter().enumerate() {
2516 if shadowed.contains(&candidate) {
2521 continue;
2522 }
2523
2524 for &victim in &lifetimes[(idx + 1)..] {
2525 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2533 continue;
2534 };
2535
2536 if tcx.parent(def_id) != owner_id.to_def_id() {
2541 continue;
2542 }
2543
2544 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2546 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2547 {
2548 shadowed.insert(victim);
2549 tcx.emit_node_span_lint(
2550 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2551 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2552 tcx.def_span(def_id),
2553 RedundantLifetimeArgsLint { candidate, victim },
2554 );
2555 }
2556 }
2557 }
2558}
2559
2560#[derive(const _: () =
{
impl<'_sess, 'tcx, G> rustc_errors::Diagnostic<'_sess, G> for
RedundantLifetimeArgsLint<'tcx> where
G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
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)]
2561#[diag("unnecessary lifetime parameter `{$victim}`")]
2562#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2563struct RedundantLifetimeArgsLint<'tcx> {
2564 victim: ty::Region<'tcx>,
2566 candidate: ty::Region<'tcx>,
2568}