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::parse::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 );
732 })
733}
734
735fn test_region_obligations<'tcx>(
739 tcx: TyCtxt<'tcx>,
740 id: LocalDefId,
741 param_env: ty::ParamEnv<'tcx>,
742 wf_tys: &FxIndexSet<Ty<'tcx>>,
743 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
744) -> bool {
745 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
749
750 add_constraints(&infcx);
751
752 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
753 {
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:753",
"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(753u32),
::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");
754
755 errors.is_empty()
758}
759
760struct GATArgsCollector<'tcx> {
765 gat: DefId,
766 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
768 types: FxIndexSet<(Ty<'tcx>, usize)>,
770}
771
772impl<'tcx> GATArgsCollector<'tcx> {
773 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
774 gat: DefId,
775 t: T,
776 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
777 let mut visitor =
778 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
779 t.visit_with(&mut visitor);
780 (visitor.regions, visitor.types)
781 }
782}
783
784impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
785 fn visit_ty(&mut self, t: Ty<'tcx>) {
786 match t.kind() {
787 &ty::Alias(ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
788 if def_id == self.gat =>
789 {
790 for (idx, arg) in args.iter().enumerate() {
791 match arg.kind() {
792 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
793 self.regions.insert((lt, idx));
794 }
795 GenericArgKind::Type(t) => {
796 self.types.insert((t, idx));
797 }
798 _ => {}
799 }
800 }
801 }
802 _ => {}
803 }
804 t.super_visit_with(self)
805 }
806}
807
808fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
809 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
810 let trait_def_id = tcx.local_parent(trait_item_def_id);
811
812 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
813 .skip(1)
814 .flat_map(|supertrait_def_id| {
815 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
816 })
817 .collect();
818 if !shadowed.is_empty() {
819 let shadowee = if let [shadowed] = shadowed[..] {
820 errors::SupertraitItemShadowee::Labeled {
821 span: tcx.def_span(shadowed.def_id),
822 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
823 }
824 } else {
825 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
826 .iter()
827 .map(|item| {
828 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
829 })
830 .unzip();
831 errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
832 };
833
834 tcx.emit_node_span_lint(
835 SHADOWING_SUPERTRAIT_ITEMS,
836 tcx.local_def_id_to_hir_id(trait_item_def_id),
837 tcx.def_span(trait_item_def_id),
838 errors::SupertraitItemShadowing {
839 item: item_name,
840 subtrait: tcx.item_name(trait_def_id.to_def_id()),
841 shadowee,
842 },
843 );
844 }
845}
846
847fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
848 match param.kind {
849 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
851
852 ty::GenericParamDefKind::Const { .. } => {
854 let ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
855 let span = tcx.def_span(param.def_id);
856 let def_id = param.def_id.expect_local();
857
858 if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
859 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
860 wfcx.register_bound(
861 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
862 wfcx.param_env,
863 ty,
864 tcx.require_lang_item(LangItem::ConstParamTy, span),
865 );
866 Ok(())
867 })
868 } else {
869 let span = || {
870 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
871 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
872 else {
873 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
874 };
875 span
876 };
877 let mut diag = match ty.kind() {
878 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
879 ty::FnPtr(..) => tcx.dcx().struct_span_err(
880 span(),
881 "using function pointers as const generic parameters is forbidden",
882 ),
883 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
884 span(),
885 "using raw pointers as const generic parameters is forbidden",
886 ),
887 _ => {
888 ty.error_reported()?;
890
891 tcx.dcx().struct_span_err(
892 span(),
893 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
894 "`{ty}` is forbidden as the type of a const generic parameter",
895 ),
896 )
897 }
898 };
899
900 diag.note("the only supported types are integers, `bool`, and `char`");
901
902 let cause = ObligationCause::misc(span(), def_id);
903 let adt_const_params_feature_string =
904 " more complex and user defined types".to_string();
905 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
906 tcx,
907 tcx.param_env(param.def_id),
908 ty,
909 cause,
910 ) {
911 Err(
913 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
914 | ConstParamTyImplementationError::NonExhaustive(..)
915 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
916 ) => None,
917 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
918 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![
919 (adt_const_params_feature_string, sym::min_adt_const_params),
920 (
921 " references to implement the `ConstParamTy` trait".into(),
922 sym::unsized_const_params,
923 ),
924 ])
925 }
926 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
929 fn ty_is_local(ty: Ty<'_>) -> bool {
930 match ty.kind() {
931 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
932 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
934 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
937 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
940 _ => false,
941 }
942 }
943
944 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![(
945 adt_const_params_feature_string,
946 sym::min_adt_const_params,
947 )])
948 }
949 Ok(..) => {
951 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)])
952 }
953 };
954 if let Some(features) = may_suggest_feature {
955 tcx.disabled_nightly_features(&mut diag, features);
956 }
957
958 Err(diag.emit())
959 }
960 }
961 }
962}
963
964#[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(964u32),
::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))]
965pub(crate) fn check_associated_item(
966 tcx: TyCtxt<'_>,
967 def_id: LocalDefId,
968) -> Result<(), ErrorGuaranteed> {
969 let loc = Some(WellFormedLoc::Ty(def_id));
970 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
971 let item = tcx.associated_item(def_id);
972
973 tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
976
977 let self_ty = match item.container {
978 ty::AssocContainer::Trait => tcx.types.self_param,
979 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
980 tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
981 }
982 };
983
984 let span = tcx.def_span(def_id);
985
986 match item.kind {
987 ty::AssocKind::Const { .. } => {
988 let ty = tcx.type_of(def_id).instantiate_identity();
989 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
990 wfcx.register_wf_obligation(span, loc, ty.into());
991
992 let has_value = item.defaultness(tcx).has_value();
993 if tcx.is_type_const(def_id) {
994 check_type_const(wfcx, def_id, ty, has_value)?;
995 }
996
997 if has_value {
998 let code = ObligationCauseCode::SizedConstOrStatic;
999 wfcx.register_bound(
1000 ObligationCause::new(span, def_id, code),
1001 wfcx.param_env,
1002 ty,
1003 tcx.require_lang_item(LangItem::Sized, span),
1004 );
1005 }
1006
1007 Ok(())
1008 }
1009 ty::AssocKind::Fn { .. } => {
1010 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1011 let hir_sig =
1012 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
1013 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
1014 check_method_receiver(wfcx, hir_sig, item, self_ty)
1015 }
1016 ty::AssocKind::Type { .. } => {
1017 if let ty::AssocContainer::Trait = item.container {
1018 check_associated_type_bounds(wfcx, item, span)
1019 }
1020 if item.defaultness(tcx).has_value() {
1021 let ty = tcx.type_of(def_id).instantiate_identity();
1022 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
1023 wfcx.register_wf_obligation(span, loc, ty.into());
1024 }
1025 Ok(())
1026 }
1027 }
1028 })
1029}
1030
1031fn check_type_defn<'tcx>(
1033 tcx: TyCtxt<'tcx>,
1034 item: &hir::Item<'tcx>,
1035 all_sized: bool,
1036) -> Result<(), ErrorGuaranteed> {
1037 tcx.ensure_ok().check_representability(item.owner_id.def_id);
1038 let adt_def = tcx.adt_def(item.owner_id);
1039
1040 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1041 let variants = adt_def.variants();
1042 let packed = adt_def.repr().packed();
1043
1044 for variant in variants.iter() {
1045 for field in &variant.fields {
1047 if let Some(def_id) = field.value
1048 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1049 {
1050 if let Some(def_id) = def_id.as_local()
1053 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1054 && let expr = &tcx.hir_body(anon.body).value
1055 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1056 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1057 {
1058 } else {
1061 let _ = tcx.const_eval_poly(def_id);
1064 }
1065 }
1066 let field_id = field.did.expect_local();
1067 let hir::FieldDef { ty: hir_ty, .. } =
1068 tcx.hir_node_by_def_id(field_id).expect_field();
1069 let ty = wfcx.deeply_normalize(
1070 hir_ty.span,
1071 None,
1072 tcx.type_of(field.did).instantiate_identity(),
1073 );
1074 wfcx.register_wf_obligation(
1075 hir_ty.span,
1076 Some(WellFormedLoc::Ty(field_id)),
1077 ty.into(),
1078 );
1079
1080 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())
1081 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1082 {
1083 tcx.dcx().span_err(
1086 hir_ty.span,
1087 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1088 "scalable vectors cannot be fields of a {}",
1089 adt_def.variant_descr()
1090 ),
1091 );
1092 }
1093 }
1094
1095 let needs_drop_copy = || {
1098 packed && {
1099 let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1100 let ty = tcx.erase_and_anonymize_regions(ty);
1101 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1102 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1103 }
1104 };
1105 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1107 let unsized_len = if all_sized { 0 } else { 1 };
1108 for (idx, field) in
1109 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1110 {
1111 let last = idx == variant.fields.len() - 1;
1112 let field_id = field.did.expect_local();
1113 let hir::FieldDef { ty: hir_ty, .. } =
1114 tcx.hir_node_by_def_id(field_id).expect_field();
1115 let ty = wfcx.normalize(
1116 hir_ty.span,
1117 None,
1118 tcx.type_of(field.did).instantiate_identity(),
1119 );
1120 wfcx.register_bound(
1121 traits::ObligationCause::new(
1122 hir_ty.span,
1123 wfcx.body_def_id,
1124 ObligationCauseCode::FieldSized {
1125 adt_kind: match &item.kind {
1126 ItemKind::Struct(..) => AdtKind::Struct,
1127 ItemKind::Union(..) => AdtKind::Union,
1128 ItemKind::Enum(..) => AdtKind::Enum,
1129 kind => ::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("should be wfchecking an ADT, got {0:?}", kind))span_bug!(
1130 item.span,
1131 "should be wfchecking an ADT, got {kind:?}"
1132 ),
1133 },
1134 span: hir_ty.span,
1135 last,
1136 },
1137 ),
1138 wfcx.param_env,
1139 ty,
1140 tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1141 );
1142 }
1143
1144 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1146 match tcx.const_eval_poly(discr_def_id) {
1147 Ok(_) => {}
1148 Err(ErrorHandled::Reported(..)) => {}
1149 Err(ErrorHandled::TooGeneric(sp)) => {
1150 ::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")
1151 }
1152 }
1153 }
1154 }
1155
1156 check_where_clauses(wfcx, item.owner_id.def_id);
1157 Ok(())
1158 })
1159}
1160
1161#[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(1161u32),
::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:1163",
"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(1163u32),
::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))]
1162fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1163 debug!(?item.owner_id);
1164
1165 let def_id = item.owner_id.def_id;
1166 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1167 return Ok(());
1169 }
1170
1171 let trait_def = tcx.trait_def(def_id);
1172 if trait_def.is_marker
1173 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1174 {
1175 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1176 struct_span_code_err!(
1177 tcx.dcx(),
1178 tcx.def_span(*associated_def_id),
1179 E0714,
1180 "marker traits cannot have associated items",
1181 )
1182 .emit();
1183 }
1184 }
1185
1186 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1187 check_where_clauses(wfcx, def_id);
1188 Ok(())
1189 });
1190
1191 if let hir::ItemKind::Trait { .. } = item.kind {
1193 check_gat_where_clauses(tcx, item.owner_id.def_id);
1194 }
1195 res
1196}
1197
1198fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1203 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1204
1205 {
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:1205",
"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(1205u32),
::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);
1206 let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1207 |(bound, bound_span)| {
1208 traits::wf::clause_obligations(
1209 wfcx.infcx,
1210 wfcx.param_env,
1211 wfcx.body_def_id,
1212 bound,
1213 bound_span,
1214 )
1215 },
1216 );
1217
1218 wfcx.register_obligations(wf_obligations);
1219}
1220
1221fn check_item_fn(
1222 tcx: TyCtxt<'_>,
1223 def_id: LocalDefId,
1224 decl: &hir::FnDecl<'_>,
1225) -> Result<(), ErrorGuaranteed> {
1226 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1227 check_eiis_fn(tcx, def_id);
1228
1229 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1230 check_fn_or_method(wfcx, sig, decl, def_id);
1231 Ok(())
1232 })
1233}
1234
1235fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1236 for EiiImpl { resolution, span, .. } in
1239 {
{
'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()
1240 {
1241 let (foreign_item, name) = match resolution {
1242 EiiImplResolution::Macro(def_id) => {
1243 if let Some(foreign_item) =
1246 {
{
'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)
1247 {
1248 (foreign_item, tcx.item_name(*def_id))
1249 } else {
1250 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1251 continue;
1252 }
1253 }
1254 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1255 EiiImplResolution::Error(_eg) => continue,
1256 };
1257
1258 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1259 }
1260}
1261
1262fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1263 for EiiImpl { resolution, span, .. } in
1266 {
{
'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()
1267 {
1268 let (foreign_item, name) = match resolution {
1269 EiiImplResolution::Macro(def_id) => {
1270 if let Some(foreign_item) =
1273 {
{
'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)
1274 {
1275 (foreign_item, tcx.item_name(*def_id))
1276 } else {
1277 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1278 continue;
1279 }
1280 }
1281 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1282 EiiImplResolution::Error(_eg) => continue,
1283 };
1284
1285 let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1286 }
1287}
1288
1289#[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(1289u32),
::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))]
1290pub(crate) fn check_static_item<'tcx>(
1291 tcx: TyCtxt<'tcx>,
1292 item_id: LocalDefId,
1293 ty: Ty<'tcx>,
1294 should_check_for_sync: bool,
1295) -> Result<(), ErrorGuaranteed> {
1296 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1297 if should_check_for_sync {
1298 check_eiis_static(tcx, item_id, ty);
1299 }
1300
1301 let span = tcx.ty_span(item_id);
1302 let loc = Some(WellFormedLoc::Ty(item_id));
1303 let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1304
1305 let is_foreign_item = tcx.is_foreign_item(item_id);
1306 let is_structurally_foreign_item = || {
1307 let tail = tcx.struct_tail_raw(
1308 item_ty,
1309 &ObligationCause::dummy(),
1310 |ty| wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty)),
1311 || {},
1312 );
1313
1314 matches!(tail.kind(), ty::Foreign(_))
1315 };
1316 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1317
1318 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1319 if forbid_unsized {
1320 let span = tcx.def_span(item_id);
1321 wfcx.register_bound(
1322 traits::ObligationCause::new(
1323 span,
1324 wfcx.body_def_id,
1325 ObligationCauseCode::SizedConstOrStatic,
1326 ),
1327 wfcx.param_env,
1328 item_ty,
1329 tcx.require_lang_item(LangItem::Sized, span),
1330 );
1331 }
1332
1333 let should_check_for_sync = should_check_for_sync
1335 && !is_foreign_item
1336 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1337 && !tcx.is_thread_local_static(item_id.to_def_id());
1338
1339 if should_check_for_sync {
1340 wfcx.register_bound(
1341 traits::ObligationCause::new(
1342 span,
1343 wfcx.body_def_id,
1344 ObligationCauseCode::SharedStatic,
1345 ),
1346 wfcx.param_env,
1347 item_ty,
1348 tcx.require_lang_item(LangItem::Sync, span),
1349 );
1350 }
1351 Ok(())
1352 })
1353}
1354
1355#[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(1355u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&["def_id", "item_ty",
"has_value"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&has_value as
&dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = wfcx.tcx();
let span = tcx.def_span(def_id);
wfcx.register_bound(ObligationCause::new(span, def_id,
ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
item_ty, tcx.require_lang_item(LangItem::ConstParamTy, span));
if has_value {
let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
let norm_ct =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
raw_ct);
wfcx.register_wf_obligation(span,
Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
wfcx.register_obligation(Obligation::new(tcx,
ObligationCause::new(span, def_id,
ObligationCauseCode::WellFormed(None)), wfcx.param_env,
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct,
item_ty))));
}
Ok(())
}
}
}#[instrument(level = "debug", skip(wfcx))]
1356pub(super) fn check_type_const<'tcx>(
1357 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1358 def_id: LocalDefId,
1359 item_ty: Ty<'tcx>,
1360 has_value: bool,
1361) -> Result<(), ErrorGuaranteed> {
1362 let tcx = wfcx.tcx();
1363 let span = tcx.def_span(def_id);
1364
1365 wfcx.register_bound(
1366 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1367 wfcx.param_env,
1368 item_ty,
1369 tcx.require_lang_item(LangItem::ConstParamTy, span),
1370 );
1371
1372 if has_value {
1373 let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1374 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1375 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1376
1377 wfcx.register_obligation(Obligation::new(
1378 tcx,
1379 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1380 wfcx.param_env,
1381 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1382 ));
1383 }
1384 Ok(())
1385}
1386
1387#[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(1387u32),
::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:1459",
"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(1459u32),
::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_))]
1388fn check_impl<'tcx>(
1389 tcx: TyCtxt<'tcx>,
1390 item: &'tcx hir::Item<'tcx>,
1391 impl_: &hir::Impl<'_>,
1392) -> Result<(), ErrorGuaranteed> {
1393 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1394 match impl_.of_trait {
1395 Some(of_trait) => {
1396 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1400 tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1403 let trait_span = of_trait.trait_ref.path.span;
1404 let trait_ref = wfcx.deeply_normalize(
1405 trait_span,
1406 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1407 trait_ref,
1408 );
1409 let trait_pred =
1410 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1411 let mut obligations = traits::wf::trait_obligations(
1412 wfcx.infcx,
1413 wfcx.param_env,
1414 wfcx.body_def_id,
1415 trait_pred,
1416 trait_span,
1417 item,
1418 );
1419 for obligation in &mut obligations {
1420 if obligation.cause.span != trait_span {
1421 continue;
1423 }
1424 if let Some(pred) = obligation.predicate.as_trait_clause()
1425 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1426 {
1427 obligation.cause.span = impl_.self_ty.span;
1428 }
1429 if let Some(pred) = obligation.predicate.as_projection_clause()
1430 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1431 {
1432 obligation.cause.span = impl_.self_ty.span;
1433 }
1434 }
1435
1436 if tcx.is_conditionally_const(item.owner_id.def_id) {
1438 for (bound, _) in
1439 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1440 {
1441 let bound = wfcx.normalize(
1442 item.span,
1443 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1444 bound,
1445 );
1446 wfcx.register_obligation(Obligation::new(
1447 tcx,
1448 ObligationCause::new(
1449 impl_.self_ty.span,
1450 wfcx.body_def_id,
1451 ObligationCauseCode::WellFormed(None),
1452 ),
1453 wfcx.param_env,
1454 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1455 ))
1456 }
1457 }
1458
1459 debug!(?obligations);
1460 wfcx.register_obligations(obligations);
1461 }
1462 None => {
1463 let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1464 let self_ty = wfcx.deeply_normalize(
1465 item.span,
1466 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1467 Unnormalized::new_wip(self_ty),
1468 );
1469 wfcx.register_wf_obligation(
1470 impl_.self_ty.span,
1471 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1472 self_ty.into(),
1473 );
1474 }
1475 }
1476
1477 check_where_clauses(wfcx, item.owner_id.def_id);
1478 Ok(())
1479 })
1480}
1481
1482#[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(1483u32),
::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))]
1484pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1485 let infcx = wfcx.infcx;
1486 let tcx = wfcx.tcx();
1487
1488 let predicates = tcx.predicates_of(def_id.to_def_id());
1489 let generics = tcx.generics_of(def_id);
1490
1491 for param in &generics.own_params {
1498 if let Some(default) = param
1499 .default_value(tcx)
1500 .map(ty::EarlyBinder::instantiate_identity)
1501 .map(Unnormalized::skip_norm_wip)
1502 {
1503 if !default.has_param() {
1510 wfcx.register_wf_obligation(
1511 tcx.def_span(param.def_id),
1512 matches!(param.kind, GenericParamDefKind::Type { .. })
1513 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1514 default.as_term().unwrap(),
1515 );
1516 } else {
1517 let GenericArgKind::Const(ct) = default.kind() else {
1520 continue;
1521 };
1522
1523 let ct_ty = match ct.kind() {
1524 ty::ConstKind::Infer(_)
1525 | ty::ConstKind::Placeholder(_)
1526 | ty::ConstKind::Bound(_, _) => unreachable!(),
1527 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1528 ty::ConstKind::Value(cv) => cv.ty,
1529 ty::ConstKind::Unevaluated(uv) => {
1530 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args).skip_norm_wip()
1531 }
1532 ty::ConstKind::Param(param_ct) => {
1533 param_ct.find_const_ty_from_env(wfcx.param_env)
1534 }
1535 };
1536
1537 let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1538 if !ct_ty.has_param() && !param_ty.has_param() {
1539 let cause = traits::ObligationCause::new(
1540 tcx.def_span(param.def_id),
1541 wfcx.body_def_id,
1542 ObligationCauseCode::WellFormed(None),
1543 );
1544 wfcx.register_obligation(Obligation::new(
1545 tcx,
1546 cause,
1547 wfcx.param_env,
1548 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1549 ));
1550 }
1551 }
1552 }
1553 }
1554
1555 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1564 if param.index >= generics.parent_count as u32
1565 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1567 && !default.has_param()
1569 {
1570 return default;
1572 }
1573 tcx.mk_param_from_def(param)
1574 });
1575
1576 let default_obligations = predicates
1578 .predicates
1579 .iter()
1580 .flat_map(|&(pred, sp)| {
1581 #[derive(Default)]
1582 struct CountParams {
1583 params: FxHashSet<u32>,
1584 }
1585 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1586 type Result = ControlFlow<()>;
1587 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1588 if let ty::Param(param) = t.kind() {
1589 self.params.insert(param.index);
1590 }
1591 t.super_visit_with(self)
1592 }
1593
1594 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1595 ControlFlow::Break(())
1596 }
1597
1598 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1599 if let ty::ConstKind::Param(param) = c.kind() {
1600 self.params.insert(param.index);
1601 }
1602 c.super_visit_with(self)
1603 }
1604 }
1605 let mut param_count = CountParams::default();
1606 let has_region = pred.visit_with(&mut param_count).is_break();
1607 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1608 if instantiated_pred.skip_normalization().has_non_region_param()
1611 || param_count.params.len() > 1
1612 || has_region
1613 {
1614 None
1615 } else if predicates
1616 .predicates
1617 .iter()
1618 .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_pred)
1619 {
1620 None
1622 } else {
1623 Some((instantiated_pred, sp))
1624 }
1625 })
1626 .map(|(pred, sp)| {
1627 let pred = wfcx.normalize(sp, None, pred);
1637 let cause = traits::ObligationCause::new(
1638 sp,
1639 wfcx.body_def_id,
1640 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1641 );
1642 Obligation::new(tcx, cause, wfcx.param_env, pred)
1643 });
1644
1645 let predicates = predicates.instantiate_identity(tcx);
1646
1647 let assoc_const_obligations: Vec<_> = predicates
1648 .predicates
1649 .iter()
1650 .copied()
1651 .zip(predicates.spans.iter().copied())
1652 .filter_map(|(clause, sp)| {
1653 let clause = clause.skip_norm_wip();
1654 let proj = clause.as_projection_clause()?;
1655 let pred_binder = proj
1656 .map_bound(|pred| {
1657 pred.term.as_const().map(|ct| {
1658 let assoc_const_ty = tcx
1659 .type_of(pred.projection_term.def_id())
1660 .instantiate(tcx, pred.projection_term.args)
1661 .skip_norm_wip();
1662 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1663 })
1664 })
1665 .transpose();
1666 pred_binder.map(|pred_binder| {
1667 let cause = traits::ObligationCause::new(
1668 sp,
1669 wfcx.body_def_id,
1670 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1671 );
1672 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1673 })
1674 })
1675 .collect();
1676
1677 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1678 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1679 traits::wf::clause_obligations(
1680 infcx,
1681 wfcx.param_env,
1682 wfcx.body_def_id,
1683 p.skip_norm_wip(),
1684 sp,
1685 )
1686 });
1687 let obligations: Vec<_> =
1688 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1689 wfcx.register_obligations(obligations);
1690}
1691
1692#[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(1692u32),
::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))]
1693fn check_fn_or_method<'tcx>(
1694 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1695 sig: ty::PolyFnSig<'tcx>,
1696 hir_decl: &hir::FnDecl<'_>,
1697 def_id: LocalDefId,
1698) {
1699 let tcx = wfcx.tcx();
1700 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1701
1702 let arg_span =
1708 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1709
1710 sig.inputs_and_output =
1711 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1712 wfcx.deeply_normalize(
1713 arg_span(idx),
1714 Some(WellFormedLoc::Param {
1715 function: def_id,
1716 param_idx: idx,
1719 }),
1720 Unnormalized::new_wip(ty),
1721 )
1722 }));
1723
1724 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1725 wfcx.register_wf_obligation(
1726 arg_span(idx),
1727 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1728 ty.into(),
1729 );
1730 }
1731
1732 check_where_clauses(wfcx, def_id);
1733
1734 if sig.abi() == ExternAbi::RustCall {
1735 let span = tcx.def_span(def_id);
1736 let has_implicit_self = hir_decl.implicit_self() != hir::ImplicitSelfKind::None;
1737 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1738 if let Some(ty) = inputs.next() {
1740 wfcx.register_bound(
1741 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1742 wfcx.param_env,
1743 *ty,
1744 tcx.require_lang_item(hir::LangItem::Tuple, span),
1745 );
1746 wfcx.register_bound(
1747 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1748 wfcx.param_env,
1749 *ty,
1750 tcx.require_lang_item(hir::LangItem::Sized, span),
1751 );
1752 } else {
1753 tcx.dcx().span_err(
1754 hir_decl.inputs.last().map_or(span, |input| input.span),
1755 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1756 );
1757 }
1758 if inputs.next().is_some() {
1760 tcx.dcx().span_err(
1761 hir_decl.inputs.last().map_or(span, |input| input.span),
1762 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1763 );
1764 }
1765 }
1766
1767 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1769 let span = match hir_decl.output {
1770 hir::FnRetTy::Return(ty) => ty.span,
1771 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1772 };
1773
1774 wfcx.register_bound(
1775 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1776 wfcx.param_env,
1777 sig.output(),
1778 tcx.require_lang_item(LangItem::Sized, span),
1779 );
1780 }
1781}
1782
1783#[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)]
1785enum ArbitrarySelfTypesLevel {
1786 Basic, WithPointers, }
1789
1790#[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(1790u32),
::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:1810",
"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(1810u32),
::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))]
1791fn check_method_receiver<'tcx>(
1792 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1793 fn_sig: &hir::FnSig<'_>,
1794 method: ty::AssocItem,
1795 self_ty: Ty<'tcx>,
1796) -> Result<(), ErrorGuaranteed> {
1797 let tcx = wfcx.tcx();
1798
1799 if !method.is_method() {
1800 return Ok(());
1801 }
1802
1803 let span = fn_sig.decl.inputs[0].span;
1804 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1805
1806 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1807 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1808 let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1809
1810 debug!("check_method_receiver: sig={:?}", sig);
1811
1812 let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1813
1814 let receiver_ty = sig.inputs()[0];
1815 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1816
1817 receiver_ty.error_reported()?;
1820
1821 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1822 Some(ArbitrarySelfTypesLevel::WithPointers)
1823 } else if tcx.features().arbitrary_self_types() {
1824 Some(ArbitrarySelfTypesLevel::Basic)
1825 } else {
1826 None
1827 };
1828 let generics = tcx.generics_of(method.def_id);
1829
1830 let receiver_validity =
1831 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1832 if let Err(receiver_validity_err) = receiver_validity {
1833 return Err(match arbitrary_self_types_level {
1834 None if receiver_is_valid(
1838 wfcx,
1839 span,
1840 receiver_ty,
1841 self_ty,
1842 Some(ArbitrarySelfTypesLevel::Basic),
1843 generics,
1844 )
1845 .is_ok() =>
1846 {
1847 feature_err(
1849 &tcx.sess,
1850 sym::arbitrary_self_types,
1851 span,
1852 format!(
1853 "`{receiver_ty}` cannot be used as the type of `self` without \
1854 the `arbitrary_self_types` feature",
1855 ),
1856 )
1857 .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>`"))
1858 .emit()
1859 }
1860 None | Some(ArbitrarySelfTypesLevel::Basic)
1861 if receiver_is_valid(
1862 wfcx,
1863 span,
1864 receiver_ty,
1865 self_ty,
1866 Some(ArbitrarySelfTypesLevel::WithPointers),
1867 generics,
1868 )
1869 .is_ok() =>
1870 {
1871 feature_err(
1873 &tcx.sess,
1874 sym::arbitrary_self_types_pointers,
1875 span,
1876 format!(
1877 "`{receiver_ty}` cannot be used as the type of `self` without \
1878 the `arbitrary_self_types_pointers` feature",
1879 ),
1880 )
1881 .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>`"))
1882 .emit()
1883 }
1884 _ =>
1885 {
1887 match receiver_validity_err {
1888 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1889 let hint = match receiver_ty
1890 .builtin_deref(false)
1891 .unwrap_or(receiver_ty)
1892 .ty_adt_def()
1893 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1894 {
1895 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1896 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1897 _ => None,
1898 };
1899
1900 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1901 }
1902 ReceiverValidityError::DoesNotDeref => {
1903 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1904 span,
1905 receiver_ty,
1906 })
1907 }
1908 ReceiverValidityError::MethodGenericParamUsed => {
1909 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1910 }
1911 }
1912 }
1913 });
1914 }
1915 Ok(())
1916}
1917
1918enum ReceiverValidityError {
1922 DoesNotDeref,
1925 MethodGenericParamUsed,
1927}
1928
1929fn confirm_type_is_not_a_method_generic_param(
1932 ty: Ty<'_>,
1933 method_generics: &ty::Generics,
1934) -> Result<(), ReceiverValidityError> {
1935 if let ty::Param(param) = ty.kind() {
1936 if (param.index as usize) >= method_generics.parent_count {
1937 return Err(ReceiverValidityError::MethodGenericParamUsed);
1938 }
1939 }
1940 Ok(())
1941}
1942
1943fn receiver_is_valid<'tcx>(
1953 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1954 span: Span,
1955 receiver_ty: Ty<'tcx>,
1956 self_ty: Ty<'tcx>,
1957 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1958 method_generics: &ty::Generics,
1959) -> Result<(), ReceiverValidityError> {
1960 let infcx = wfcx.infcx;
1961 let tcx = wfcx.tcx();
1962 let cause =
1963 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1964
1965 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1967 let ocx = ObligationCtxt::new(wfcx.infcx);
1968 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1969 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1970 Ok(())
1971 } else {
1972 Err(NoSolution)
1973 }
1974 }) {
1975 return Ok(());
1976 }
1977
1978 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1979
1980 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1981
1982 if arbitrary_self_types_enabled.is_some() {
1986 autoderef = autoderef.use_receiver_trait();
1987 }
1988
1989 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1991 autoderef = autoderef.include_raw_pointers();
1992 }
1993
1994 while let Some((potential_self_ty, _)) = autoderef.next() {
1996 {
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:1996",
"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(1996u32),
::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!(
1997 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1998 potential_self_ty, self_ty
1999 );
2000
2001 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
2002
2003 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
2006 let ocx = ObligationCtxt::new(wfcx.infcx);
2007 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
2008 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
2009 Ok(())
2010 } else {
2011 Err(NoSolution)
2012 }
2013 }) {
2014 wfcx.register_obligations(autoderef.into_obligations());
2015 return Ok(());
2016 }
2017
2018 if arbitrary_self_types_enabled.is_none() {
2021 let legacy_receiver_trait_def_id =
2022 tcx.require_lang_item(LangItem::LegacyReceiver, span);
2023 if !legacy_receiver_is_implemented(
2024 wfcx,
2025 legacy_receiver_trait_def_id,
2026 cause.clone(),
2027 potential_self_ty,
2028 ) {
2029 break;
2031 }
2032
2033 wfcx.register_bound(
2035 cause.clone(),
2036 wfcx.param_env,
2037 potential_self_ty,
2038 legacy_receiver_trait_def_id,
2039 );
2040 }
2041 }
2042
2043 {
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:2043",
"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(2043u32),
::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);
2044 Err(ReceiverValidityError::DoesNotDeref)
2045}
2046
2047fn legacy_receiver_is_implemented<'tcx>(
2048 wfcx: &WfCheckingCtxt<'_, 'tcx>,
2049 legacy_receiver_trait_def_id: DefId,
2050 cause: ObligationCause<'tcx>,
2051 receiver_ty: Ty<'tcx>,
2052) -> bool {
2053 let tcx = wfcx.tcx();
2054 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
2055
2056 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
2057
2058 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
2059 true
2060 } else {
2061 {
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:2061",
"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(2061u32),
::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!(
2062 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
2063 receiver_ty
2064 );
2065 false
2066 }
2067}
2068
2069pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2070 match tcx.def_kind(def_id) {
2071 DefKind::Enum | DefKind::Struct | DefKind::Union => {
2072 }
2074 DefKind::TyAlias => {
2075 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!(
2076 tcx.type_alias_is_lazy(def_id),
2077 "should not be computing variance of non-free type alias"
2078 );
2079 }
2080 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:?}"),
2081 }
2082
2083 let ty_predicates = tcx.predicates_of(def_id);
2084 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);
2085 let variances = tcx.variances_of(def_id);
2086
2087 let mut constrained_parameters: FxHashSet<_> = variances
2088 .iter()
2089 .enumerate()
2090 .filter(|&(_, &variance)| variance != ty::Bivariant)
2091 .map(|(index, _)| Parameter(index as u32))
2092 .collect();
2093
2094 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2095
2096 let explicitly_bounded_params = LazyCell::new(|| {
2098 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2099 tcx.hir_node_by_def_id(def_id)
2100 .generics()
2101 .unwrap()
2102 .predicates
2103 .iter()
2104 .filter_map(|predicate| match predicate.kind {
2105 hir::WherePredicateKind::BoundPredicate(predicate) => {
2106 match icx.lower_ty(predicate.bounded_ty).kind() {
2107 ty::Param(data) => Some(Parameter(data.index)),
2108 _ => None,
2109 }
2110 }
2111 _ => None,
2112 })
2113 .collect::<FxHashSet<_>>()
2114 });
2115
2116 for (index, _) in variances.iter().enumerate() {
2117 let parameter = Parameter(index as u32);
2118
2119 if constrained_parameters.contains(¶meter) {
2120 continue;
2121 }
2122
2123 let node = tcx.hir_node_by_def_id(def_id);
2124 let item = node.expect_item();
2125 let hir_generics = node.generics().unwrap();
2126 let hir_param = &hir_generics.params[index];
2127
2128 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2129
2130 if ty_param.def_id != hir_param.def_id.into() {
2131 tcx.dcx().span_delayed_bug(
2139 hir_param.span,
2140 "hir generics and ty generics in different order",
2141 );
2142 continue;
2143 }
2144
2145 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2147 .type_of(def_id)
2148 .instantiate_identity()
2149 .skip_norm_wip()
2150 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2151 {
2152 continue;
2153 }
2154
2155 match hir_param.name {
2156 hir::ParamName::Error(_) => {
2157 }
2160 _ => {
2161 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2162 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2163 }
2164 }
2165 }
2166}
2167
2168struct HasErrorDeep<'tcx> {
2170 tcx: TyCtxt<'tcx>,
2171 seen: FxHashSet<DefId>,
2172}
2173impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2174 type Result = ControlFlow<ErrorGuaranteed>;
2175
2176 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2177 match *ty.kind() {
2178 ty::Adt(def, _) => {
2179 if self.seen.insert(def.did()) {
2180 for field in def.all_fields() {
2181 self.tcx
2182 .type_of(field.did)
2183 .instantiate_identity()
2184 .skip_norm_wip()
2185 .visit_with(self)?;
2186 }
2187 }
2188 }
2189 ty::Error(guar) => return ControlFlow::Break(guar),
2190 _ => {}
2191 }
2192 ty.super_visit_with(self)
2193 }
2194
2195 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2196 if let Err(guar) = r.error_reported() {
2197 ControlFlow::Break(guar)
2198 } else {
2199 ControlFlow::Continue(())
2200 }
2201 }
2202
2203 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2204 if let Err(guar) = c.error_reported() {
2205 ControlFlow::Break(guar)
2206 } else {
2207 ControlFlow::Continue(())
2208 }
2209 }
2210}
2211
2212fn report_bivariance<'tcx>(
2213 tcx: TyCtxt<'tcx>,
2214 param: &'tcx hir::GenericParam<'tcx>,
2215 has_explicit_bounds: bool,
2216 item: &'tcx hir::Item<'tcx>,
2217) -> ErrorGuaranteed {
2218 let param_name = param.name.ident();
2219
2220 let help = match item.kind {
2221 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2222 if let Some(def_id) = tcx.lang_items().phantom_data() {
2223 errors::UnusedGenericParameterHelp::Adt {
2224 param_name,
2225 phantom_data: tcx.def_path_str(def_id),
2226 }
2227 } else {
2228 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2229 }
2230 }
2231 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2232 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:?}"),
2233 };
2234
2235 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2236 intravisit::walk_item(
2237 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2238 item,
2239 );
2240
2241 if !usage_spans.is_empty() {
2242 let item_def_id = item.owner_id.to_def_id();
2246 let is_probably_cyclical =
2247 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2248 .visit_def(item_def_id)
2249 .is_break();
2250 if is_probably_cyclical {
2259 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2260 spans: usage_spans,
2261 param_span: param.span,
2262 param_name,
2263 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2264 help,
2265 note: (),
2266 });
2267 }
2268 }
2269
2270 let const_param_help =
2271 #[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);
2272
2273 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2274 span: param.span,
2275 param_name,
2276 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2277 usage_spans,
2278 help,
2279 const_param_help,
2280 });
2281 diag.code(E0392);
2282 if item.kind.recovered() {
2283 diag.delay_as_bug()
2285 } else {
2286 diag.emit()
2287 }
2288}
2289
2290struct IsProbablyCyclical<'tcx> {
2296 tcx: TyCtxt<'tcx>,
2297 item_def_id: DefId,
2298 seen: FxHashSet<DefId>,
2299}
2300
2301impl<'tcx> IsProbablyCyclical<'tcx> {
2302 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2303 match self.tcx.def_kind(def_id) {
2304 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2305 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2306 self.tcx
2307 .type_of(field.did)
2308 .instantiate_identity()
2309 .skip_norm_wip()
2310 .visit_with(self)
2311 })
2312 }
2313 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2314 self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip().visit_with(self)
2315 }
2316 _ => ControlFlow::Continue(()),
2317 }
2318 }
2319}
2320
2321impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2322 type Result = ControlFlow<(), ()>;
2323
2324 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2325 let def_id = match ty.kind() {
2326 ty::Adt(adt_def, _) => Some(adt_def.did()),
2327 &ty::Alias(ty::AliasTy { kind: ty::Free { def_id }, .. }) => Some(def_id),
2328 _ => None,
2329 };
2330 if let Some(def_id) = def_id {
2331 if def_id == self.item_def_id {
2332 return ControlFlow::Break(());
2333 }
2334 if self.seen.insert(def_id) {
2335 self.visit_def(def_id)?;
2336 }
2337 }
2338 ty.super_visit_with(self)
2339 }
2340}
2341
2342struct CollectUsageSpans<'a> {
2347 spans: &'a mut Vec<Span>,
2348 param_def_id: DefId,
2349}
2350
2351impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2352 type Result = ();
2353
2354 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2355 }
2357
2358 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2359 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2360 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2361 && def_id == self.param_def_id
2362 {
2363 self.spans.push(t.span);
2364 return;
2365 } else if let Res::SelfTyAlias { .. } = qpath.res {
2366 self.spans.push(t.span);
2367 return;
2368 }
2369 }
2370 intravisit::walk_ty(self, t);
2371 }
2372}
2373
2374impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2375 #[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(2377u32),
::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))]
2378 fn check_false_global_bounds(&mut self) {
2379 let tcx = self.ocx.infcx.tcx;
2380 let mut span = tcx.def_span(self.body_def_id);
2381 let empty_env = ty::ParamEnv::empty();
2382
2383 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2384 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2386
2387 for (pred, obligation_span) in implied_obligations {
2388 match pred.kind().skip_binder() {
2389 ty::ClauseKind::WellFormed(..)
2393 | ty::ClauseKind::UnstableFeature(..) => continue,
2395 _ => {}
2396 }
2397
2398 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2400 let pred = self.normalize(span, None, Unnormalized::new_wip(pred));
2401
2402 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2404 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2405 span = predicates
2406 .iter()
2407 .find(|pred| pred.span.contains(obligation_span))
2409 .map(|pred| pred.span)
2410 .unwrap_or(obligation_span);
2411 }
2412
2413 let obligation = Obligation::new(
2414 tcx,
2415 traits::ObligationCause::new(
2416 span,
2417 self.body_def_id,
2418 ObligationCauseCode::TrivialBound,
2419 ),
2420 empty_env,
2421 pred,
2422 );
2423 self.ocx.register_obligation(obligation);
2424 }
2425 }
2426 }
2427}
2428
2429pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2430 let items = tcx.hir_crate_items(());
2431 let res =
2432 items
2433 .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2434 .and(
2435 items.par_impl_items(|item| {
2436 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2437 }),
2438 )
2439 .and(items.par_trait_items(|item| {
2440 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2441 }))
2442 .and(items.par_foreign_items(|item| {
2443 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2444 }))
2445 .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2446 .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2447
2448 super::entry::check_for_entry_fn(tcx)?;
2449
2450 res
2451}
2452
2453fn lint_redundant_lifetimes<'tcx>(
2454 tcx: TyCtxt<'tcx>,
2455 owner_id: LocalDefId,
2456 outlives_env: &OutlivesEnvironment<'tcx>,
2457) {
2458 let def_kind = tcx.def_kind(owner_id);
2459 match def_kind {
2460 DefKind::Struct
2461 | DefKind::Union
2462 | DefKind::Enum
2463 | DefKind::Trait
2464 | DefKind::TraitAlias
2465 | DefKind::Fn
2466 | DefKind::Const { .. }
2467 | DefKind::Impl { of_trait: _ } => {
2468 }
2470 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2471 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2472 return;
2477 }
2478 }
2479 DefKind::Mod
2480 | DefKind::Variant
2481 | DefKind::TyAlias
2482 | DefKind::ForeignTy
2483 | DefKind::TyParam
2484 | DefKind::ConstParam
2485 | DefKind::Static { .. }
2486 | DefKind::Ctor(_, _)
2487 | DefKind::Macro(_)
2488 | DefKind::ExternCrate
2489 | DefKind::Use
2490 | DefKind::ForeignMod
2491 | DefKind::AnonConst
2492 | DefKind::InlineConst
2493 | DefKind::OpaqueTy
2494 | DefKind::Field
2495 | DefKind::LifetimeParam
2496 | DefKind::GlobalAsm
2497 | DefKind::Closure
2498 | DefKind::SyntheticCoroutineBody => return,
2499 }
2500
2501 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];
2510 lifetimes.extend(
2511 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2512 );
2513 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2515 for (idx, var) in tcx
2516 .fn_sig(owner_id)
2517 .instantiate_identity()
2518 .skip_norm_wip()
2519 .bound_vars()
2520 .iter()
2521 .enumerate()
2522 {
2523 let ty::BoundVariableKind::Region(kind) = var else { continue };
2524 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2525 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2526 }
2527 }
2528 lifetimes.retain(|candidate| candidate.is_named(tcx));
2529
2530 let mut shadowed = FxHashSet::default();
2534
2535 for (idx, &candidate) in lifetimes.iter().enumerate() {
2536 if shadowed.contains(&candidate) {
2541 continue;
2542 }
2543
2544 for &victim in &lifetimes[(idx + 1)..] {
2545 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2553 continue;
2554 };
2555
2556 if tcx.parent(def_id) != owner_id.to_def_id() {
2561 continue;
2562 }
2563
2564 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2566 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2567 {
2568 shadowed.insert(victim);
2569 tcx.emit_node_span_lint(
2570 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2571 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2572 tcx.def_span(def_id),
2573 RedundantLifetimeArgsLint { candidate, victim },
2574 );
2575 }
2576 }
2577 }
2578}
2579
2580#[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)]
2581#[diag("unnecessary lifetime parameter `{$victim}`")]
2582#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2583struct RedundantLifetimeArgsLint<'tcx> {
2584 victim: ty::Region<'tcx>,
2586 candidate: ty::Region<'tcx>,
2588}