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, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags,
26 TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
27 Unnormalized, 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::errors;
48use crate::errors::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);
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 = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
215 if errors_compat.is_empty() {
216 Ok(())
219 } else {
220 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
221 }
222}
223
224pub(super) fn check_well_formed(
225 tcx: TyCtxt<'_>,
226 def_id: LocalDefId,
227) -> Result<(), ErrorGuaranteed> {
228 let mut res = crate::check::check::check_item_type(tcx, def_id);
229
230 for param in &tcx.generics_of(def_id).own_params {
231 res = res.and(check_param_wf(tcx, param));
232 }
233
234 res
235}
236
237#[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(250u32),
::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:257",
"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(257u32),
::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),
hir::ItemKind::Struct(..) =>
check_type_defn(tcx, item, false),
hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
hir::ItemKind::Trait { .. } => check_trait(tcx, item),
hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
_ => Ok(()),
}
}
}
}#[instrument(skip(tcx), level = "debug")]
251pub(super) fn check_item<'tcx>(
252 tcx: TyCtxt<'tcx>,
253 item: &'tcx hir::Item<'tcx>,
254) -> Result<(), ErrorGuaranteed> {
255 let def_id = item.owner_id.def_id;
256
257 debug!(
258 ?item.owner_id,
259 item.name = ? tcx.def_path_str(def_id)
260 );
261
262 match item.kind {
263 hir::ItemKind::Impl(ref impl_) => {
281 crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
282 let mut res = Ok(());
283 if let Some(of_trait) = impl_.of_trait {
284 let header = tcx.impl_trait_header(def_id);
285 let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
286 if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
287 let sp = of_trait.trait_ref.path.span;
288 res = Err(tcx
289 .dcx()
290 .struct_span_err(sp, "impls of auto traits cannot be default")
291 .with_span_labels(of_trait.defaultness_span, "default because of this")
292 .with_span_label(sp, "auto trait")
293 .emit());
294 }
295 match header.polarity {
296 ty::ImplPolarity::Positive => {
297 res = res.and(check_impl(tcx, item, impl_));
298 }
299 ty::ImplPolarity::Negative => {
300 let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
301 bug!("impl_polarity query disagrees with impl's polarity in HIR");
302 };
303 if let hir::Defaultness::Default { .. } = of_trait.defaultness {
305 let mut spans = vec![span];
306 spans.extend(of_trait.defaultness_span);
307 res = Err(struct_span_code_err!(
308 tcx.dcx(),
309 spans,
310 E0750,
311 "negative impls cannot be default impls"
312 )
313 .emit());
314 }
315 }
316 ty::ImplPolarity::Reservation => {
317 }
319 }
320 } else {
321 res = res.and(check_impl(tcx, item, impl_));
322 }
323 res
324 }
325 hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
326 hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
327 hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
328 hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
329 hir::ItemKind::Trait { .. } => check_trait(tcx, item),
330 hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
331 _ => Ok(()),
332 }
333}
334
335pub(super) fn check_foreign_item<'tcx>(
336 tcx: TyCtxt<'tcx>,
337 item: &'tcx hir::ForeignItem<'tcx>,
338) -> Result<(), ErrorGuaranteed> {
339 let def_id = item.owner_id.def_id;
340
341 {
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:341",
"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(341u32),
::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!(
342 ?item.owner_id,
343 item.name = ? tcx.def_path_str(def_id)
344 );
345
346 match item.kind {
347 hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
348 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
349 }
350}
351
352pub(crate) fn check_trait_item<'tcx>(
353 tcx: TyCtxt<'tcx>,
354 def_id: LocalDefId,
355) -> Result<(), ErrorGuaranteed> {
356 lint_item_shadowing_supertrait_item(tcx, def_id);
358
359 let mut res = Ok(());
360
361 if tcx.def_kind(def_id) == DefKind::AssocFn {
362 for &assoc_ty_def_id in
363 tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
364 {
365 res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
366 }
367 }
368 res
369}
370
371fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
384 let mut required_bounds_by_item = FxIndexMap::default();
386 let associated_items = tcx.associated_items(trait_def_id);
387
388 loop {
394 let mut should_continue = false;
395 for gat_item in associated_items.in_definition_order() {
396 let gat_def_id = gat_item.def_id.expect_local();
397 let gat_item = tcx.associated_item(gat_def_id);
398 if !gat_item.is_type() {
400 continue;
401 }
402 let gat_generics = tcx.generics_of(gat_def_id);
403 if gat_generics.is_own_empty() {
405 continue;
406 }
407
408 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
412 for item in associated_items.in_definition_order() {
413 let item_def_id = item.def_id.expect_local();
414 if item_def_id == gat_def_id {
416 continue;
417 }
418
419 let param_env = tcx.param_env(item_def_id);
420
421 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
422 ty::AssocKind::Fn { .. } => {
424 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
428 item_def_id.to_def_id(),
429 tcx.fn_sig(item_def_id).instantiate_identity().skip_norm_wip(),
430 );
431 gather_gat_bounds(
432 tcx,
433 param_env,
434 item_def_id,
435 sig.inputs_and_output,
436 &sig.inputs().iter().copied().collect(),
439 gat_def_id,
440 gat_generics,
441 )
442 }
443 ty::AssocKind::Type { .. } => {
445 let param_env = augment_param_env(
449 tcx,
450 param_env,
451 required_bounds_by_item.get(&item_def_id),
452 );
453 gather_gat_bounds(
454 tcx,
455 param_env,
456 item_def_id,
457 tcx.explicit_item_bounds(item_def_id)
458 .iter_identity_copied()
459 .map(Unnormalized::skip_norm_wip)
460 .collect::<Vec<_>>(),
461 &FxIndexSet::default(),
462 gat_def_id,
463 gat_generics,
464 )
465 }
466 ty::AssocKind::Const { .. } => None,
467 };
468
469 if let Some(item_required_bounds) = item_required_bounds {
470 if let Some(new_required_bounds) = &mut new_required_bounds {
476 new_required_bounds.retain(|b| item_required_bounds.contains(b));
477 } else {
478 new_required_bounds = Some(item_required_bounds);
479 }
480 }
481 }
482
483 if let Some(new_required_bounds) = new_required_bounds {
484 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
485 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
486 should_continue = true;
489 }
490 }
491 }
492 if !should_continue {
497 break;
498 }
499 }
500
501 for (gat_def_id, required_bounds) in required_bounds_by_item {
502 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
504 continue;
505 }
506
507 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
508 {
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:508",
"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(508u32),
::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);
509 let param_env = tcx.param_env(gat_def_id);
510
511 let unsatisfied_bounds: Vec<_> = required_bounds
512 .into_iter()
513 .filter(|clause| match clause.kind().skip_binder() {
514 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
515 !region_known_to_outlive(
516 tcx,
517 gat_def_id,
518 param_env,
519 &FxIndexSet::default(),
520 a,
521 b,
522 )
523 }
524 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
525 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
526 }
527 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected ClauseKind"))bug!("Unexpected ClauseKind"),
528 })
529 .map(|clause| clause.to_string())
530 .collect();
531
532 if !unsatisfied_bounds.is_empty() {
533 let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
534 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!(
535 "{} {}",
536 gat_item_hir.generics.add_where_or_trailing_comma(),
537 unsatisfied_bounds.join(", "),
538 );
539 let bound =
540 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
541 tcx.dcx()
542 .struct_span_err(
543 gat_item_hir.span,
544 ::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),
545 )
546 .with_span_suggestion(
547 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
548 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add the required where clause{0}",
plural))
})format!("add the required where clause{plural}"),
549 suggestion,
550 Applicability::MachineApplicable,
551 )
552 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
bound))
})format!(
553 "{bound} currently required to ensure that impls have maximum flexibility"
554 ))
555 .with_note(
556 "we are soliciting feedback, see issue #87479 \
557 <https://github.com/rust-lang/rust/issues/87479> for more information",
558 )
559 .emit();
560 }
561 }
562}
563
564fn augment_param_env<'tcx>(
566 tcx: TyCtxt<'tcx>,
567 param_env: ty::ParamEnv<'tcx>,
568 new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
569) -> ty::ParamEnv<'tcx> {
570 let Some(new_predicates) = new_predicates else {
571 return param_env;
572 };
573
574 if new_predicates.is_empty() {
575 return param_env;
576 }
577
578 let bounds = tcx.mk_clauses_from_iter(
579 param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
580 );
581 ty::ParamEnv::new(bounds)
584}
585
586fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
597 tcx: TyCtxt<'tcx>,
598 param_env: ty::ParamEnv<'tcx>,
599 item_def_id: LocalDefId,
600 to_check: T,
601 wf_tys: &FxIndexSet<Ty<'tcx>>,
602 gat_def_id: LocalDefId,
603 gat_generics: &'tcx ty::Generics,
604) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
605 let mut bounds = FxIndexSet::default();
607
608 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
609
610 if types.is_empty() && regions.is_empty() {
616 return None;
617 }
618
619 for (region_a, region_a_idx) in ®ions {
620 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
624 continue;
625 }
626 for (ty, ty_idx) in &types {
631 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
633 {
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:633",
"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(633u32),
::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);
634 {
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:634",
"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(634u32),
::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}");
635 let ty_param = gat_generics.param_at(*ty_idx, tcx);
639 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
640 let region_param = gat_generics.param_at(*region_a_idx, tcx);
643 let region_param = ty::Region::new_early_param(
644 tcx,
645 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
646 );
647 bounds.insert(
650 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
651 .upcast(tcx),
652 );
653 }
654 }
655
656 for (region_b, region_b_idx) in ®ions {
661 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 {
665 continue;
666 }
667 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
668 {
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:668",
"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(668u32),
::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);
669 {
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:669",
"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(669u32),
::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}");
670 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
672 let region_a_param = ty::Region::new_early_param(
673 tcx,
674 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
675 );
676 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
678 let region_b_param = ty::Region::new_early_param(
679 tcx,
680 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
681 );
682 bounds.insert(
684 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
685 region_a_param,
686 region_b_param,
687 ))
688 .upcast(tcx),
689 );
690 }
691 }
692 }
693
694 Some(bounds)
695}
696
697fn ty_known_to_outlive<'tcx>(
700 tcx: TyCtxt<'tcx>,
701 id: LocalDefId,
702 param_env: ty::ParamEnv<'tcx>,
703 wf_tys: &FxIndexSet<Ty<'tcx>>,
704 ty: Ty<'tcx>,
705 region: ty::Region<'tcx>,
706) -> bool {
707 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
708 infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
709 sub_region: region,
710 sup_type: ty,
711 origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
712 });
713 })
714}
715
716fn region_known_to_outlive<'tcx>(
719 tcx: TyCtxt<'tcx>,
720 id: LocalDefId,
721 param_env: ty::ParamEnv<'tcx>,
722 wf_tys: &FxIndexSet<Ty<'tcx>>,
723 region_a: ty::Region<'tcx>,
724 region_b: ty::Region<'tcx>,
725) -> bool {
726 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
727 infcx.sub_regions(
728 SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
729 region_b,
730 region_a,
731 ty::VisibleForLeakCheck::Unreachable,
732 );
733 })
734}
735
736fn test_region_obligations<'tcx>(
740 tcx: TyCtxt<'tcx>,
741 id: LocalDefId,
742 param_env: ty::ParamEnv<'tcx>,
743 wf_tys: &FxIndexSet<Ty<'tcx>>,
744 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
745) -> bool {
746 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
750
751 add_constraints(&infcx);
752
753 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
754 {
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:754",
"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(754u32),
::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");
755
756 errors.is_empty()
759}
760
761struct GATArgsCollector<'tcx> {
766 gat: DefId,
767 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
769 types: FxIndexSet<(Ty<'tcx>, usize)>,
771}
772
773impl<'tcx> GATArgsCollector<'tcx> {
774 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
775 gat: DefId,
776 t: T,
777 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
778 let mut visitor =
779 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
780 t.visit_with(&mut visitor);
781 (visitor.regions, visitor.types)
782 }
783}
784
785impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
786 fn visit_ty(&mut self, t: Ty<'tcx>) {
787 match t.kind() {
788 &ty::Alias(ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
789 if def_id == self.gat =>
790 {
791 for (idx, arg) in args.iter().enumerate() {
792 match arg.kind() {
793 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
794 self.regions.insert((lt, idx));
795 }
796 GenericArgKind::Type(t) => {
797 self.types.insert((t, idx));
798 }
799 _ => {}
800 }
801 }
802 }
803 _ => {}
804 }
805 t.super_visit_with(self)
806 }
807}
808
809fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
810 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
811 let trait_def_id = tcx.local_parent(trait_item_def_id);
812
813 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
814 .skip(1)
815 .flat_map(|supertrait_def_id| {
816 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
817 })
818 .collect();
819 if !shadowed.is_empty() {
820 let shadowee = if let [shadowed] = shadowed[..] {
821 errors::SupertraitItemShadowee::Labeled {
822 span: tcx.def_span(shadowed.def_id),
823 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
824 }
825 } else {
826 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
827 .iter()
828 .map(|item| {
829 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
830 })
831 .unzip();
832 errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
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 errors::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().adt_const_params() || tcx.features().min_adt_const_params() {
860 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
861 wfcx.register_bound(
862 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
863 wfcx.param_env,
864 ty,
865 tcx.require_lang_item(LangItem::ConstParamTy, span),
866 );
867 Ok(())
868 })
869 } else {
870 let span = || {
871 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
872 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
873 else {
874 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
875 };
876 span
877 };
878 let mut diag = match ty.kind() {
879 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
880 ty::FnPtr(..) => tcx.dcx().struct_span_err(
881 span(),
882 "using function pointers as const generic parameters is forbidden",
883 ),
884 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
885 span(),
886 "using raw pointers as const generic parameters is forbidden",
887 ),
888 _ => {
889 ty.error_reported()?;
891
892 tcx.dcx().struct_span_err(
893 span(),
894 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
895 "`{ty}` is forbidden as the type of a const generic parameter",
896 ),
897 )
898 }
899 };
900
901 diag.note("the only supported types are integers, `bool`, and `char`");
902
903 let cause = ObligationCause::misc(span(), def_id);
904 let adt_const_params_feature_string =
905 " more complex and user defined types".to_string();
906 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
907 tcx,
908 tcx.param_env(param.def_id),
909 ty,
910 cause,
911 ) {
912 Err(
914 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
915 | ConstParamTyImplementationError::NonExhaustive(..)
916 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
917 ) => None,
918 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
919 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![
920 (adt_const_params_feature_string, sym::min_adt_const_params),
921 (
922 " references to implement the `ConstParamTy` trait".into(),
923 sym::unsized_const_params,
924 ),
925 ])
926 }
927 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
930 fn ty_is_local(ty: Ty<'_>) -> bool {
931 match ty.kind() {
932 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
933 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
935 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
938 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
941 _ => false,
942 }
943 }
944
945 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![(
946 adt_const_params_feature_string,
947 sym::min_adt_const_params,
948 )])
949 }
950 Ok(..) => {
952 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)])
953 }
954 };
955 if let Some(features) = may_suggest_feature {
956 tcx.disabled_nightly_features(&mut diag, features);
957 }
958
959 Err(diag.emit())
960 }
961 }
962 }
963}
964
965#[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(965u32),
::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))]
966pub(crate) fn check_associated_item(
967 tcx: TyCtxt<'_>,
968 def_id: LocalDefId,
969) -> Result<(), ErrorGuaranteed> {
970 let loc = Some(WellFormedLoc::Ty(def_id));
971 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
972 let item = tcx.associated_item(def_id);
973
974 tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
977
978 let self_ty = match item.container {
979 ty::AssocContainer::Trait => tcx.types.self_param,
980 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
981 tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
982 }
983 };
984
985 let span = tcx.def_span(def_id);
986
987 match item.kind {
988 ty::AssocKind::Const { .. } => {
989 let ty = tcx.type_of(def_id).instantiate_identity();
990 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
991 wfcx.register_wf_obligation(span, loc, ty.into());
992
993 let has_value = item.defaultness(tcx).has_value();
994 if tcx.is_type_const(def_id) {
995 check_type_const(wfcx, def_id, ty, has_value)?;
996 }
997
998 if has_value {
999 let code = ObligationCauseCode::SizedConstOrStatic;
1000 wfcx.register_bound(
1001 ObligationCause::new(span, def_id, code),
1002 wfcx.param_env,
1003 ty,
1004 tcx.require_lang_item(LangItem::Sized, span),
1005 );
1006 }
1007
1008 Ok(())
1009 }
1010 ty::AssocKind::Fn { .. } => {
1011 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1012 let hir_sig =
1013 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
1014 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1015 check_method_receiver(wfcx, hir_sig, item, self_ty)
1016 }
1017 ty::AssocKind::Type { .. } => {
1018 if let ty::AssocContainer::Trait = item.container {
1019 check_associated_type_bounds(wfcx, item, span)
1020 }
1021 if item.defaultness(tcx).has_value() {
1022 let ty = tcx.type_of(def_id).instantiate_identity();
1023 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1024 wfcx.register_wf_obligation(span, loc, ty.into());
1025 }
1026 Ok(())
1027 }
1028 }
1029 })
1030}
1031
1032fn check_type_defn<'tcx>(
1034 tcx: TyCtxt<'tcx>,
1035 item: &hir::Item<'tcx>,
1036 all_sized: bool,
1037) -> Result<(), ErrorGuaranteed> {
1038 tcx.ensure_ok().check_representability(item.owner_id.def_id);
1039 let adt_def = tcx.adt_def(item.owner_id);
1040
1041 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1042 let variants = adt_def.variants();
1043 let packed = adt_def.repr().packed();
1044
1045 for variant in variants.iter() {
1046 for field in &variant.fields {
1048 if let Some(def_id) = field.value
1049 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1050 {
1051 if let Some(def_id) = def_id.as_local()
1054 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1055 && let expr = &tcx.hir_body(anon.body).value
1056 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1057 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1058 {
1059 } else {
1062 let _ = tcx.const_eval_poly(def_id);
1065 }
1066 }
1067 let field_id = field.did.expect_local();
1068 let hir::FieldDef { ty: hir_ty, .. } =
1069 tcx.hir_node_by_def_id(field_id).expect_field();
1070 let ty = wfcx.deeply_normalize(
1071 hir_ty.span,
1072 None,
1073 tcx.type_of(field.did).instantiate_identity(),
1074 );
1075 wfcx.register_wf_obligation(
1076 hir_ty.span,
1077 Some(WellFormedLoc::Ty(field_id)),
1078 ty.into(),
1079 );
1080
1081 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())
1082 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1083 {
1084 tcx.dcx().span_err(
1087 hir_ty.span,
1088 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1089 "scalable vectors cannot be fields of a {}",
1090 adt_def.variant_descr()
1091 ),
1092 );
1093 }
1094 }
1095
1096 let needs_drop_copy = || {
1099 packed && {
1100 let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1101 let ty = tcx.erase_and_anonymize_regions(ty);
1102 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1103 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1104 }
1105 };
1106 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1108 let unsized_len = if all_sized { 0 } else { 1 };
1109 for (idx, field) in
1110 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1111 {
1112 let last = idx == variant.fields.len() - 1;
1113 let field_id = field.did.expect_local();
1114 let hir::FieldDef { ty: hir_ty, .. } =
1115 tcx.hir_node_by_def_id(field_id).expect_field();
1116 let ty = wfcx.normalize(
1117 hir_ty.span,
1118 None,
1119 tcx.type_of(field.did).instantiate_identity(),
1120 );
1121 wfcx.register_bound(
1122 traits::ObligationCause::new(
1123 hir_ty.span,
1124 wfcx.body_def_id,
1125 ObligationCauseCode::FieldSized {
1126 adt_kind: match &item.kind {
1127 ItemKind::Struct(..) => AdtKind::Struct,
1128 ItemKind::Union(..) => AdtKind::Union,
1129 ItemKind::Enum(..) => AdtKind::Enum,
1130 kind => ::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("should be wfchecking an ADT, got {0:?}", kind))span_bug!(
1131 item.span,
1132 "should be wfchecking an ADT, got {kind:?}"
1133 ),
1134 },
1135 span: hir_ty.span,
1136 last,
1137 },
1138 ),
1139 wfcx.param_env,
1140 ty,
1141 tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1142 );
1143 }
1144
1145 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1147 match tcx.const_eval_poly(discr_def_id) {
1148 Ok(_) => {}
1149 Err(ErrorHandled::Reported(..)) => {}
1150 Err(ErrorHandled::TooGeneric(sp)) => {
1151 ::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")
1152 }
1153 }
1154 }
1155 }
1156
1157 check_where_clauses(wfcx, item.owner_id.def_id);
1158 Ok(())
1159 })
1160}
1161
1162#[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(1162u32),
::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::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,
&{ 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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
{
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:1164",
"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(1164u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["item.owner_id"],
::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))])
});
} else { ; }
};
let def_id = item.owner_id.def_id;
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(()) });
if let hir::ItemKind::Trait { .. } = item.kind {
check_gat_where_clauses(tcx, item.owner_id.def_id);
}
res
}
}
}#[instrument(skip(tcx, item))]
1163fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1164 debug!(?item.owner_id);
1165
1166 let def_id = item.owner_id.def_id;
1167 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1168 return Ok(());
1170 }
1171
1172 let trait_def = tcx.trait_def(def_id);
1173 if trait_def.is_marker
1174 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1175 {
1176 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1177 struct_span_code_err!(
1178 tcx.dcx(),
1179 tcx.def_span(*associated_def_id),
1180 E0714,
1181 "marker traits cannot have associated items",
1182 )
1183 .emit();
1184 }
1185 }
1186
1187 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1188 check_where_clauses(wfcx, def_id);
1189 Ok(())
1190 });
1191
1192 if let hir::ItemKind::Trait { .. } = item.kind {
1194 check_gat_where_clauses(tcx, item.owner_id.def_id);
1195 }
1196 res
1197}
1198
1199fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1204 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1205
1206 {
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:1206",
"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(1206u32),
::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);
1207 let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1208 |(bound, bound_span)| {
1209 traits::wf::clause_obligations(
1210 wfcx.infcx,
1211 wfcx.param_env,
1212 wfcx.body_def_id,
1213 bound,
1214 bound_span,
1215 )
1216 },
1217 );
1218
1219 wfcx.register_obligations(wf_obligations);
1220}
1221
1222fn check_item_fn(
1223 tcx: TyCtxt<'_>,
1224 def_id: LocalDefId,
1225 decl: &hir::FnDecl<'_>,
1226) -> Result<(), ErrorGuaranteed> {
1227 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1228 check_eiis_fn(tcx, def_id);
1229
1230 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1231 check_fn_or_method(wfcx, sig, decl, def_id);
1232 Ok(())
1233 })
1234}
1235
1236fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1237 for EiiImpl { resolution, span, .. } in
1240 {
{
'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()
1241 {
1242 let (foreign_item, name) = match resolution {
1243 EiiImplResolution::Macro(def_id) => {
1244 if let Some(foreign_item) =
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(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)
1248 {
1249 (foreign_item, tcx.item_name(*def_id))
1250 } else {
1251 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1252 continue;
1253 }
1254 }
1255 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1256 EiiImplResolution::Error(_eg) => continue,
1257 };
1258
1259 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1260 }
1261}
1262
1263fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1264 for EiiImpl { resolution, span, .. } in
1267 {
{
'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()
1268 {
1269 let (foreign_item, name) = match resolution {
1270 EiiImplResolution::Macro(def_id) => {
1271 if let Some(foreign_item) =
1274 {
{
'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)
1275 {
1276 (foreign_item, tcx.item_name(*def_id))
1277 } else {
1278 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1279 continue;
1280 }
1281 }
1282 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1283 EiiImplResolution::Error(_eg) => continue,
1284 };
1285
1286 let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1287 }
1288}
1289
1290#[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(1290u32),
::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, Unnormalized::new_wip(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))]
1291pub(crate) fn check_static_item<'tcx>(
1292 tcx: TyCtxt<'tcx>,
1293 item_id: LocalDefId,
1294 ty: Ty<'tcx>,
1295 should_check_for_sync: bool,
1296) -> Result<(), ErrorGuaranteed> {
1297 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1298 if should_check_for_sync {
1299 check_eiis_static(tcx, item_id, ty);
1300 }
1301
1302 let span = tcx.ty_span(item_id);
1303 let loc = Some(WellFormedLoc::Ty(item_id));
1304 let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1305
1306 let is_foreign_item = tcx.is_foreign_item(item_id);
1307 let is_structurally_foreign_item = || {
1308 let tail = tcx.struct_tail_raw(
1309 item_ty,
1310 &ObligationCause::dummy(),
1311 |ty| wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty)),
1312 || {},
1313 );
1314
1315 matches!(tail.kind(), ty::Foreign(_))
1316 };
1317 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1318
1319 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1320 if forbid_unsized {
1321 let span = tcx.def_span(item_id);
1322 wfcx.register_bound(
1323 traits::ObligationCause::new(
1324 span,
1325 wfcx.body_def_id,
1326 ObligationCauseCode::SizedConstOrStatic,
1327 ),
1328 wfcx.param_env,
1329 item_ty,
1330 tcx.require_lang_item(LangItem::Sized, span),
1331 );
1332 }
1333
1334 let should_check_for_sync = should_check_for_sync
1336 && !is_foreign_item
1337 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1338 && !tcx.is_thread_local_static(item_id.to_def_id());
1339
1340 if should_check_for_sync {
1341 wfcx.register_bound(
1342 traits::ObligationCause::new(
1343 span,
1344 wfcx.body_def_id,
1345 ObligationCauseCode::SharedStatic,
1346 ),
1347 wfcx.param_env,
1348 item_ty,
1349 tcx.require_lang_item(LangItem::Sync, span),
1350 );
1351 }
1352 Ok(())
1353 })
1354}
1355
1356#[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(1356u32),
::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);
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))]
1357pub(super) fn check_type_const<'tcx>(
1358 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1359 def_id: LocalDefId,
1360 item_ty: Ty<'tcx>,
1361 has_value: bool,
1362) -> Result<(), ErrorGuaranteed> {
1363 let tcx = wfcx.tcx();
1364 let span = tcx.def_span(def_id);
1365
1366 wfcx.register_bound(
1367 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1368 wfcx.param_env,
1369 item_ty,
1370 tcx.require_lang_item(LangItem::ConstParamTy, span),
1371 );
1372
1373 if has_value {
1374 let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1375 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1376 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1377
1378 wfcx.register_obligation(Obligation::new(
1379 tcx,
1380 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1381 wfcx.param_env,
1382 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1383 ));
1384 }
1385 Ok(())
1386}
1387
1388#[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(1388u32),
::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:1460",
"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(1460u32),
::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_))]
1389fn check_impl<'tcx>(
1390 tcx: TyCtxt<'tcx>,
1391 item: &'tcx hir::Item<'tcx>,
1392 impl_: &hir::Impl<'_>,
1393) -> Result<(), ErrorGuaranteed> {
1394 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1395 match impl_.of_trait {
1396 Some(of_trait) => {
1397 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1401 tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1404 let trait_span = of_trait.trait_ref.path.span;
1405 let trait_ref = wfcx.deeply_normalize(
1406 trait_span,
1407 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1408 trait_ref,
1409 );
1410 let trait_pred =
1411 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1412 let mut obligations = traits::wf::trait_obligations(
1413 wfcx.infcx,
1414 wfcx.param_env,
1415 wfcx.body_def_id,
1416 trait_pred,
1417 trait_span,
1418 item,
1419 );
1420 for obligation in &mut obligations {
1421 if obligation.cause.span != trait_span {
1422 continue;
1424 }
1425 if let Some(pred) = obligation.predicate.as_trait_clause()
1426 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1427 {
1428 obligation.cause.span = impl_.self_ty.span;
1429 }
1430 if let Some(pred) = obligation.predicate.as_projection_clause()
1431 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1432 {
1433 obligation.cause.span = impl_.self_ty.span;
1434 }
1435 }
1436
1437 if tcx.is_conditionally_const(item.owner_id.def_id) {
1439 for (bound, _) in
1440 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1441 {
1442 let bound = wfcx.normalize(
1443 item.span,
1444 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1445 bound,
1446 );
1447 wfcx.register_obligation(Obligation::new(
1448 tcx,
1449 ObligationCause::new(
1450 impl_.self_ty.span,
1451 wfcx.body_def_id,
1452 ObligationCauseCode::WellFormed(None),
1453 ),
1454 wfcx.param_env,
1455 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1456 ))
1457 }
1458 }
1459
1460 debug!(?obligations);
1461 wfcx.register_obligations(obligations);
1462 }
1463 None => {
1464 let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1465 let self_ty = wfcx.deeply_normalize(
1466 item.span,
1467 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1468 Unnormalized::new_wip(self_ty),
1469 );
1470 wfcx.register_wf_obligation(
1471 impl_.self_ty.span,
1472 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1473 self_ty.into(),
1474 );
1475 }
1476 }
1477
1478 check_where_clauses(wfcx, item.owner_id.def_id);
1479 Ok(())
1480 })
1481}
1482
1483#[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(1484u32),
::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::Unevaluated(uv) => {
infcx.tcx.type_of(uv.def).instantiate(infcx.tcx,
uv.args).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(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 =
tcx.type_of(pred.projection_term.def_id()).instantiate(tcx,
pred.projection_term.args).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))]
1485pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1486 let infcx = wfcx.infcx;
1487 let tcx = wfcx.tcx();
1488
1489 let predicates = tcx.predicates_of(def_id.to_def_id());
1490 let generics = tcx.generics_of(def_id);
1491
1492 for param in &generics.own_params {
1499 if let Some(default) = param
1500 .default_value(tcx)
1501 .map(ty::EarlyBinder::instantiate_identity)
1502 .map(Unnormalized::skip_norm_wip)
1503 {
1504 if !default.has_param() {
1511 wfcx.register_wf_obligation(
1512 tcx.def_span(param.def_id),
1513 matches!(param.kind, GenericParamDefKind::Type { .. })
1514 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1515 default.as_term().unwrap(),
1516 );
1517 } else {
1518 let GenericArgKind::Const(ct) = default.kind() else {
1521 continue;
1522 };
1523
1524 let ct_ty = match ct.kind() {
1525 ty::ConstKind::Infer(_)
1526 | ty::ConstKind::Placeholder(_)
1527 | ty::ConstKind::Bound(_, _) => unreachable!(),
1528 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1529 ty::ConstKind::Value(cv) => cv.ty,
1530 ty::ConstKind::Unevaluated(uv) => {
1531 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args).skip_norm_wip()
1532 }
1533 ty::ConstKind::Param(param_ct) => {
1534 param_ct.find_const_ty_from_env(wfcx.param_env)
1535 }
1536 };
1537
1538 let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1539 if !ct_ty.has_param() && !param_ty.has_param() {
1540 let cause = traits::ObligationCause::new(
1541 tcx.def_span(param.def_id),
1542 wfcx.body_def_id,
1543 ObligationCauseCode::WellFormed(None),
1544 );
1545 wfcx.register_obligation(Obligation::new(
1546 tcx,
1547 cause,
1548 wfcx.param_env,
1549 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1550 ));
1551 }
1552 }
1553 }
1554 }
1555
1556 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1565 if param.index >= generics.parent_count as u32
1566 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1568 && !default.has_param()
1570 {
1571 return default;
1573 }
1574 tcx.mk_param_from_def(param)
1575 });
1576
1577 let default_obligations = predicates
1579 .predicates
1580 .iter()
1581 .flat_map(|&(pred, sp)| {
1582 #[derive(Default)]
1583 struct CountParams {
1584 params: FxHashSet<u32>,
1585 }
1586 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1587 type Result = ControlFlow<()>;
1588 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1589 if let ty::Param(param) = t.kind() {
1590 self.params.insert(param.index);
1591 }
1592 t.super_visit_with(self)
1593 }
1594
1595 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1596 ControlFlow::Break(())
1597 }
1598
1599 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1600 if let ty::ConstKind::Param(param) = c.kind() {
1601 self.params.insert(param.index);
1602 }
1603 c.super_visit_with(self)
1604 }
1605 }
1606 let mut param_count = CountParams::default();
1607 let has_region = pred.visit_with(&mut param_count).is_break();
1608 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1609 if instantiated_pred.skip_normalization().has_non_region_param()
1612 || param_count.params.len() > 1
1613 || has_region
1614 {
1615 None
1616 } else if predicates
1617 .predicates
1618 .iter()
1619 .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_pred)
1620 {
1621 None
1623 } else {
1624 Some((instantiated_pred, sp))
1625 }
1626 })
1627 .map(|(pred, sp)| {
1628 let pred = wfcx.normalize(sp, None, pred);
1638 let cause = traits::ObligationCause::new(
1639 sp,
1640 wfcx.body_def_id,
1641 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1642 );
1643 Obligation::new(tcx, cause, wfcx.param_env, pred)
1644 });
1645
1646 let predicates = predicates.instantiate_identity(tcx);
1647
1648 let assoc_const_obligations: Vec<_> = predicates
1649 .predicates
1650 .iter()
1651 .copied()
1652 .zip(predicates.spans.iter().copied())
1653 .filter_map(|(clause, sp)| {
1654 let clause = clause.skip_norm_wip();
1655 let proj = clause.as_projection_clause()?;
1656 let pred_binder = proj
1657 .map_bound(|pred| {
1658 pred.term.as_const().map(|ct| {
1659 let assoc_const_ty = tcx
1660 .type_of(pred.projection_term.def_id())
1661 .instantiate(tcx, pred.projection_term.args)
1662 .skip_norm_wip();
1663 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1664 })
1665 })
1666 .transpose();
1667 pred_binder.map(|pred_binder| {
1668 let cause = traits::ObligationCause::new(
1669 sp,
1670 wfcx.body_def_id,
1671 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1672 );
1673 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1674 })
1675 })
1676 .collect();
1677
1678 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1679 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1680 traits::wf::clause_obligations(
1681 infcx,
1682 wfcx.param_env,
1683 wfcx.body_def_id,
1684 p.skip_norm_wip(),
1685 sp,
1686 )
1687 });
1688 let obligations: Vec<_> =
1689 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1690 wfcx.register_obligations(obligations);
1691}
1692
1693#[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(1693u32),
::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() != hir::ImplicitSelfKind::None;
let mut inputs =
sig.inputs().iter().skip(if has_implicit_self {
1
} else { 0 });
if let Some(ty) = inputs.next() {
wfcx.register_bound(ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::RustCall),
wfcx.param_env, *ty,
tcx.require_lang_item(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))]
1694fn check_fn_or_method<'tcx>(
1695 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1696 sig: ty::PolyFnSig<'tcx>,
1697 hir_decl: &hir::FnDecl<'_>,
1698 def_id: LocalDefId,
1699) {
1700 let tcx = wfcx.tcx();
1701 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1702
1703 let arg_span =
1709 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1710
1711 sig.inputs_and_output =
1712 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1713 wfcx.deeply_normalize(
1714 arg_span(idx),
1715 Some(WellFormedLoc::Param {
1716 function: def_id,
1717 param_idx: idx,
1720 }),
1721 Unnormalized::new_wip(ty),
1722 )
1723 }));
1724
1725 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1726 wfcx.register_wf_obligation(
1727 arg_span(idx),
1728 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1729 ty.into(),
1730 );
1731 }
1732
1733 check_where_clauses(wfcx, def_id);
1734
1735 if sig.abi() == ExternAbi::RustCall {
1736 let span = tcx.def_span(def_id);
1737 let has_implicit_self = hir_decl.implicit_self() != hir::ImplicitSelfKind::None;
1738 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1739 if let Some(ty) = inputs.next() {
1741 wfcx.register_bound(
1742 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1743 wfcx.param_env,
1744 *ty,
1745 tcx.require_lang_item(hir::LangItem::Tuple, span),
1746 );
1747 wfcx.register_bound(
1748 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1749 wfcx.param_env,
1750 *ty,
1751 tcx.require_lang_item(hir::LangItem::Sized, span),
1752 );
1753 } else {
1754 tcx.dcx().span_err(
1755 hir_decl.inputs.last().map_or(span, |input| input.span),
1756 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1757 );
1758 }
1759 if inputs.next().is_some() {
1761 tcx.dcx().span_err(
1762 hir_decl.inputs.last().map_or(span, |input| input.span),
1763 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1764 );
1765 }
1766 }
1767
1768 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1770 let span = match hir_decl.output {
1771 hir::FnRetTy::Return(ty) => ty.span,
1772 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1773 };
1774
1775 wfcx.register_bound(
1776 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1777 wfcx.param_env,
1778 sig.output(),
1779 tcx.require_lang_item(LangItem::Sized, span),
1780 );
1781 }
1782}
1783
1784#[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)]
1786enum ArbitrarySelfTypesLevel {
1787 Basic, WithPointers, }
1790
1791#[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(1791u32),
::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:1811",
"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(1811u32),
::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(errors::InvalidReceiverTy {
span,
receiver_ty,
hint,
})
}
ReceiverValidityError::DoesNotDeref => {
tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
span,
receiver_ty,
})
}
ReceiverValidityError::MethodGenericParamUsed => {
tcx.dcx().emit_err(errors::InvalidGenericReceiverTy {
span,
receiver_ty,
})
}
}
}
});
}
Ok(())
}
}
}#[instrument(level = "debug", skip(wfcx))]
1792fn check_method_receiver<'tcx>(
1793 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1794 fn_sig: &hir::FnSig<'_>,
1795 method: ty::AssocItem,
1796 self_ty: Ty<'tcx>,
1797) -> Result<(), ErrorGuaranteed> {
1798 let tcx = wfcx.tcx();
1799
1800 if !method.is_method() {
1801 return Ok(());
1802 }
1803
1804 let span = fn_sig.decl.inputs[0].span;
1805 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1806
1807 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1808 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1809 let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1810
1811 debug!("check_method_receiver: sig={:?}", sig);
1812
1813 let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1814
1815 let receiver_ty = sig.inputs()[0];
1816 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1817
1818 receiver_ty.error_reported()?;
1821
1822 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1823 Some(ArbitrarySelfTypesLevel::WithPointers)
1824 } else if tcx.features().arbitrary_self_types() {
1825 Some(ArbitrarySelfTypesLevel::Basic)
1826 } else {
1827 None
1828 };
1829 let generics = tcx.generics_of(method.def_id);
1830
1831 let receiver_validity =
1832 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1833 if let Err(receiver_validity_err) = receiver_validity {
1834 return Err(match arbitrary_self_types_level {
1835 None if receiver_is_valid(
1839 wfcx,
1840 span,
1841 receiver_ty,
1842 self_ty,
1843 Some(ArbitrarySelfTypesLevel::Basic),
1844 generics,
1845 )
1846 .is_ok() =>
1847 {
1848 feature_err(
1850 &tcx.sess,
1851 sym::arbitrary_self_types,
1852 span,
1853 format!(
1854 "`{receiver_ty}` cannot be used as the type of `self` without \
1855 the `arbitrary_self_types` feature",
1856 ),
1857 )
1858 .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>`"))
1859 .emit()
1860 }
1861 None | Some(ArbitrarySelfTypesLevel::Basic)
1862 if receiver_is_valid(
1863 wfcx,
1864 span,
1865 receiver_ty,
1866 self_ty,
1867 Some(ArbitrarySelfTypesLevel::WithPointers),
1868 generics,
1869 )
1870 .is_ok() =>
1871 {
1872 feature_err(
1874 &tcx.sess,
1875 sym::arbitrary_self_types_pointers,
1876 span,
1877 format!(
1878 "`{receiver_ty}` cannot be used as the type of `self` without \
1879 the `arbitrary_self_types_pointers` feature",
1880 ),
1881 )
1882 .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>`"))
1883 .emit()
1884 }
1885 _ =>
1886 {
1888 match receiver_validity_err {
1889 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1890 let hint = match receiver_ty
1891 .builtin_deref(false)
1892 .unwrap_or(receiver_ty)
1893 .ty_adt_def()
1894 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1895 {
1896 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1897 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1898 _ => None,
1899 };
1900
1901 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1902 }
1903 ReceiverValidityError::DoesNotDeref => {
1904 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1905 span,
1906 receiver_ty,
1907 })
1908 }
1909 ReceiverValidityError::MethodGenericParamUsed => {
1910 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1911 }
1912 }
1913 }
1914 });
1915 }
1916 Ok(())
1917}
1918
1919enum ReceiverValidityError {
1923 DoesNotDeref,
1926 MethodGenericParamUsed,
1928}
1929
1930fn confirm_type_is_not_a_method_generic_param(
1933 ty: Ty<'_>,
1934 method_generics: &ty::Generics,
1935) -> Result<(), ReceiverValidityError> {
1936 if let ty::Param(param) = ty.kind() {
1937 if (param.index as usize) >= method_generics.parent_count {
1938 return Err(ReceiverValidityError::MethodGenericParamUsed);
1939 }
1940 }
1941 Ok(())
1942}
1943
1944fn receiver_is_valid<'tcx>(
1954 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1955 span: Span,
1956 receiver_ty: Ty<'tcx>,
1957 self_ty: Ty<'tcx>,
1958 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1959 method_generics: &ty::Generics,
1960) -> Result<(), ReceiverValidityError> {
1961 let infcx = wfcx.infcx;
1962 let tcx = wfcx.tcx();
1963 let cause =
1964 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1965
1966 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1968 let ocx = ObligationCtxt::new(wfcx.infcx);
1969 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1970 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1971 Ok(())
1972 } else {
1973 Err(NoSolution)
1974 }
1975 }) {
1976 return Ok(());
1977 }
1978
1979 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1980
1981 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1982
1983 if arbitrary_self_types_enabled.is_some() {
1987 autoderef = autoderef.use_receiver_trait();
1988 }
1989
1990 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1992 autoderef = autoderef.include_raw_pointers();
1993 }
1994
1995 while let Some((potential_self_ty, _)) = autoderef.next() {
1997 {
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:1997",
"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(1997u32),
::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!(
1998 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1999 potential_self_ty, self_ty
2000 );
2001
2002 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
2003
2004 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
2007 let ocx = ObligationCtxt::new(wfcx.infcx);
2008 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
2009 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
2010 Ok(())
2011 } else {
2012 Err(NoSolution)
2013 }
2014 }) {
2015 wfcx.register_obligations(autoderef.into_obligations());
2016 return Ok(());
2017 }
2018
2019 if arbitrary_self_types_enabled.is_none() {
2022 let legacy_receiver_trait_def_id =
2023 tcx.require_lang_item(LangItem::LegacyReceiver, span);
2024 if !legacy_receiver_is_implemented(
2025 wfcx,
2026 legacy_receiver_trait_def_id,
2027 cause.clone(),
2028 potential_self_ty,
2029 ) {
2030 break;
2032 }
2033
2034 wfcx.register_bound(
2036 cause.clone(),
2037 wfcx.param_env,
2038 potential_self_ty,
2039 legacy_receiver_trait_def_id,
2040 );
2041 }
2042 }
2043
2044 {
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:2044",
"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(2044u32),
::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);
2045 Err(ReceiverValidityError::DoesNotDeref)
2046}
2047
2048fn legacy_receiver_is_implemented<'tcx>(
2049 wfcx: &WfCheckingCtxt<'_, 'tcx>,
2050 legacy_receiver_trait_def_id: DefId,
2051 cause: ObligationCause<'tcx>,
2052 receiver_ty: Ty<'tcx>,
2053) -> bool {
2054 let tcx = wfcx.tcx();
2055 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2056
2057 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2058
2059 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2060 true
2061 } else {
2062 {
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:2062",
"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(2062u32),
::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!(
2063 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2064 receiver_ty
2065 );
2066 false
2067 }
2068}
2069
2070pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2071 match tcx.def_kind(def_id) {
2072 DefKind::Enum | DefKind::Struct | DefKind::Union => {
2073 }
2075 DefKind::TyAlias => {
2076 if !tcx.type_alias_is_lazy(def_id) {
{
::core::panicking::panic_fmt(format_args!("should not be computing variance of non-free type alias"));
}
};assert!(
2077 tcx.type_alias_is_lazy(def_id),
2078 "should not be computing variance of non-free type alias"
2079 );
2080 }
2081 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:?}"),
2082 }
2083
2084 let ty_predicates = tcx.predicates_of(def_id);
2085 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);
2086 let variances = tcx.variances_of(def_id);
2087
2088 let mut constrained_parameters: FxHashSet<_> = variances
2089 .iter()
2090 .enumerate()
2091 .filter(|&(_, &variance)| variance != ty::Bivariant)
2092 .map(|(index, _)| Parameter(index as u32))
2093 .collect();
2094
2095 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2096
2097 let explicitly_bounded_params = LazyCell::new(|| {
2099 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2100 tcx.hir_node_by_def_id(def_id)
2101 .generics()
2102 .unwrap()
2103 .predicates
2104 .iter()
2105 .filter_map(|predicate| match predicate.kind {
2106 hir::WherePredicateKind::BoundPredicate(predicate) => {
2107 match icx.lower_ty(predicate.bounded_ty).kind() {
2108 ty::Param(data) => Some(Parameter(data.index)),
2109 _ => None,
2110 }
2111 }
2112 _ => None,
2113 })
2114 .collect::<FxHashSet<_>>()
2115 });
2116
2117 for (index, _) in variances.iter().enumerate() {
2118 let parameter = Parameter(index as u32);
2119
2120 if constrained_parameters.contains(¶meter) {
2121 continue;
2122 }
2123
2124 let node = tcx.hir_node_by_def_id(def_id);
2125 let item = node.expect_item();
2126 let hir_generics = node.generics().unwrap();
2127 let hir_param = &hir_generics.params[index];
2128
2129 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2130
2131 if ty_param.def_id != hir_param.def_id.into() {
2132 tcx.dcx().span_delayed_bug(
2140 hir_param.span,
2141 "hir generics and ty generics in different order",
2142 );
2143 continue;
2144 }
2145
2146 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2148 .type_of(def_id)
2149 .instantiate_identity()
2150 .skip_norm_wip()
2151 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2152 {
2153 continue;
2154 }
2155
2156 match hir_param.name {
2157 hir::ParamName::Error(_) => {
2158 }
2161 _ => {
2162 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2163 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2164 }
2165 }
2166 }
2167}
2168
2169struct HasErrorDeep<'tcx> {
2171 tcx: TyCtxt<'tcx>,
2172 seen: FxHashSet<DefId>,
2173}
2174impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2175 type Result = ControlFlow<ErrorGuaranteed>;
2176
2177 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2178 match *ty.kind() {
2179 ty::Adt(def, _) => {
2180 if self.seen.insert(def.did()) {
2181 for field in def.all_fields() {
2182 self.tcx
2183 .type_of(field.did)
2184 .instantiate_identity()
2185 .skip_norm_wip()
2186 .visit_with(self)?;
2187 }
2188 }
2189 }
2190 ty::Error(guar) => return ControlFlow::Break(guar),
2191 _ => {}
2192 }
2193 ty.super_visit_with(self)
2194 }
2195
2196 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2197 if let Err(guar) = r.error_reported() {
2198 ControlFlow::Break(guar)
2199 } else {
2200 ControlFlow::Continue(())
2201 }
2202 }
2203
2204 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2205 if let Err(guar) = c.error_reported() {
2206 ControlFlow::Break(guar)
2207 } else {
2208 ControlFlow::Continue(())
2209 }
2210 }
2211}
2212
2213fn report_bivariance<'tcx>(
2214 tcx: TyCtxt<'tcx>,
2215 param: &'tcx hir::GenericParam<'tcx>,
2216 has_explicit_bounds: bool,
2217 item: &'tcx hir::Item<'tcx>,
2218) -> ErrorGuaranteed {
2219 let param_name = param.name.ident();
2220
2221 let help = match item.kind {
2222 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2223 if let Some(def_id) = tcx.lang_items().phantom_data() {
2224 errors::UnusedGenericParameterHelp::Adt {
2225 param_name,
2226 phantom_data: tcx.def_path_str(def_id),
2227 }
2228 } else {
2229 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2230 }
2231 }
2232 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2233 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:?}"),
2234 };
2235
2236 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2237 intravisit::walk_item(
2238 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2239 item,
2240 );
2241
2242 if !usage_spans.is_empty() {
2243 let item_def_id = item.owner_id.to_def_id();
2247 let is_probably_cyclical =
2248 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2249 .visit_def(item_def_id)
2250 .is_break();
2251 if is_probably_cyclical {
2260 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2261 spans: usage_spans,
2262 param_span: param.span,
2263 param_name,
2264 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2265 help,
2266 note: (),
2267 });
2268 }
2269 }
2270
2271 let const_param_help =
2272 #[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);
2273
2274 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2275 span: param.span,
2276 param_name,
2277 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2278 usage_spans,
2279 help,
2280 const_param_help,
2281 });
2282 diag.code(E0392);
2283 if item.kind.recovered() {
2284 diag.delay_as_bug()
2286 } else {
2287 diag.emit()
2288 }
2289}
2290
2291struct IsProbablyCyclical<'tcx> {
2297 tcx: TyCtxt<'tcx>,
2298 item_def_id: DefId,
2299 seen: FxHashSet<DefId>,
2300}
2301
2302impl<'tcx> IsProbablyCyclical<'tcx> {
2303 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2304 match self.tcx.def_kind(def_id) {
2305 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2306 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2307 self.tcx
2308 .type_of(field.did)
2309 .instantiate_identity()
2310 .skip_norm_wip()
2311 .visit_with(self)
2312 })
2313 }
2314 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2315 self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip().visit_with(self)
2316 }
2317 _ => ControlFlow::Continue(()),
2318 }
2319 }
2320}
2321
2322impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2323 type Result = ControlFlow<(), ()>;
2324
2325 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2326 let def_id = match ty.kind() {
2327 ty::Adt(adt_def, _) => Some(adt_def.did()),
2328 &ty::Alias(ty::AliasTy { kind: ty::Free { def_id }, .. }) => Some(def_id),
2329 _ => None,
2330 };
2331 if let Some(def_id) = def_id {
2332 if def_id == self.item_def_id {
2333 return ControlFlow::Break(());
2334 }
2335 if self.seen.insert(def_id) {
2336 self.visit_def(def_id)?;
2337 }
2338 }
2339 ty.super_visit_with(self)
2340 }
2341}
2342
2343struct CollectUsageSpans<'a> {
2348 spans: &'a mut Vec<Span>,
2349 param_def_id: DefId,
2350}
2351
2352impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2353 type Result = ();
2354
2355 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2356 }
2358
2359 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2360 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2361 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2362 && def_id == self.param_def_id
2363 {
2364 self.spans.push(t.span);
2365 return;
2366 } else if let Res::SelfTyAlias { .. } = qpath.res {
2367 self.spans.push(t.span);
2368 return;
2369 }
2370 }
2371 intravisit::walk_ty(self, t);
2372 }
2373}
2374
2375impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2376 #[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(2378u32),
::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))]
2379 fn check_false_global_bounds(&mut self) {
2380 let tcx = self.ocx.infcx.tcx;
2381 let mut span = tcx.def_span(self.body_def_id);
2382 let empty_env = ty::ParamEnv::empty();
2383
2384 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2385 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2387
2388 for (pred, obligation_span) in implied_obligations {
2389 match pred.kind().skip_binder() {
2390 ty::ClauseKind::WellFormed(..)
2394 | ty::ClauseKind::UnstableFeature(..) => continue,
2396 _ => {}
2397 }
2398
2399 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2401 let pred = self.normalize(span, None, Unnormalized::new_wip(pred));
2402
2403 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2405 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2406 span = predicates
2407 .iter()
2408 .find(|pred| pred.span.contains(obligation_span))
2410 .map(|pred| pred.span)
2411 .unwrap_or(obligation_span);
2412 }
2413
2414 let obligation = Obligation::new(
2415 tcx,
2416 traits::ObligationCause::new(
2417 span,
2418 self.body_def_id,
2419 ObligationCauseCode::TrivialBound,
2420 ),
2421 empty_env,
2422 pred,
2423 );
2424 self.ocx.register_obligation(obligation);
2425 }
2426 }
2427 }
2428}
2429
2430pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2431 let items = tcx.hir_crate_items(());
2432 let res =
2433 items
2434 .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2435 .and(
2436 items.par_impl_items(|item| {
2437 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2438 }),
2439 )
2440 .and(items.par_trait_items(|item| {
2441 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2442 }))
2443 .and(items.par_foreign_items(|item| {
2444 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2445 }))
2446 .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2447 .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2448
2449 super::entry::check_for_entry_fn(tcx)?;
2450
2451 res
2452}
2453
2454fn lint_redundant_lifetimes<'tcx>(
2455 tcx: TyCtxt<'tcx>,
2456 owner_id: LocalDefId,
2457 outlives_env: &OutlivesEnvironment<'tcx>,
2458) {
2459 let def_kind = tcx.def_kind(owner_id);
2460 match def_kind {
2461 DefKind::Struct
2462 | DefKind::Union
2463 | DefKind::Enum
2464 | DefKind::Trait
2465 | DefKind::TraitAlias
2466 | DefKind::Fn
2467 | DefKind::Const { .. }
2468 | DefKind::Impl { of_trait: _ } => {
2469 }
2471 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2472 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2473 return;
2478 }
2479 }
2480 DefKind::Mod
2481 | DefKind::Variant
2482 | DefKind::TyAlias
2483 | DefKind::ForeignTy
2484 | DefKind::TyParam
2485 | DefKind::ConstParam
2486 | DefKind::Static { .. }
2487 | DefKind::Ctor(_, _)
2488 | DefKind::Macro(_)
2489 | DefKind::ExternCrate
2490 | DefKind::Use
2491 | DefKind::ForeignMod
2492 | DefKind::AnonConst
2493 | DefKind::InlineConst
2494 | DefKind::OpaqueTy
2495 | DefKind::Field
2496 | DefKind::LifetimeParam
2497 | DefKind::GlobalAsm
2498 | DefKind::Closure
2499 | DefKind::SyntheticCoroutineBody => return,
2500 }
2501
2502 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];
2511 lifetimes.extend(
2512 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2513 );
2514 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2516 for (idx, var) in tcx
2517 .fn_sig(owner_id)
2518 .instantiate_identity()
2519 .skip_norm_wip()
2520 .bound_vars()
2521 .iter()
2522 .enumerate()
2523 {
2524 let ty::BoundVariableKind::Region(kind) = var else { continue };
2525 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2526 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2527 }
2528 }
2529 lifetimes.retain(|candidate| candidate.is_named(tcx));
2530
2531 let mut shadowed = FxHashSet::default();
2535
2536 for (idx, &candidate) in lifetimes.iter().enumerate() {
2537 if shadowed.contains(&candidate) {
2542 continue;
2543 }
2544
2545 for &victim in &lifetimes[(idx + 1)..] {
2546 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2554 continue;
2555 };
2556
2557 if tcx.parent(def_id) != owner_id.to_def_id() {
2562 continue;
2563 }
2564
2565 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2567 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2568 {
2569 shadowed.insert(victim);
2570 tcx.emit_node_span_lint(
2571 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2572 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2573 tcx.def_span(def_id),
2574 RedundantLifetimeArgsLint { candidate, victim },
2575 );
2576 }
2577 }
2578 }
2579}
2580
2581#[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)]
2582#[diag("unnecessary lifetime parameter `{$victim}`")]
2583#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2584struct RedundantLifetimeArgsLint<'tcx> {
2585 victim: ty::Region<'tcx>,
2587 candidate: ty::Region<'tcx>,
2589}