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().const_param_ty_unchecked() {
860 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
861 wfcx.register_wf_obligation(span, None, ty.into());
862 Ok(())
863 })
864 } else if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
865 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
866 wfcx.register_bound(
867 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
868 wfcx.param_env,
869 ty,
870 tcx.require_lang_item(LangItem::ConstParamTy, span),
871 );
872 Ok(())
873 })
874 } else {
875 let span = || {
876 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
877 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
878 else {
879 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
880 };
881 span
882 };
883 let mut diag = match ty.kind() {
884 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
885 ty::FnPtr(..) => tcx.dcx().struct_span_err(
886 span(),
887 "using function pointers as const generic parameters is forbidden",
888 ),
889 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
890 span(),
891 "using raw pointers as const generic parameters is forbidden",
892 ),
893 _ => {
894 ty.error_reported()?;
896
897 tcx.dcx().struct_span_err(
898 span(),
899 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
900 "`{ty}` is forbidden as the type of a const generic parameter",
901 ),
902 )
903 }
904 };
905
906 diag.note("the only supported types are integers, `bool`, and `char`");
907
908 let cause = ObligationCause::misc(span(), def_id);
909 let adt_const_params_feature_string =
910 " more complex and user defined types".to_string();
911 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
912 tcx,
913 tcx.param_env(param.def_id),
914 ty,
915 cause,
916 ) {
917 Err(
919 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
920 | ConstParamTyImplementationError::NonExhaustive(..)
921 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
922 ) => None,
923 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
924 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params),
(" references to implement the `ConstParamTy` trait".into(),
sym::unsized_const_params)]))vec![
925 (adt_const_params_feature_string, sym::min_adt_const_params),
926 (
927 " references to implement the `ConstParamTy` trait".into(),
928 sym::unsized_const_params,
929 ),
930 ])
931 }
932 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
935 fn ty_is_local(ty: Ty<'_>) -> bool {
936 match ty.kind() {
937 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
938 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
940 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
943 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
946 _ => false,
947 }
948 }
949
950 ty_is_local(ty).then_some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params)]))vec![(
951 adt_const_params_feature_string,
952 sym::min_adt_const_params,
953 )])
954 }
955 Ok(..) => {
957 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params)]))vec![(adt_const_params_feature_string, sym::min_adt_const_params)])
958 }
959 };
960 if let Some(features) = may_suggest_feature {
961 tcx.disabled_nightly_features(&mut diag, features);
962 }
963
964 Err(diag.emit())
965 }
966 }
967 }
968}
969
970#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_associated_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(970u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let loc = Some(WellFormedLoc::Ty(def_id));
enter_wf_checking_ctxt(tcx, def_id,
|wfcx|
{
let item = tcx.associated_item(def_id);
tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
let self_ty =
match item.container {
ty::AssocContainer::Trait => tcx.types.self_param,
ty::AssocContainer::InherentImpl |
ty::AssocContainer::TraitImpl(_) => {
tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
}
};
let span = tcx.def_span(def_id);
match item.kind {
ty::AssocKind::Const { .. } => {
let ty = tcx.type_of(def_id).instantiate_identity();
let ty =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
ty);
wfcx.register_wf_obligation(span, loc, ty.into());
let has_value = item.defaultness(tcx).has_value();
if tcx.is_type_const(def_id) {
check_type_const(wfcx, def_id, ty, has_value)?;
}
if has_value {
let code = ObligationCauseCode::SizedConstOrStatic;
wfcx.register_bound(ObligationCause::new(span, def_id,
code), wfcx.param_env, ty,
tcx.require_lang_item(LangItem::Sized, span));
}
Ok(())
}
ty::AssocKind::Fn { .. } => {
let sig =
tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
let hir_sig =
tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
check_method_receiver(wfcx, hir_sig, item, self_ty)
}
ty::AssocKind::Type { .. } => {
if let ty::AssocContainer::Trait = item.container {
check_associated_type_bounds(wfcx, item, span)
}
if item.defaultness(tcx).has_value() {
let ty = tcx.type_of(def_id).instantiate_identity();
let ty =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
ty);
wfcx.register_wf_obligation(span, loc, ty.into());
}
Ok(())
}
}
})
}
}
}#[instrument(level = "debug", skip(tcx))]
971pub(crate) fn check_associated_item(
972 tcx: TyCtxt<'_>,
973 def_id: LocalDefId,
974) -> Result<(), ErrorGuaranteed> {
975 let loc = Some(WellFormedLoc::Ty(def_id));
976 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
977 let item = tcx.associated_item(def_id);
978
979 tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
982
983 let self_ty = match item.container {
984 ty::AssocContainer::Trait => tcx.types.self_param,
985 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
986 tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
987 }
988 };
989
990 let span = tcx.def_span(def_id);
991
992 match item.kind {
993 ty::AssocKind::Const { .. } => {
994 let ty = tcx.type_of(def_id).instantiate_identity();
995 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
996 wfcx.register_wf_obligation(span, loc, ty.into());
997
998 let has_value = item.defaultness(tcx).has_value();
999 if tcx.is_type_const(def_id) {
1000 check_type_const(wfcx, def_id, ty, has_value)?;
1001 }
1002
1003 if has_value {
1004 let code = ObligationCauseCode::SizedConstOrStatic;
1005 wfcx.register_bound(
1006 ObligationCause::new(span, def_id, code),
1007 wfcx.param_env,
1008 ty,
1009 tcx.require_lang_item(LangItem::Sized, span),
1010 );
1011 }
1012
1013 Ok(())
1014 }
1015 ty::AssocKind::Fn { .. } => {
1016 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1017 let hir_sig =
1018 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
1019 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1020 check_method_receiver(wfcx, hir_sig, item, self_ty)
1021 }
1022 ty::AssocKind::Type { .. } => {
1023 if let ty::AssocContainer::Trait = item.container {
1024 check_associated_type_bounds(wfcx, item, span)
1025 }
1026 if item.defaultness(tcx).has_value() {
1027 let ty = tcx.type_of(def_id).instantiate_identity();
1028 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1029 wfcx.register_wf_obligation(span, loc, ty.into());
1030 }
1031 Ok(())
1032 }
1033 }
1034 })
1035}
1036
1037fn check_type_defn<'tcx>(
1039 tcx: TyCtxt<'tcx>,
1040 item: &hir::Item<'tcx>,
1041 all_sized: bool,
1042) -> Result<(), ErrorGuaranteed> {
1043 tcx.ensure_ok().check_representability(item.owner_id.def_id);
1044 let adt_def = tcx.adt_def(item.owner_id);
1045
1046 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1047 let variants = adt_def.variants();
1048 let packed = adt_def.repr().packed();
1049
1050 for variant in variants.iter() {
1051 for field in &variant.fields {
1053 if let Some(def_id) = field.value
1054 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1055 {
1056 if let Some(def_id) = def_id.as_local()
1059 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1060 && let expr = &tcx.hir_body(anon.body).value
1061 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1062 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1063 {
1064 } else {
1067 let _ = tcx.const_eval_poly(def_id);
1070 }
1071 }
1072 let field_id = field.did.expect_local();
1073 let hir::FieldDef { ty: hir_ty, .. } =
1074 tcx.hir_node_by_def_id(field_id).expect_field();
1075 let ty = wfcx.deeply_normalize(
1076 hir_ty.span,
1077 None,
1078 tcx.type_of(field.did).instantiate_identity(),
1079 );
1080 wfcx.register_wf_obligation(
1081 hir_ty.span,
1082 Some(WellFormedLoc::Ty(field_id)),
1083 ty.into(),
1084 );
1085
1086 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())
1087 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1088 {
1089 tcx.dcx().span_err(
1092 hir_ty.span,
1093 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1094 "scalable vectors cannot be fields of a {}",
1095 adt_def.variant_descr()
1096 ),
1097 );
1098 }
1099 }
1100
1101 let needs_drop_copy = || {
1104 packed && {
1105 let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1106 let ty = tcx.erase_and_anonymize_regions(ty);
1107 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1108 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1109 }
1110 };
1111 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1113 let unsized_len = if all_sized { 0 } else { 1 };
1114 for (idx, field) in
1115 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1116 {
1117 let last = idx == variant.fields.len() - 1;
1118 let field_id = field.did.expect_local();
1119 let hir::FieldDef { ty: hir_ty, .. } =
1120 tcx.hir_node_by_def_id(field_id).expect_field();
1121 let ty = wfcx.normalize(
1122 hir_ty.span,
1123 None,
1124 tcx.type_of(field.did).instantiate_identity(),
1125 );
1126 wfcx.register_bound(
1127 traits::ObligationCause::new(
1128 hir_ty.span,
1129 wfcx.body_def_id,
1130 ObligationCauseCode::FieldSized {
1131 adt_kind: match &item.kind {
1132 ItemKind::Struct(..) => AdtKind::Struct,
1133 ItemKind::Union(..) => AdtKind::Union,
1134 ItemKind::Enum(..) => AdtKind::Enum,
1135 kind => ::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("should be wfchecking an ADT, got {0:?}", kind))span_bug!(
1136 item.span,
1137 "should be wfchecking an ADT, got {kind:?}"
1138 ),
1139 },
1140 span: hir_ty.span,
1141 last,
1142 },
1143 ),
1144 wfcx.param_env,
1145 ty,
1146 tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1147 );
1148 }
1149
1150 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1152 match tcx.const_eval_poly(discr_def_id) {
1153 Ok(_) => {}
1154 Err(ErrorHandled::Reported(..)) => {}
1155 Err(ErrorHandled::TooGeneric(sp)) => {
1156 ::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")
1157 }
1158 }
1159 }
1160 }
1161
1162 check_where_clauses(wfcx, item.owner_id.def_id);
1163 Ok(())
1164 })
1165}
1166
1167#[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(1167u32),
::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:1169",
"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(1169u32),
::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))]
1168fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1169 debug!(?item.owner_id);
1170
1171 let def_id = item.owner_id.def_id;
1172 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1173 return Ok(());
1175 }
1176
1177 let trait_def = tcx.trait_def(def_id);
1178 if trait_def.is_marker
1179 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1180 {
1181 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1182 struct_span_code_err!(
1183 tcx.dcx(),
1184 tcx.def_span(*associated_def_id),
1185 E0714,
1186 "marker traits cannot have associated items",
1187 )
1188 .emit();
1189 }
1190 }
1191
1192 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1193 check_where_clauses(wfcx, def_id);
1194 Ok(())
1195 });
1196
1197 if let hir::ItemKind::Trait { .. } = item.kind {
1199 check_gat_where_clauses(tcx, item.owner_id.def_id);
1200 }
1201 res
1202}
1203
1204fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1209 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1210
1211 {
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:1211",
"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(1211u32),
::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);
1212 let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1213 |(bound, bound_span)| {
1214 traits::wf::clause_obligations(
1215 wfcx.infcx,
1216 wfcx.param_env,
1217 wfcx.body_def_id,
1218 bound,
1219 bound_span,
1220 )
1221 },
1222 );
1223
1224 wfcx.register_obligations(wf_obligations);
1225}
1226
1227fn check_item_fn(
1228 tcx: TyCtxt<'_>,
1229 def_id: LocalDefId,
1230 decl: &hir::FnDecl<'_>,
1231) -> Result<(), ErrorGuaranteed> {
1232 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1233 check_eiis_fn(tcx, def_id);
1234
1235 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1236 check_fn_or_method(wfcx, sig, decl, def_id);
1237 Ok(())
1238 })
1239}
1240
1241fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1242 for EiiImpl { resolution, span, .. } in
1245 {
{
'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()
1246 {
1247 let (foreign_item, name) = match resolution {
1248 EiiImplResolution::Macro(def_id) => {
1249 if let Some(foreign_item) =
1252 {
{
'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)
1253 {
1254 (foreign_item, tcx.item_name(*def_id))
1255 } else {
1256 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1257 continue;
1258 }
1259 }
1260 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1261 EiiImplResolution::Error(_eg) => continue,
1262 };
1263
1264 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1265 }
1266}
1267
1268fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1269 for EiiImpl { resolution, span, .. } in
1272 {
{
'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()
1273 {
1274 let (foreign_item, name) = match resolution {
1275 EiiImplResolution::Macro(def_id) => {
1276 if let Some(foreign_item) =
1279 {
{
'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)
1280 {
1281 (foreign_item, tcx.item_name(*def_id))
1282 } else {
1283 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1284 continue;
1285 }
1286 }
1287 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1288 EiiImplResolution::Error(_eg) => continue,
1289 };
1290
1291 let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1292 }
1293}
1294
1295#[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(1295u32),
::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))]
1296pub(crate) fn check_static_item<'tcx>(
1297 tcx: TyCtxt<'tcx>,
1298 item_id: LocalDefId,
1299 ty: Ty<'tcx>,
1300 should_check_for_sync: bool,
1301) -> Result<(), ErrorGuaranteed> {
1302 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1303 if should_check_for_sync {
1304 check_eiis_static(tcx, item_id, ty);
1305 }
1306
1307 let span = tcx.ty_span(item_id);
1308 let loc = Some(WellFormedLoc::Ty(item_id));
1309 let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1310
1311 let is_foreign_item = tcx.is_foreign_item(item_id);
1312 let is_structurally_foreign_item = || {
1313 let tail = tcx.struct_tail_raw(
1314 item_ty,
1315 &ObligationCause::dummy(),
1316 |ty| wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty)),
1317 || {},
1318 );
1319
1320 matches!(tail.kind(), ty::Foreign(_))
1321 };
1322 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1323
1324 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1325 if forbid_unsized {
1326 let span = tcx.def_span(item_id);
1327 wfcx.register_bound(
1328 traits::ObligationCause::new(
1329 span,
1330 wfcx.body_def_id,
1331 ObligationCauseCode::SizedConstOrStatic,
1332 ),
1333 wfcx.param_env,
1334 item_ty,
1335 tcx.require_lang_item(LangItem::Sized, span),
1336 );
1337 }
1338
1339 let should_check_for_sync = should_check_for_sync
1341 && !is_foreign_item
1342 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1343 && !tcx.is_thread_local_static(item_id.to_def_id());
1344
1345 if should_check_for_sync {
1346 wfcx.register_bound(
1347 traits::ObligationCause::new(
1348 span,
1349 wfcx.body_def_id,
1350 ObligationCauseCode::SharedStatic,
1351 ),
1352 wfcx.param_env,
1353 item_ty,
1354 tcx.require_lang_item(LangItem::Sync, span),
1355 );
1356 }
1357 Ok(())
1358 })
1359}
1360
1361#[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(1361u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["def_id", "item_ty",
"has_value"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&has_value as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = wfcx.tcx();
let span = tcx.def_span(def_id);
if !tcx.features().const_param_ty_unchecked() {
wfcx.register_bound(ObligationCause::new(span, def_id,
ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
item_ty,
tcx.require_lang_item(LangItem::ConstParamTy, span));
}
if has_value {
let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
let norm_ct =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
raw_ct);
wfcx.register_wf_obligation(span,
Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
wfcx.register_obligation(Obligation::new(tcx,
ObligationCause::new(span, def_id,
ObligationCauseCode::WellFormed(None)), wfcx.param_env,
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct,
item_ty))));
}
Ok(())
}
}
}#[instrument(level = "debug", skip(wfcx))]
1362pub(super) fn check_type_const<'tcx>(
1363 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1364 def_id: LocalDefId,
1365 item_ty: Ty<'tcx>,
1366 has_value: bool,
1367) -> Result<(), ErrorGuaranteed> {
1368 let tcx = wfcx.tcx();
1369 let span = tcx.def_span(def_id);
1370
1371 if !tcx.features().const_param_ty_unchecked() {
1372 wfcx.register_bound(
1373 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1374 wfcx.param_env,
1375 item_ty,
1376 tcx.require_lang_item(LangItem::ConstParamTy, span),
1377 );
1378 }
1379
1380 if has_value {
1381 let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1382 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1383 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1384
1385 wfcx.register_obligation(Obligation::new(
1386 tcx,
1387 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1388 wfcx.param_env,
1389 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1390 ));
1391 }
1392 Ok(())
1393}
1394
1395#[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(1395u32),
::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:1467",
"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(1467u32),
::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_))]
1396fn check_impl<'tcx>(
1397 tcx: TyCtxt<'tcx>,
1398 item: &'tcx hir::Item<'tcx>,
1399 impl_: &hir::Impl<'_>,
1400) -> Result<(), ErrorGuaranteed> {
1401 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1402 match impl_.of_trait {
1403 Some(of_trait) => {
1404 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1408 tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1411 let trait_span = of_trait.trait_ref.path.span;
1412 let trait_ref = wfcx.deeply_normalize(
1413 trait_span,
1414 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1415 trait_ref,
1416 );
1417 let trait_pred =
1418 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1419 let mut obligations = traits::wf::trait_obligations(
1420 wfcx.infcx,
1421 wfcx.param_env,
1422 wfcx.body_def_id,
1423 trait_pred,
1424 trait_span,
1425 item,
1426 );
1427 for obligation in &mut obligations {
1428 if obligation.cause.span != trait_span {
1429 continue;
1431 }
1432 if let Some(pred) = obligation.predicate.as_trait_clause()
1433 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1434 {
1435 obligation.cause.span = impl_.self_ty.span;
1436 }
1437 if let Some(pred) = obligation.predicate.as_projection_clause()
1438 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1439 {
1440 obligation.cause.span = impl_.self_ty.span;
1441 }
1442 }
1443
1444 if tcx.is_conditionally_const(item.owner_id.def_id) {
1446 for (bound, _) in
1447 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1448 {
1449 let bound = wfcx.normalize(
1450 item.span,
1451 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1452 bound,
1453 );
1454 wfcx.register_obligation(Obligation::new(
1455 tcx,
1456 ObligationCause::new(
1457 impl_.self_ty.span,
1458 wfcx.body_def_id,
1459 ObligationCauseCode::WellFormed(None),
1460 ),
1461 wfcx.param_env,
1462 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1463 ))
1464 }
1465 }
1466
1467 debug!(?obligations);
1468 wfcx.register_obligations(obligations);
1469 }
1470 None => {
1471 let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1472 let self_ty = wfcx.deeply_normalize(
1473 item.span,
1474 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1475 Unnormalized::new_wip(self_ty),
1476 );
1477 wfcx.register_wf_obligation(
1478 impl_.self_ty.span,
1479 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1480 self_ty.into(),
1481 );
1482 }
1483 }
1484
1485 check_where_clauses(wfcx, item.owner_id.def_id);
1486 Ok(())
1487 })
1488}
1489
1490#[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(1491u32),
::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))]
1492pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1493 let infcx = wfcx.infcx;
1494 let tcx = wfcx.tcx();
1495
1496 let predicates = tcx.predicates_of(def_id.to_def_id());
1497 let generics = tcx.generics_of(def_id);
1498
1499 for param in &generics.own_params {
1506 if let Some(default) = param
1507 .default_value(tcx)
1508 .map(ty::EarlyBinder::instantiate_identity)
1509 .map(Unnormalized::skip_norm_wip)
1510 {
1511 if !default.has_param() {
1518 wfcx.register_wf_obligation(
1519 tcx.def_span(param.def_id),
1520 matches!(param.kind, GenericParamDefKind::Type { .. })
1521 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1522 default.as_term().unwrap(),
1523 );
1524 } else {
1525 let GenericArgKind::Const(ct) = default.kind() else {
1528 continue;
1529 };
1530
1531 let ct_ty = match ct.kind() {
1532 ty::ConstKind::Infer(_)
1533 | ty::ConstKind::Placeholder(_)
1534 | ty::ConstKind::Bound(_, _) => unreachable!(),
1535 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1536 ty::ConstKind::Value(cv) => cv.ty,
1537 ty::ConstKind::Unevaluated(uv) => {
1538 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args).skip_norm_wip()
1539 }
1540 ty::ConstKind::Param(param_ct) => {
1541 param_ct.find_const_ty_from_env(wfcx.param_env)
1542 }
1543 };
1544
1545 let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1546 if !ct_ty.has_param() && !param_ty.has_param() {
1547 let cause = traits::ObligationCause::new(
1548 tcx.def_span(param.def_id),
1549 wfcx.body_def_id,
1550 ObligationCauseCode::WellFormed(None),
1551 );
1552 wfcx.register_obligation(Obligation::new(
1553 tcx,
1554 cause,
1555 wfcx.param_env,
1556 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1557 ));
1558 }
1559 }
1560 }
1561 }
1562
1563 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1572 if param.index >= generics.parent_count as u32
1573 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1575 && !default.has_param()
1577 {
1578 return default;
1580 }
1581 tcx.mk_param_from_def(param)
1582 });
1583
1584 let default_obligations = predicates
1586 .predicates
1587 .iter()
1588 .flat_map(|&(pred, sp)| {
1589 #[derive(Default)]
1590 struct CountParams {
1591 params: FxHashSet<u32>,
1592 }
1593 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1594 type Result = ControlFlow<()>;
1595 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1596 if let ty::Param(param) = t.kind() {
1597 self.params.insert(param.index);
1598 }
1599 t.super_visit_with(self)
1600 }
1601
1602 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1603 ControlFlow::Break(())
1604 }
1605
1606 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1607 if let ty::ConstKind::Param(param) = c.kind() {
1608 self.params.insert(param.index);
1609 }
1610 c.super_visit_with(self)
1611 }
1612 }
1613 let mut param_count = CountParams::default();
1614 let has_region = pred.visit_with(&mut param_count).is_break();
1615 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1616 if instantiated_pred.skip_normalization().has_non_region_param()
1619 || param_count.params.len() > 1
1620 || has_region
1621 {
1622 None
1623 } else if predicates
1624 .predicates
1625 .iter()
1626 .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_pred)
1627 {
1628 None
1630 } else {
1631 Some((instantiated_pred, sp))
1632 }
1633 })
1634 .map(|(pred, sp)| {
1635 let pred = wfcx.normalize(sp, None, pred);
1645 let cause = traits::ObligationCause::new(
1646 sp,
1647 wfcx.body_def_id,
1648 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1649 );
1650 Obligation::new(tcx, cause, wfcx.param_env, pred)
1651 });
1652
1653 let predicates = predicates.instantiate_identity(tcx);
1654
1655 let assoc_const_obligations: Vec<_> = predicates
1656 .predicates
1657 .iter()
1658 .copied()
1659 .zip(predicates.spans.iter().copied())
1660 .filter_map(|(clause, sp)| {
1661 let clause = clause.skip_norm_wip();
1662 let proj = clause.as_projection_clause()?;
1663 let pred_binder = proj
1664 .map_bound(|pred| {
1665 pred.term.as_const().map(|ct| {
1666 let assoc_const_ty = tcx
1667 .type_of(pred.projection_term.def_id())
1668 .instantiate(tcx, pred.projection_term.args)
1669 .skip_norm_wip();
1670 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1671 })
1672 })
1673 .transpose();
1674 pred_binder.map(|pred_binder| {
1675 let cause = traits::ObligationCause::new(
1676 sp,
1677 wfcx.body_def_id,
1678 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1679 );
1680 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1681 })
1682 })
1683 .collect();
1684
1685 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1686 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1687 traits::wf::clause_obligations(
1688 infcx,
1689 wfcx.param_env,
1690 wfcx.body_def_id,
1691 p.skip_norm_wip(),
1692 sp,
1693 )
1694 });
1695 let obligations: Vec<_> =
1696 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1697 wfcx.register_obligations(obligations);
1698}
1699
1700#[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(1700u32),
::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))]
1701fn check_fn_or_method<'tcx>(
1702 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1703 sig: ty::PolyFnSig<'tcx>,
1704 hir_decl: &hir::FnDecl<'_>,
1705 def_id: LocalDefId,
1706) {
1707 let tcx = wfcx.tcx();
1708 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1709
1710 let arg_span =
1716 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1717
1718 sig.inputs_and_output =
1719 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1720 wfcx.deeply_normalize(
1721 arg_span(idx),
1722 Some(WellFormedLoc::Param {
1723 function: def_id,
1724 param_idx: idx,
1727 }),
1728 Unnormalized::new_wip(ty),
1729 )
1730 }));
1731
1732 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1733 wfcx.register_wf_obligation(
1734 arg_span(idx),
1735 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1736 ty.into(),
1737 );
1738 }
1739
1740 check_where_clauses(wfcx, def_id);
1741
1742 if sig.abi() == ExternAbi::RustCall {
1743 let span = tcx.def_span(def_id);
1744 let has_implicit_self = hir_decl.implicit_self() != hir::ImplicitSelfKind::None;
1745 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1746 if let Some(ty) = inputs.next() {
1748 wfcx.register_bound(
1749 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1750 wfcx.param_env,
1751 *ty,
1752 tcx.require_lang_item(hir::LangItem::Tuple, span),
1753 );
1754 wfcx.register_bound(
1755 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1756 wfcx.param_env,
1757 *ty,
1758 tcx.require_lang_item(hir::LangItem::Sized, span),
1759 );
1760 } else {
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 if inputs.next().is_some() {
1768 tcx.dcx().span_err(
1769 hir_decl.inputs.last().map_or(span, |input| input.span),
1770 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1771 );
1772 }
1773 }
1774
1775 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1777 let span = match hir_decl.output {
1778 hir::FnRetTy::Return(ty) => ty.span,
1779 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1780 };
1781
1782 wfcx.register_bound(
1783 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1784 wfcx.param_env,
1785 sig.output(),
1786 tcx.require_lang_item(LangItem::Sized, span),
1787 );
1788 }
1789}
1790
1791#[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)]
1793enum ArbitrarySelfTypesLevel {
1794 Basic, WithPointers, }
1797
1798#[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(1798u32),
::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:1818",
"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(1818u32),
::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))]
1799fn check_method_receiver<'tcx>(
1800 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1801 fn_sig: &hir::FnSig<'_>,
1802 method: ty::AssocItem,
1803 self_ty: Ty<'tcx>,
1804) -> Result<(), ErrorGuaranteed> {
1805 let tcx = wfcx.tcx();
1806
1807 if !method.is_method() {
1808 return Ok(());
1809 }
1810
1811 let span = fn_sig.decl.inputs[0].span;
1812 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1813
1814 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1815 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1816 let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1817
1818 debug!("check_method_receiver: sig={:?}", sig);
1819
1820 let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1821
1822 let receiver_ty = sig.inputs()[0];
1823 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1824
1825 receiver_ty.error_reported()?;
1828
1829 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1830 Some(ArbitrarySelfTypesLevel::WithPointers)
1831 } else if tcx.features().arbitrary_self_types() {
1832 Some(ArbitrarySelfTypesLevel::Basic)
1833 } else {
1834 None
1835 };
1836 let generics = tcx.generics_of(method.def_id);
1837
1838 let receiver_validity =
1839 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1840 if let Err(receiver_validity_err) = receiver_validity {
1841 return Err(match arbitrary_self_types_level {
1842 None if receiver_is_valid(
1846 wfcx,
1847 span,
1848 receiver_ty,
1849 self_ty,
1850 Some(ArbitrarySelfTypesLevel::Basic),
1851 generics,
1852 )
1853 .is_ok() =>
1854 {
1855 feature_err(
1857 &tcx.sess,
1858 sym::arbitrary_self_types,
1859 span,
1860 format!(
1861 "`{receiver_ty}` cannot be used as the type of `self` without \
1862 the `arbitrary_self_types` feature",
1863 ),
1864 )
1865 .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>`"))
1866 .emit()
1867 }
1868 None | Some(ArbitrarySelfTypesLevel::Basic)
1869 if receiver_is_valid(
1870 wfcx,
1871 span,
1872 receiver_ty,
1873 self_ty,
1874 Some(ArbitrarySelfTypesLevel::WithPointers),
1875 generics,
1876 )
1877 .is_ok() =>
1878 {
1879 feature_err(
1881 &tcx.sess,
1882 sym::arbitrary_self_types_pointers,
1883 span,
1884 format!(
1885 "`{receiver_ty}` cannot be used as the type of `self` without \
1886 the `arbitrary_self_types_pointers` feature",
1887 ),
1888 )
1889 .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>`"))
1890 .emit()
1891 }
1892 _ =>
1893 {
1895 match receiver_validity_err {
1896 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1897 let hint = match receiver_ty
1898 .builtin_deref(false)
1899 .unwrap_or(receiver_ty)
1900 .ty_adt_def()
1901 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1902 {
1903 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1904 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1905 _ => None,
1906 };
1907
1908 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1909 }
1910 ReceiverValidityError::DoesNotDeref => {
1911 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1912 span,
1913 receiver_ty,
1914 })
1915 }
1916 ReceiverValidityError::MethodGenericParamUsed => {
1917 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1918 }
1919 }
1920 }
1921 });
1922 }
1923 Ok(())
1924}
1925
1926enum ReceiverValidityError {
1930 DoesNotDeref,
1933 MethodGenericParamUsed,
1935}
1936
1937fn confirm_type_is_not_a_method_generic_param(
1940 ty: Ty<'_>,
1941 method_generics: &ty::Generics,
1942) -> Result<(), ReceiverValidityError> {
1943 if let ty::Param(param) = ty.kind() {
1944 if (param.index as usize) >= method_generics.parent_count {
1945 return Err(ReceiverValidityError::MethodGenericParamUsed);
1946 }
1947 }
1948 Ok(())
1949}
1950
1951fn receiver_is_valid<'tcx>(
1961 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1962 span: Span,
1963 receiver_ty: Ty<'tcx>,
1964 self_ty: Ty<'tcx>,
1965 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1966 method_generics: &ty::Generics,
1967) -> Result<(), ReceiverValidityError> {
1968 let infcx = wfcx.infcx;
1969 let tcx = wfcx.tcx();
1970 let cause =
1971 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1972
1973 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1975 let ocx = ObligationCtxt::new(wfcx.infcx);
1976 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1977 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1978 Ok(())
1979 } else {
1980 Err(NoSolution)
1981 }
1982 }) {
1983 return Ok(());
1984 }
1985
1986 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1987
1988 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1989
1990 if arbitrary_self_types_enabled.is_some() {
1994 autoderef = autoderef.use_receiver_trait();
1995 }
1996
1997 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1999 autoderef = autoderef.include_raw_pointers();
2000 }
2001
2002 while let Some((potential_self_ty, _)) = autoderef.next() {
2004 {
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:2004",
"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(2004u32),
::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!(
2005 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
2006 potential_self_ty, self_ty
2007 );
2008
2009 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
2010
2011 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
2014 let ocx = ObligationCtxt::new(wfcx.infcx);
2015 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
2016 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
2017 Ok(())
2018 } else {
2019 Err(NoSolution)
2020 }
2021 }) {
2022 wfcx.register_obligations(autoderef.into_obligations());
2023 return Ok(());
2024 }
2025
2026 if arbitrary_self_types_enabled.is_none() {
2029 let legacy_receiver_trait_def_id =
2030 tcx.require_lang_item(LangItem::LegacyReceiver, span);
2031 if !legacy_receiver_is_implemented(
2032 wfcx,
2033 legacy_receiver_trait_def_id,
2034 cause.clone(),
2035 potential_self_ty,
2036 ) {
2037 break;
2039 }
2040
2041 wfcx.register_bound(
2043 cause.clone(),
2044 wfcx.param_env,
2045 potential_self_ty,
2046 legacy_receiver_trait_def_id,
2047 );
2048 }
2049 }
2050
2051 {
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:2051",
"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(2051u32),
::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);
2052 Err(ReceiverValidityError::DoesNotDeref)
2053}
2054
2055fn legacy_receiver_is_implemented<'tcx>(
2056 wfcx: &WfCheckingCtxt<'_, 'tcx>,
2057 legacy_receiver_trait_def_id: DefId,
2058 cause: ObligationCause<'tcx>,
2059 receiver_ty: Ty<'tcx>,
2060) -> bool {
2061 let tcx = wfcx.tcx();
2062 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2063
2064 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2065
2066 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2067 true
2068 } else {
2069 {
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:2069",
"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(2069u32),
::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!(
2070 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2071 receiver_ty
2072 );
2073 false
2074 }
2075}
2076
2077pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2078 match tcx.def_kind(def_id) {
2079 DefKind::Enum | DefKind::Struct | DefKind::Union => {
2080 }
2082 DefKind::TyAlias => {
2083 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!(
2084 tcx.type_alias_is_lazy(def_id),
2085 "should not be computing variance of non-free type alias"
2086 );
2087 }
2088 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:?}"),
2089 }
2090
2091 let ty_predicates = tcx.predicates_of(def_id);
2092 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);
2093 let variances = tcx.variances_of(def_id);
2094
2095 let mut constrained_parameters: FxHashSet<_> = variances
2096 .iter()
2097 .enumerate()
2098 .filter(|&(_, &variance)| variance != ty::Bivariant)
2099 .map(|(index, _)| Parameter(index as u32))
2100 .collect();
2101
2102 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2103
2104 let explicitly_bounded_params = LazyCell::new(|| {
2106 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2107 tcx.hir_node_by_def_id(def_id)
2108 .generics()
2109 .unwrap()
2110 .predicates
2111 .iter()
2112 .filter_map(|predicate| match predicate.kind {
2113 hir::WherePredicateKind::BoundPredicate(predicate) => {
2114 match icx.lower_ty(predicate.bounded_ty).kind() {
2115 ty::Param(data) => Some(Parameter(data.index)),
2116 _ => None,
2117 }
2118 }
2119 _ => None,
2120 })
2121 .collect::<FxHashSet<_>>()
2122 });
2123
2124 for (index, _) in variances.iter().enumerate() {
2125 let parameter = Parameter(index as u32);
2126
2127 if constrained_parameters.contains(¶meter) {
2128 continue;
2129 }
2130
2131 let node = tcx.hir_node_by_def_id(def_id);
2132 let item = node.expect_item();
2133 let hir_generics = node.generics().unwrap();
2134 let hir_param = &hir_generics.params[index];
2135
2136 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2137
2138 if ty_param.def_id != hir_param.def_id.into() {
2139 tcx.dcx().span_delayed_bug(
2147 hir_param.span,
2148 "hir generics and ty generics in different order",
2149 );
2150 continue;
2151 }
2152
2153 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2155 .type_of(def_id)
2156 .instantiate_identity()
2157 .skip_norm_wip()
2158 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2159 {
2160 continue;
2161 }
2162
2163 match hir_param.name {
2164 hir::ParamName::Error(_) => {
2165 }
2168 _ => {
2169 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2170 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2171 }
2172 }
2173 }
2174}
2175
2176struct HasErrorDeep<'tcx> {
2178 tcx: TyCtxt<'tcx>,
2179 seen: FxHashSet<DefId>,
2180}
2181impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2182 type Result = ControlFlow<ErrorGuaranteed>;
2183
2184 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2185 match *ty.kind() {
2186 ty::Adt(def, _) => {
2187 if self.seen.insert(def.did()) {
2188 for field in def.all_fields() {
2189 self.tcx
2190 .type_of(field.did)
2191 .instantiate_identity()
2192 .skip_norm_wip()
2193 .visit_with(self)?;
2194 }
2195 }
2196 }
2197 ty::Error(guar) => return ControlFlow::Break(guar),
2198 _ => {}
2199 }
2200 ty.super_visit_with(self)
2201 }
2202
2203 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2204 if let Err(guar) = r.error_reported() {
2205 ControlFlow::Break(guar)
2206 } else {
2207 ControlFlow::Continue(())
2208 }
2209 }
2210
2211 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2212 if let Err(guar) = c.error_reported() {
2213 ControlFlow::Break(guar)
2214 } else {
2215 ControlFlow::Continue(())
2216 }
2217 }
2218}
2219
2220fn report_bivariance<'tcx>(
2221 tcx: TyCtxt<'tcx>,
2222 param: &'tcx hir::GenericParam<'tcx>,
2223 has_explicit_bounds: bool,
2224 item: &'tcx hir::Item<'tcx>,
2225) -> ErrorGuaranteed {
2226 let param_name = param.name.ident();
2227
2228 let help = match item.kind {
2229 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2230 if let Some(def_id) = tcx.lang_items().phantom_data() {
2231 errors::UnusedGenericParameterHelp::Adt {
2232 param_name,
2233 phantom_data: tcx.def_path_str(def_id),
2234 }
2235 } else {
2236 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2237 }
2238 }
2239 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2240 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:?}"),
2241 };
2242
2243 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2244 intravisit::walk_item(
2245 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2246 item,
2247 );
2248
2249 if !usage_spans.is_empty() {
2250 let item_def_id = item.owner_id.to_def_id();
2254 let is_probably_cyclical =
2255 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2256 .visit_def(item_def_id)
2257 .is_break();
2258 if is_probably_cyclical {
2267 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2268 spans: usage_spans,
2269 param_span: param.span,
2270 param_name,
2271 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2272 help,
2273 note: (),
2274 });
2275 }
2276 }
2277
2278 let const_param_help =
2279 #[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);
2280
2281 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2282 span: param.span,
2283 param_name,
2284 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2285 usage_spans,
2286 help,
2287 const_param_help,
2288 });
2289 diag.code(E0392);
2290 if item.kind.recovered() {
2291 diag.delay_as_bug()
2293 } else {
2294 diag.emit()
2295 }
2296}
2297
2298struct IsProbablyCyclical<'tcx> {
2304 tcx: TyCtxt<'tcx>,
2305 item_def_id: DefId,
2306 seen: FxHashSet<DefId>,
2307}
2308
2309impl<'tcx> IsProbablyCyclical<'tcx> {
2310 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2311 match self.tcx.def_kind(def_id) {
2312 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2313 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2314 self.tcx
2315 .type_of(field.did)
2316 .instantiate_identity()
2317 .skip_norm_wip()
2318 .visit_with(self)
2319 })
2320 }
2321 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2322 self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip().visit_with(self)
2323 }
2324 _ => ControlFlow::Continue(()),
2325 }
2326 }
2327}
2328
2329impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2330 type Result = ControlFlow<(), ()>;
2331
2332 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2333 let def_id = match ty.kind() {
2334 ty::Adt(adt_def, _) => Some(adt_def.did()),
2335 &ty::Alias(ty::AliasTy { kind: ty::Free { def_id }, .. }) => Some(def_id),
2336 _ => None,
2337 };
2338 if let Some(def_id) = def_id {
2339 if def_id == self.item_def_id {
2340 return ControlFlow::Break(());
2341 }
2342 if self.seen.insert(def_id) {
2343 self.visit_def(def_id)?;
2344 }
2345 }
2346 ty.super_visit_with(self)
2347 }
2348}
2349
2350struct CollectUsageSpans<'a> {
2355 spans: &'a mut Vec<Span>,
2356 param_def_id: DefId,
2357}
2358
2359impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2360 type Result = ();
2361
2362 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2363 }
2365
2366 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2367 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2368 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2369 && def_id == self.param_def_id
2370 {
2371 self.spans.push(t.span);
2372 return;
2373 } else if let Res::SelfTyAlias { .. } = qpath.res {
2374 self.spans.push(t.span);
2375 return;
2376 }
2377 }
2378 intravisit::walk_ty(self, t);
2379 }
2380}
2381
2382impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2383 #[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(2385u32),
::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))]
2386 fn check_false_global_bounds(&mut self) {
2387 let tcx = self.ocx.infcx.tcx;
2388 let mut span = tcx.def_span(self.body_def_id);
2389 let empty_env = ty::ParamEnv::empty();
2390
2391 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2392 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2394
2395 for (pred, obligation_span) in implied_obligations {
2396 match pred.kind().skip_binder() {
2397 ty::ClauseKind::WellFormed(..)
2401 | ty::ClauseKind::UnstableFeature(..) => continue,
2403 _ => {}
2404 }
2405
2406 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2408 let pred = self.normalize(span, None, Unnormalized::new_wip(pred));
2409
2410 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2412 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2413 span = predicates
2414 .iter()
2415 .find(|pred| pred.span.contains(obligation_span))
2417 .map(|pred| pred.span)
2418 .unwrap_or(obligation_span);
2419 }
2420
2421 let obligation = Obligation::new(
2422 tcx,
2423 traits::ObligationCause::new(
2424 span,
2425 self.body_def_id,
2426 ObligationCauseCode::TrivialBound,
2427 ),
2428 empty_env,
2429 pred,
2430 );
2431 self.ocx.register_obligation(obligation);
2432 }
2433 }
2434 }
2435}
2436
2437pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2438 let items = tcx.hir_crate_items(());
2439 let res =
2440 items
2441 .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2442 .and(
2443 items.par_impl_items(|item| {
2444 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2445 }),
2446 )
2447 .and(items.par_trait_items(|item| {
2448 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2449 }))
2450 .and(items.par_foreign_items(|item| {
2451 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2452 }))
2453 .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2454 .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2455
2456 super::entry::check_for_entry_fn(tcx)?;
2457
2458 res
2459}
2460
2461fn lint_redundant_lifetimes<'tcx>(
2462 tcx: TyCtxt<'tcx>,
2463 owner_id: LocalDefId,
2464 outlives_env: &OutlivesEnvironment<'tcx>,
2465) {
2466 let def_kind = tcx.def_kind(owner_id);
2467 match def_kind {
2468 DefKind::Struct
2469 | DefKind::Union
2470 | DefKind::Enum
2471 | DefKind::Trait
2472 | DefKind::TraitAlias
2473 | DefKind::Fn
2474 | DefKind::Const { .. }
2475 | DefKind::Impl { of_trait: _ } => {
2476 }
2478 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2479 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2480 return;
2485 }
2486 }
2487 DefKind::Mod
2488 | DefKind::Variant
2489 | DefKind::TyAlias
2490 | DefKind::ForeignTy
2491 | DefKind::TyParam
2492 | DefKind::ConstParam
2493 | DefKind::Static { .. }
2494 | DefKind::Ctor(_, _)
2495 | DefKind::Macro(_)
2496 | DefKind::ExternCrate
2497 | DefKind::Use
2498 | DefKind::ForeignMod
2499 | DefKind::AnonConst
2500 | DefKind::InlineConst
2501 | DefKind::OpaqueTy
2502 | DefKind::Field
2503 | DefKind::LifetimeParam
2504 | DefKind::GlobalAsm
2505 | DefKind::Closure
2506 | DefKind::SyntheticCoroutineBody => return,
2507 }
2508
2509 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];
2518 lifetimes.extend(
2519 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2520 );
2521 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2523 for (idx, var) in tcx
2524 .fn_sig(owner_id)
2525 .instantiate_identity()
2526 .skip_norm_wip()
2527 .bound_vars()
2528 .iter()
2529 .enumerate()
2530 {
2531 let ty::BoundVariableKind::Region(kind) = var else { continue };
2532 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2533 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2534 }
2535 }
2536 lifetimes.retain(|candidate| candidate.is_named(tcx));
2537
2538 let mut shadowed = FxHashSet::default();
2542
2543 for (idx, &candidate) in lifetimes.iter().enumerate() {
2544 if shadowed.contains(&candidate) {
2549 continue;
2550 }
2551
2552 for &victim in &lifetimes[(idx + 1)..] {
2553 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2561 continue;
2562 };
2563
2564 if tcx.parent(def_id) != owner_id.to_def_id() {
2569 continue;
2570 }
2571
2572 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2574 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2575 {
2576 shadowed.insert(victim);
2577 tcx.emit_node_span_lint(
2578 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2579 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2580 tcx.def_span(def_id),
2581 RedundantLifetimeArgsLint { candidate, victim },
2582 );
2583 }
2584 }
2585 }
2586}
2587
2588#[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)]
2589#[diag("unnecessary lifetime parameter `{$victim}`")]
2590#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2591struct RedundantLifetimeArgsLint<'tcx> {
2592 victim: ty::Region<'tcx>,
2594 candidate: ty::Region<'tcx>,
2596}