1use std::cell::LazyCell;
2use std::ops::{ControlFlow, Deref};
3
4use hir::intravisit::{self, Visitor};
5use rustc_abi::{ExternAbi, ScalableElt};
6use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, msg, pluralize, struct_span_code_err};
9use rustc_hir::attrs::{EiiDecl, EiiImpl, EiiImplResolution};
10use rustc_hir::def::{DefKind, Res};
11use rustc_hir::def_id::{DefId, LocalDefId};
12use rustc_hir::lang_items::LangItem;
13use rustc_hir::{AmbigArg, ItemKind, find_attr};
14use rustc_infer::infer::outlives::env::OutlivesEnvironment;
15use rustc_infer::infer::{self, InferCtxt, SubregionOrigin, TyCtxtInferExt};
16use rustc_lint_defs::builtin::SHADOWING_SUPERTRAIT_ITEMS;
17use rustc_macros::LintDiagnostic;
18use rustc_middle::mir::interpret::ErrorHandled;
19use rustc_middle::traits::solve::NoSolution;
20use rustc_middle::ty::trait_def::TraitSpecializationKind;
21use rustc_middle::ty::{
22 self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags,
23 TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
24 Upcast,
25};
26use rustc_middle::{bug, span_bug};
27use rustc_session::parse::feature_err;
28use rustc_span::{DUMMY_SP, Span, sym};
29use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
30use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
31use rustc_trait_selection::traits::misc::{
32 ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
33};
34use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
35use rustc_trait_selection::traits::{
36 self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
37 WellFormedLoc,
38};
39use tracing::{debug, instrument};
40use {rustc_ast as ast, rustc_hir as hir};
41
42use super::compare_eii::compare_eii_function_types;
43use crate::autoderef::Autoderef;
44use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
45use crate::errors;
46use crate::errors::InvalidReceiverTyHint;
47
48pub(super) struct WfCheckingCtxt<'a, 'tcx> {
49 pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
50 body_def_id: LocalDefId,
51 param_env: ty::ParamEnv<'tcx>,
52}
53impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
54 type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
55 fn deref(&self) -> &Self::Target {
56 &self.ocx
57 }
58}
59
60impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
61 fn tcx(&self) -> TyCtxt<'tcx> {
62 self.ocx.infcx.tcx
63 }
64
65 fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
68 where
69 T: TypeFoldable<TyCtxt<'tcx>>,
70 {
71 self.ocx.normalize(
72 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
73 self.param_env,
74 value,
75 )
76 }
77
78 pub(super) fn deeply_normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
88 where
89 T: TypeFoldable<TyCtxt<'tcx>>,
90 {
91 if self.infcx.next_trait_solver() {
92 match self.ocx.deeply_normalize(
93 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
94 self.param_env,
95 value.clone(),
96 ) {
97 Ok(value) => value,
98 Err(errors) => {
99 self.infcx.err_ctxt().report_fulfillment_errors(errors);
100 value
101 }
102 }
103 } else {
104 self.normalize(span, loc, value)
105 }
106 }
107
108 pub(super) fn register_wf_obligation(
109 &self,
110 span: Span,
111 loc: Option<WellFormedLoc>,
112 term: ty::Term<'tcx>,
113 ) {
114 let cause = traits::ObligationCause::new(
115 span,
116 self.body_def_id,
117 ObligationCauseCode::WellFormed(loc),
118 );
119 self.ocx.register_obligation(Obligation::new(
120 self.tcx(),
121 cause,
122 self.param_env,
123 ty::ClauseKind::WellFormed(term),
124 ));
125 }
126}
127
128pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
129 tcx: TyCtxt<'tcx>,
130 body_def_id: LocalDefId,
131 f: F,
132) -> Result<(), ErrorGuaranteed>
133where
134 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
135{
136 let param_env = tcx.param_env(body_def_id);
137 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
138 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
139
140 let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
141
142 if !tcx.features().trivial_bounds() {
143 wfcx.check_false_global_bounds()
144 }
145 f(&mut wfcx)?;
146
147 let errors = wfcx.evaluate_obligations_error_on_ambiguity();
148 if !errors.is_empty() {
149 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
150 }
151
152 let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
153 {
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:153",
"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(153u32),
::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);
154
155 let infcx_compat = infcx.fork();
156
157 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
160 &infcx,
161 body_def_id,
162 param_env,
163 assumed_wf_types.iter().copied(),
164 true,
165 );
166
167 lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
168
169 let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
170 if errors.is_empty() {
171 return Ok(());
172 }
173
174 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
175 &infcx_compat,
176 body_def_id,
177 param_env,
178 assumed_wf_types,
179 false,
182 );
183 let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
184 if errors_compat.is_empty() {
185 Ok(())
188 } else {
189 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
190 }
191}
192
193pub(super) fn check_well_formed(
194 tcx: TyCtxt<'_>,
195 def_id: LocalDefId,
196) -> Result<(), ErrorGuaranteed> {
197 let mut res = crate::check::check::check_item_type(tcx, def_id);
198
199 for param in &tcx.generics_of(def_id).own_params {
200 res = res.and(check_param_wf(tcx, param));
201 }
202
203 res
204}
205
206#[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(219u32),
::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:226",
"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(226u32),
::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")]
220pub(super) fn check_item<'tcx>(
221 tcx: TyCtxt<'tcx>,
222 item: &'tcx hir::Item<'tcx>,
223) -> Result<(), ErrorGuaranteed> {
224 let def_id = item.owner_id.def_id;
225
226 debug!(
227 ?item.owner_id,
228 item.name = ? tcx.def_path_str(def_id)
229 );
230
231 match item.kind {
232 hir::ItemKind::Impl(ref impl_) => {
250 crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
251 let mut res = Ok(());
252 if let Some(of_trait) = impl_.of_trait {
253 let header = tcx.impl_trait_header(def_id);
254 let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
255 if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
256 let sp = of_trait.trait_ref.path.span;
257 res = Err(tcx
258 .dcx()
259 .struct_span_err(sp, "impls of auto traits cannot be default")
260 .with_span_labels(of_trait.defaultness_span, "default because of this")
261 .with_span_label(sp, "auto trait")
262 .emit());
263 }
264 match header.polarity {
265 ty::ImplPolarity::Positive => {
266 res = res.and(check_impl(tcx, item, impl_));
267 }
268 ty::ImplPolarity::Negative => {
269 let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
270 bug!("impl_polarity query disagrees with impl's polarity in HIR");
271 };
272 if let hir::Defaultness::Default { .. } = of_trait.defaultness {
274 let mut spans = vec![span];
275 spans.extend(of_trait.defaultness_span);
276 res = Err(struct_span_code_err!(
277 tcx.dcx(),
278 spans,
279 E0750,
280 "negative impls cannot be default impls"
281 )
282 .emit());
283 }
284 }
285 ty::ImplPolarity::Reservation => {
286 }
288 }
289 } else {
290 res = res.and(check_impl(tcx, item, impl_));
291 }
292 res
293 }
294 hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
295 hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
296 hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
297 hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
298 hir::ItemKind::Trait(..) => check_trait(tcx, item),
299 hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
300 _ => Ok(()),
301 }
302}
303
304pub(super) fn check_foreign_item<'tcx>(
305 tcx: TyCtxt<'tcx>,
306 item: &'tcx hir::ForeignItem<'tcx>,
307) -> Result<(), ErrorGuaranteed> {
308 let def_id = item.owner_id.def_id;
309
310 {
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:310",
"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(310u32),
::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!(
311 ?item.owner_id,
312 item.name = ? tcx.def_path_str(def_id)
313 );
314
315 match item.kind {
316 hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
317 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
318 }
319}
320
321pub(crate) fn check_trait_item<'tcx>(
322 tcx: TyCtxt<'tcx>,
323 def_id: LocalDefId,
324) -> Result<(), ErrorGuaranteed> {
325 lint_item_shadowing_supertrait_item(tcx, def_id);
327
328 let mut res = Ok(());
329
330 if tcx.def_kind(def_id) == DefKind::AssocFn {
331 for &assoc_ty_def_id in
332 tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
333 {
334 res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
335 }
336 }
337 res
338}
339
340fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
353 let mut required_bounds_by_item = FxIndexMap::default();
355 let associated_items = tcx.associated_items(trait_def_id);
356
357 loop {
363 let mut should_continue = false;
364 for gat_item in associated_items.in_definition_order() {
365 let gat_def_id = gat_item.def_id.expect_local();
366 let gat_item = tcx.associated_item(gat_def_id);
367 if !gat_item.is_type() {
369 continue;
370 }
371 let gat_generics = tcx.generics_of(gat_def_id);
372 if gat_generics.is_own_empty() {
374 continue;
375 }
376
377 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
381 for item in associated_items.in_definition_order() {
382 let item_def_id = item.def_id.expect_local();
383 if item_def_id == gat_def_id {
385 continue;
386 }
387
388 let param_env = tcx.param_env(item_def_id);
389
390 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
391 ty::AssocKind::Fn { .. } => {
393 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
397 item_def_id.to_def_id(),
398 tcx.fn_sig(item_def_id).instantiate_identity(),
399 );
400 gather_gat_bounds(
401 tcx,
402 param_env,
403 item_def_id,
404 sig.inputs_and_output,
405 &sig.inputs().iter().copied().collect(),
408 gat_def_id,
409 gat_generics,
410 )
411 }
412 ty::AssocKind::Type { .. } => {
414 let param_env = augment_param_env(
418 tcx,
419 param_env,
420 required_bounds_by_item.get(&item_def_id),
421 );
422 gather_gat_bounds(
423 tcx,
424 param_env,
425 item_def_id,
426 tcx.explicit_item_bounds(item_def_id)
427 .iter_identity_copied()
428 .collect::<Vec<_>>(),
429 &FxIndexSet::default(),
430 gat_def_id,
431 gat_generics,
432 )
433 }
434 ty::AssocKind::Const { .. } => None,
435 };
436
437 if let Some(item_required_bounds) = item_required_bounds {
438 if let Some(new_required_bounds) = &mut new_required_bounds {
444 new_required_bounds.retain(|b| item_required_bounds.contains(b));
445 } else {
446 new_required_bounds = Some(item_required_bounds);
447 }
448 }
449 }
450
451 if let Some(new_required_bounds) = new_required_bounds {
452 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
453 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
454 should_continue = true;
457 }
458 }
459 }
460 if !should_continue {
465 break;
466 }
467 }
468
469 for (gat_def_id, required_bounds) in required_bounds_by_item {
470 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
472 continue;
473 }
474
475 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
476 {
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:476",
"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(476u32),
::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);
477 let param_env = tcx.param_env(gat_def_id);
478
479 let unsatisfied_bounds: Vec<_> = required_bounds
480 .into_iter()
481 .filter(|clause| match clause.kind().skip_binder() {
482 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
483 !region_known_to_outlive(
484 tcx,
485 gat_def_id,
486 param_env,
487 &FxIndexSet::default(),
488 a,
489 b,
490 )
491 }
492 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
493 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
494 }
495 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected ClauseKind"))bug!("Unexpected ClauseKind"),
496 })
497 .map(|clause| clause.to_string())
498 .collect();
499
500 if !unsatisfied_bounds.is_empty() {
501 let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
502 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!(
503 "{} {}",
504 gat_item_hir.generics.add_where_or_trailing_comma(),
505 unsatisfied_bounds.join(", "),
506 );
507 let bound =
508 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
509 tcx.dcx()
510 .struct_span_err(
511 gat_item_hir.span,
512 ::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),
513 )
514 .with_span_suggestion(
515 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
516 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add the required where clause{0}",
plural))
})format!("add the required where clause{plural}"),
517 suggestion,
518 Applicability::MachineApplicable,
519 )
520 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
bound))
})format!(
521 "{bound} currently required to ensure that impls have maximum flexibility"
522 ))
523 .with_note(
524 "we are soliciting feedback, see issue #87479 \
525 <https://github.com/rust-lang/rust/issues/87479> for more information",
526 )
527 .emit();
528 }
529 }
530}
531
532fn augment_param_env<'tcx>(
534 tcx: TyCtxt<'tcx>,
535 param_env: ty::ParamEnv<'tcx>,
536 new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
537) -> ty::ParamEnv<'tcx> {
538 let Some(new_predicates) = new_predicates else {
539 return param_env;
540 };
541
542 if new_predicates.is_empty() {
543 return param_env;
544 }
545
546 let bounds = tcx.mk_clauses_from_iter(
547 param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
548 );
549 ty::ParamEnv::new(bounds)
552}
553
554fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
565 tcx: TyCtxt<'tcx>,
566 param_env: ty::ParamEnv<'tcx>,
567 item_def_id: LocalDefId,
568 to_check: T,
569 wf_tys: &FxIndexSet<Ty<'tcx>>,
570 gat_def_id: LocalDefId,
571 gat_generics: &'tcx ty::Generics,
572) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
573 let mut bounds = FxIndexSet::default();
575
576 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
577
578 if types.is_empty() && regions.is_empty() {
584 return None;
585 }
586
587 for (region_a, region_a_idx) in ®ions {
588 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
592 continue;
593 }
594 for (ty, ty_idx) in &types {
599 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
601 {
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:601",
"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(601u32),
::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);
602 {
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:602",
"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(602u32),
::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}");
603 let ty_param = gat_generics.param_at(*ty_idx, tcx);
607 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
608 let region_param = gat_generics.param_at(*region_a_idx, tcx);
611 let region_param = ty::Region::new_early_param(
612 tcx,
613 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
614 );
615 bounds.insert(
618 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
619 .upcast(tcx),
620 );
621 }
622 }
623
624 for (region_b, region_b_idx) in ®ions {
629 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 {
633 continue;
634 }
635 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
636 {
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:636",
"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(636u32),
::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);
637 {
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:637",
"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(637u32),
::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}");
638 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
640 let region_a_param = ty::Region::new_early_param(
641 tcx,
642 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
643 );
644 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
646 let region_b_param = ty::Region::new_early_param(
647 tcx,
648 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
649 );
650 bounds.insert(
652 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
653 region_a_param,
654 region_b_param,
655 ))
656 .upcast(tcx),
657 );
658 }
659 }
660 }
661
662 Some(bounds)
663}
664
665fn ty_known_to_outlive<'tcx>(
668 tcx: TyCtxt<'tcx>,
669 id: LocalDefId,
670 param_env: ty::ParamEnv<'tcx>,
671 wf_tys: &FxIndexSet<Ty<'tcx>>,
672 ty: Ty<'tcx>,
673 region: ty::Region<'tcx>,
674) -> bool {
675 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
676 infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
677 sub_region: region,
678 sup_type: ty,
679 origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
680 });
681 })
682}
683
684fn region_known_to_outlive<'tcx>(
687 tcx: TyCtxt<'tcx>,
688 id: LocalDefId,
689 param_env: ty::ParamEnv<'tcx>,
690 wf_tys: &FxIndexSet<Ty<'tcx>>,
691 region_a: ty::Region<'tcx>,
692 region_b: ty::Region<'tcx>,
693) -> bool {
694 test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
695 infcx.sub_regions(
696 SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
697 region_b,
698 region_a,
699 );
700 })
701}
702
703fn test_region_obligations<'tcx>(
707 tcx: TyCtxt<'tcx>,
708 id: LocalDefId,
709 param_env: ty::ParamEnv<'tcx>,
710 wf_tys: &FxIndexSet<Ty<'tcx>>,
711 add_constraints: impl FnOnce(&InferCtxt<'tcx>),
712) -> bool {
713 let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
717
718 add_constraints(&infcx);
719
720 let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
721 {
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:721",
"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(721u32),
::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");
722
723 errors.is_empty()
726}
727
728struct GATArgsCollector<'tcx> {
733 gat: DefId,
734 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
736 types: FxIndexSet<(Ty<'tcx>, usize)>,
738}
739
740impl<'tcx> GATArgsCollector<'tcx> {
741 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
742 gat: DefId,
743 t: T,
744 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
745 let mut visitor =
746 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
747 t.visit_with(&mut visitor);
748 (visitor.regions, visitor.types)
749 }
750}
751
752impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
753 fn visit_ty(&mut self, t: Ty<'tcx>) {
754 match t.kind() {
755 ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
756 for (idx, arg) in p.args.iter().enumerate() {
757 match arg.kind() {
758 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
759 self.regions.insert((lt, idx));
760 }
761 GenericArgKind::Type(t) => {
762 self.types.insert((t, idx));
763 }
764 _ => {}
765 }
766 }
767 }
768 _ => {}
769 }
770 t.super_visit_with(self)
771 }
772}
773
774fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
775 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
776 let trait_def_id = tcx.local_parent(trait_item_def_id);
777
778 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
779 .skip(1)
780 .flat_map(|supertrait_def_id| {
781 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
782 })
783 .collect();
784 if !shadowed.is_empty() {
785 let shadowee = if let [shadowed] = shadowed[..] {
786 errors::SupertraitItemShadowee::Labeled {
787 span: tcx.def_span(shadowed.def_id),
788 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
789 }
790 } else {
791 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
792 .iter()
793 .map(|item| {
794 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
795 })
796 .unzip();
797 errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
798 };
799
800 tcx.emit_node_span_lint(
801 SHADOWING_SUPERTRAIT_ITEMS,
802 tcx.local_def_id_to_hir_id(trait_item_def_id),
803 tcx.def_span(trait_item_def_id),
804 errors::SupertraitItemShadowing {
805 item: item_name,
806 subtrait: tcx.item_name(trait_def_id.to_def_id()),
807 shadowee,
808 },
809 );
810 }
811}
812
813fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
814 match param.kind {
815 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
817
818 ty::GenericParamDefKind::Const { .. } => {
820 let ty = tcx.type_of(param.def_id).instantiate_identity();
821 let span = tcx.def_span(param.def_id);
822 let def_id = param.def_id.expect_local();
823
824 if tcx.features().adt_const_params() {
825 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
826 wfcx.register_bound(
827 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
828 wfcx.param_env,
829 ty,
830 tcx.require_lang_item(LangItem::ConstParamTy, span),
831 );
832 Ok(())
833 })
834 } else {
835 let span = || {
836 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
837 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
838 else {
839 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
840 };
841 span
842 };
843 let mut diag = match ty.kind() {
844 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
845 ty::FnPtr(..) => tcx.dcx().struct_span_err(
846 span(),
847 "using function pointers as const generic parameters is forbidden",
848 ),
849 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
850 span(),
851 "using raw pointers as const generic parameters is forbidden",
852 ),
853 _ => {
854 ty.error_reported()?;
856
857 tcx.dcx().struct_span_err(
858 span(),
859 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
860 "`{ty}` is forbidden as the type of a const generic parameter",
861 ),
862 )
863 }
864 };
865
866 diag.note("the only supported types are integers, `bool`, and `char`");
867
868 let cause = ObligationCause::misc(span(), def_id);
869 let adt_const_params_feature_string =
870 " more complex and user defined types".to_string();
871 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
872 tcx,
873 tcx.param_env(param.def_id),
874 ty,
875 cause,
876 ) {
877 Err(
879 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
880 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
881 ) => None,
882 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
883 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::adt_const_params),
(" references to implement the `ConstParamTy` trait".into(),
sym::unsized_const_params)]))vec![
884 (adt_const_params_feature_string, sym::adt_const_params),
885 (
886 " references to implement the `ConstParamTy` trait".into(),
887 sym::unsized_const_params,
888 ),
889 ])
890 }
891 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
894 fn ty_is_local(ty: Ty<'_>) -> bool {
895 match ty.kind() {
896 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
897 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
899 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
902 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
905 _ => false,
906 }
907 }
908
909 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::adt_const_params)]))vec![(
910 adt_const_params_feature_string,
911 sym::adt_const_params,
912 )])
913 }
914 Ok(..) => 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::adt_const_params)]))vec![(adt_const_params_feature_string, sym::adt_const_params)]),
916 };
917 if let Some(features) = may_suggest_feature {
918 tcx.disabled_nightly_features(&mut diag, features);
919 }
920
921 Err(diag.emit())
922 }
923 }
924 }
925}
926
927#[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(927u32),
::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_ok().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()
}
};
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();
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))]
928pub(crate) fn check_associated_item(
929 tcx: TyCtxt<'_>,
930 def_id: LocalDefId,
931) -> Result<(), ErrorGuaranteed> {
932 let loc = Some(WellFormedLoc::Ty(def_id));
933 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
934 let item = tcx.associated_item(def_id);
935
936 tcx.ensure_ok().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
939
940 let self_ty = match item.container {
941 ty::AssocContainer::Trait => tcx.types.self_param,
942 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
943 tcx.type_of(item.container_id(tcx)).instantiate_identity()
944 }
945 };
946
947 let span = tcx.def_span(def_id);
948
949 match item.kind {
950 ty::AssocKind::Const { .. } => {
951 let ty = tcx.type_of(def_id).instantiate_identity();
952 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
953 wfcx.register_wf_obligation(span, loc, ty.into());
954
955 let has_value = item.defaultness(tcx).has_value();
956 if tcx.is_type_const(def_id) {
957 check_type_const(wfcx, def_id, ty, has_value)?;
958 }
959
960 if has_value {
961 let code = ObligationCauseCode::SizedConstOrStatic;
962 wfcx.register_bound(
963 ObligationCause::new(span, def_id, code),
964 wfcx.param_env,
965 ty,
966 tcx.require_lang_item(LangItem::Sized, span),
967 );
968 }
969
970 Ok(())
971 }
972 ty::AssocKind::Fn { .. } => {
973 let sig = tcx.fn_sig(def_id).instantiate_identity();
974 let hir_sig =
975 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
976 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
977 check_method_receiver(wfcx, hir_sig, item, self_ty)
978 }
979 ty::AssocKind::Type { .. } => {
980 if let ty::AssocContainer::Trait = item.container {
981 check_associated_type_bounds(wfcx, item, span)
982 }
983 if item.defaultness(tcx).has_value() {
984 let ty = tcx.type_of(def_id).instantiate_identity();
985 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
986 wfcx.register_wf_obligation(span, loc, ty.into());
987 }
988 Ok(())
989 }
990 }
991 })
992}
993
994fn check_type_defn<'tcx>(
996 tcx: TyCtxt<'tcx>,
997 item: &hir::Item<'tcx>,
998 all_sized: bool,
999) -> Result<(), ErrorGuaranteed> {
1000 let _ = tcx.representability(item.owner_id.def_id);
1001 let adt_def = tcx.adt_def(item.owner_id);
1002
1003 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1004 let variants = adt_def.variants();
1005 let packed = adt_def.repr().packed();
1006
1007 for variant in variants.iter() {
1008 for field in &variant.fields {
1010 if let Some(def_id) = field.value
1011 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1012 {
1013 if let Some(def_id) = def_id.as_local()
1016 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1017 && let expr = &tcx.hir_body(anon.body).value
1018 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1019 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1020 {
1021 } else {
1024 let _ = tcx.const_eval_poly(def_id);
1027 }
1028 }
1029 let field_id = field.did.expect_local();
1030 let hir::FieldDef { ty: hir_ty, .. } =
1031 tcx.hir_node_by_def_id(field_id).expect_field();
1032 let ty = wfcx.deeply_normalize(
1033 hir_ty.span,
1034 None,
1035 tcx.type_of(field.did).instantiate_identity(),
1036 );
1037 wfcx.register_wf_obligation(
1038 hir_ty.span,
1039 Some(WellFormedLoc::Ty(field_id)),
1040 ty.into(),
1041 );
1042
1043 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())
1044 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1045 {
1046 tcx.dcx().span_err(
1049 hir_ty.span,
1050 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1051 "scalable vectors cannot be fields of a {}",
1052 adt_def.variant_descr()
1053 ),
1054 );
1055 }
1056 }
1057
1058 let needs_drop_copy = || {
1061 packed && {
1062 let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1063 let ty = tcx.erase_and_anonymize_regions(ty);
1064 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1065 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1066 }
1067 };
1068 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1070 let unsized_len = if all_sized { 0 } else { 1 };
1071 for (idx, field) in
1072 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1073 {
1074 let last = idx == variant.fields.len() - 1;
1075 let field_id = field.did.expect_local();
1076 let hir::FieldDef { ty: hir_ty, .. } =
1077 tcx.hir_node_by_def_id(field_id).expect_field();
1078 let ty = wfcx.normalize(
1079 hir_ty.span,
1080 None,
1081 tcx.type_of(field.did).instantiate_identity(),
1082 );
1083 wfcx.register_bound(
1084 traits::ObligationCause::new(
1085 hir_ty.span,
1086 wfcx.body_def_id,
1087 ObligationCauseCode::FieldSized {
1088 adt_kind: match &item.kind {
1089 ItemKind::Struct(..) => AdtKind::Struct,
1090 ItemKind::Union(..) => AdtKind::Union,
1091 ItemKind::Enum(..) => AdtKind::Enum,
1092 kind => ::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("should be wfchecking an ADT, got {0:?}", kind))span_bug!(
1093 item.span,
1094 "should be wfchecking an ADT, got {kind:?}"
1095 ),
1096 },
1097 span: hir_ty.span,
1098 last,
1099 },
1100 ),
1101 wfcx.param_env,
1102 ty,
1103 tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1104 );
1105 }
1106
1107 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1109 match tcx.const_eval_poly(discr_def_id) {
1110 Ok(_) => {}
1111 Err(ErrorHandled::Reported(..)) => {}
1112 Err(ErrorHandled::TooGeneric(sp)) => {
1113 ::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")
1114 }
1115 }
1116 }
1117 }
1118
1119 check_where_clauses(wfcx, item.owner_id.def_id);
1120 Ok(())
1121 })
1122}
1123
1124#[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(1124u32),
::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:1126",
"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(1126u32),
::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))]
1125fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1126 debug!(?item.owner_id);
1127
1128 let def_id = item.owner_id.def_id;
1129 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1130 return Ok(());
1132 }
1133
1134 let trait_def = tcx.trait_def(def_id);
1135 if trait_def.is_marker
1136 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1137 {
1138 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1139 struct_span_code_err!(
1140 tcx.dcx(),
1141 tcx.def_span(*associated_def_id),
1142 E0714,
1143 "marker traits cannot have associated items",
1144 )
1145 .emit();
1146 }
1147 }
1148
1149 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1150 check_where_clauses(wfcx, def_id);
1151 Ok(())
1152 });
1153
1154 if let hir::ItemKind::Trait(..) = item.kind {
1156 check_gat_where_clauses(tcx, item.owner_id.def_id);
1157 }
1158 res
1159}
1160
1161fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1166 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1167
1168 {
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:1168",
"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(1168u32),
::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);
1169 let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1170 traits::wf::clause_obligations(
1171 wfcx.infcx,
1172 wfcx.param_env,
1173 wfcx.body_def_id,
1174 bound,
1175 bound_span,
1176 )
1177 });
1178
1179 wfcx.register_obligations(wf_obligations);
1180}
1181
1182fn check_item_fn(
1183 tcx: TyCtxt<'_>,
1184 def_id: LocalDefId,
1185 decl: &hir::FnDecl<'_>,
1186) -> Result<(), ErrorGuaranteed> {
1187 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1188 check_eiis(tcx, def_id);
1189
1190 let sig = tcx.fn_sig(def_id).instantiate_identity();
1191 check_fn_or_method(wfcx, sig, decl, def_id);
1192 Ok(())
1193 })
1194}
1195
1196fn check_eiis(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1197 for EiiImpl { resolution, span, .. } in
1200 {
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
#[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()
1201 {
1202 let (foreign_item, name) = match resolution {
1203 EiiImplResolution::Macro(def_id) => {
1204 if let Some(foreign_item) =
1207 {
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(*def_id) {
#[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)
1208 {
1209 (foreign_item, tcx.item_name(*def_id))
1210 } else {
1211 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1212 continue;
1213 }
1214 }
1215 EiiImplResolution::Known(decl) => (decl.foreign_item, decl.name.name),
1216 EiiImplResolution::Error(_eg) => continue,
1217 };
1218
1219 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1220 }
1221}
1222
1223#[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(1223u32),
::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|
{
let span = tcx.ty_span(item_id);
let loc = Some(WellFormedLoc::Ty(item_id));
let item_ty = wfcx.deeply_normalize(span, loc, ty);
let is_foreign_item = tcx.is_foreign_item(item_id);
let is_structurally_foreign_item =
||
{
let tail =
tcx.struct_tail_raw(item_ty, &ObligationCause::dummy(),
|ty| wfcx.deeply_normalize(span, loc, ty), || {});
#[allow(non_exhaustive_omitted_patterns)]
match tail.kind() { ty::Foreign(_) => true, _ => false, }
};
let forbid_unsized =
!(is_foreign_item && is_structurally_foreign_item());
wfcx.register_wf_obligation(span,
Some(WellFormedLoc::Ty(item_id)), item_ty.into());
if forbid_unsized {
let span = tcx.def_span(item_id);
wfcx.register_bound(traits::ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::SizedConstOrStatic),
wfcx.param_env, item_ty,
tcx.require_lang_item(LangItem::Sized, span));
}
let should_check_for_sync =
should_check_for_sync && !is_foreign_item &&
tcx.static_mutability(item_id.to_def_id()) ==
Some(hir::Mutability::Not) &&
!tcx.is_thread_local_static(item_id.to_def_id());
if should_check_for_sync {
wfcx.register_bound(traits::ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::SharedStatic),
wfcx.param_env, item_ty,
tcx.require_lang_item(LangItem::Sync, span));
}
Ok(())
})
}
}
}#[instrument(level = "debug", skip(tcx))]
1224pub(crate) fn check_static_item<'tcx>(
1225 tcx: TyCtxt<'tcx>,
1226 item_id: LocalDefId,
1227 ty: Ty<'tcx>,
1228 should_check_for_sync: bool,
1229) -> Result<(), ErrorGuaranteed> {
1230 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1231 let span = tcx.ty_span(item_id);
1232 let loc = Some(WellFormedLoc::Ty(item_id));
1233 let item_ty = wfcx.deeply_normalize(span, loc, ty);
1234
1235 let is_foreign_item = tcx.is_foreign_item(item_id);
1236 let is_structurally_foreign_item = || {
1237 let tail = tcx.struct_tail_raw(
1238 item_ty,
1239 &ObligationCause::dummy(),
1240 |ty| wfcx.deeply_normalize(span, loc, ty),
1241 || {},
1242 );
1243
1244 matches!(tail.kind(), ty::Foreign(_))
1245 };
1246 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1247
1248 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1249 if forbid_unsized {
1250 let span = tcx.def_span(item_id);
1251 wfcx.register_bound(
1252 traits::ObligationCause::new(
1253 span,
1254 wfcx.body_def_id,
1255 ObligationCauseCode::SizedConstOrStatic,
1256 ),
1257 wfcx.param_env,
1258 item_ty,
1259 tcx.require_lang_item(LangItem::Sized, span),
1260 );
1261 }
1262
1263 let should_check_for_sync = should_check_for_sync
1265 && !is_foreign_item
1266 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1267 && !tcx.is_thread_local_static(item_id.to_def_id());
1268
1269 if should_check_for_sync {
1270 wfcx.register_bound(
1271 traits::ObligationCause::new(
1272 span,
1273 wfcx.body_def_id,
1274 ObligationCauseCode::SharedStatic,
1275 ),
1276 wfcx.param_env,
1277 item_ty,
1278 tcx.require_lang_item(LangItem::Sync, span),
1279 );
1280 }
1281 Ok(())
1282 })
1283}
1284
1285#[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(1285u32),
::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))]
1286pub(super) fn check_type_const<'tcx>(
1287 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1288 def_id: LocalDefId,
1289 item_ty: Ty<'tcx>,
1290 has_value: bool,
1291) -> Result<(), ErrorGuaranteed> {
1292 let tcx = wfcx.tcx();
1293 let span = tcx.def_span(def_id);
1294
1295 wfcx.register_bound(
1296 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1297 wfcx.param_env,
1298 item_ty,
1299 tcx.require_lang_item(LangItem::ConstParamTy, span),
1300 );
1301
1302 if has_value {
1303 let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1304 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1305 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1306
1307 wfcx.register_obligation(Obligation::new(
1308 tcx,
1309 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1310 wfcx.param_env,
1311 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1312 ));
1313 }
1314 Ok(())
1315}
1316
1317#[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(1317u32),
::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_ok().coherent_trait(trait_ref.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:1389",
"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(1389u32),
::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();
let self_ty =
wfcx.deeply_normalize(item.span,
Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
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_))]
1318fn check_impl<'tcx>(
1319 tcx: TyCtxt<'tcx>,
1320 item: &'tcx hir::Item<'tcx>,
1321 impl_: &hir::Impl<'_>,
1322) -> Result<(), ErrorGuaranteed> {
1323 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1324 match impl_.of_trait {
1325 Some(of_trait) => {
1326 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1330 tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1333 let trait_span = of_trait.trait_ref.path.span;
1334 let trait_ref = wfcx.deeply_normalize(
1335 trait_span,
1336 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1337 trait_ref,
1338 );
1339 let trait_pred =
1340 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1341 let mut obligations = traits::wf::trait_obligations(
1342 wfcx.infcx,
1343 wfcx.param_env,
1344 wfcx.body_def_id,
1345 trait_pred,
1346 trait_span,
1347 item,
1348 );
1349 for obligation in &mut obligations {
1350 if obligation.cause.span != trait_span {
1351 continue;
1353 }
1354 if let Some(pred) = obligation.predicate.as_trait_clause()
1355 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1356 {
1357 obligation.cause.span = impl_.self_ty.span;
1358 }
1359 if let Some(pred) = obligation.predicate.as_projection_clause()
1360 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1361 {
1362 obligation.cause.span = impl_.self_ty.span;
1363 }
1364 }
1365
1366 if tcx.is_conditionally_const(item.owner_id.def_id) {
1368 for (bound, _) in
1369 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1370 {
1371 let bound = wfcx.normalize(
1372 item.span,
1373 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1374 bound,
1375 );
1376 wfcx.register_obligation(Obligation::new(
1377 tcx,
1378 ObligationCause::new(
1379 impl_.self_ty.span,
1380 wfcx.body_def_id,
1381 ObligationCauseCode::WellFormed(None),
1382 ),
1383 wfcx.param_env,
1384 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1385 ))
1386 }
1387 }
1388
1389 debug!(?obligations);
1390 wfcx.register_obligations(obligations);
1391 }
1392 None => {
1393 let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1394 let self_ty = wfcx.deeply_normalize(
1395 item.span,
1396 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1397 self_ty,
1398 );
1399 wfcx.register_wf_obligation(
1400 impl_.self_ty.span,
1401 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1402 self_ty.into(),
1403 );
1404 }
1405 }
1406
1407 check_where_clauses(wfcx, item.owner_id.def_id);
1408 Ok(())
1409 })
1410}
1411
1412#[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(1413u32),
::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)
{
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)
}
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();
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)
&& !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.has_non_region_param() ||
param_count.params.len() > 1 || has_region {
None
} else if predicates.predicates.iter().any(|&(p, _)|
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 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);
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, sp)
});
let obligations: Vec<_> =
wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
wfcx.register_obligations(obligations);
}
}
}#[instrument(level = "debug", skip(wfcx))]
1414pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1415 let infcx = wfcx.infcx;
1416 let tcx = wfcx.tcx();
1417
1418 let predicates = tcx.predicates_of(def_id.to_def_id());
1419 let generics = tcx.generics_of(def_id);
1420
1421 for param in &generics.own_params {
1428 if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1429 if !default.has_param() {
1436 wfcx.register_wf_obligation(
1437 tcx.def_span(param.def_id),
1438 matches!(param.kind, GenericParamDefKind::Type { .. })
1439 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1440 default.as_term().unwrap(),
1441 );
1442 } else {
1443 let GenericArgKind::Const(ct) = default.kind() else {
1446 continue;
1447 };
1448
1449 let ct_ty = match ct.kind() {
1450 ty::ConstKind::Infer(_)
1451 | ty::ConstKind::Placeholder(_)
1452 | ty::ConstKind::Bound(_, _) => unreachable!(),
1453 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1454 ty::ConstKind::Value(cv) => cv.ty,
1455 ty::ConstKind::Unevaluated(uv) => {
1456 infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1457 }
1458 ty::ConstKind::Param(param_ct) => {
1459 param_ct.find_const_ty_from_env(wfcx.param_env)
1460 }
1461 };
1462
1463 let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1464 if !ct_ty.has_param() && !param_ty.has_param() {
1465 let cause = traits::ObligationCause::new(
1466 tcx.def_span(param.def_id),
1467 wfcx.body_def_id,
1468 ObligationCauseCode::WellFormed(None),
1469 );
1470 wfcx.register_obligation(Obligation::new(
1471 tcx,
1472 cause,
1473 wfcx.param_env,
1474 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1475 ));
1476 }
1477 }
1478 }
1479 }
1480
1481 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1490 if param.index >= generics.parent_count as u32
1491 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1493 && !default.has_param()
1495 {
1496 return default;
1498 }
1499 tcx.mk_param_from_def(param)
1500 });
1501
1502 let default_obligations = predicates
1504 .predicates
1505 .iter()
1506 .flat_map(|&(pred, sp)| {
1507 #[derive(Default)]
1508 struct CountParams {
1509 params: FxHashSet<u32>,
1510 }
1511 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1512 type Result = ControlFlow<()>;
1513 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1514 if let ty::Param(param) = t.kind() {
1515 self.params.insert(param.index);
1516 }
1517 t.super_visit_with(self)
1518 }
1519
1520 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1521 ControlFlow::Break(())
1522 }
1523
1524 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1525 if let ty::ConstKind::Param(param) = c.kind() {
1526 self.params.insert(param.index);
1527 }
1528 c.super_visit_with(self)
1529 }
1530 }
1531 let mut param_count = CountParams::default();
1532 let has_region = pred.visit_with(&mut param_count).is_break();
1533 let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1534 if instantiated_pred.has_non_region_param()
1537 || param_count.params.len() > 1
1538 || has_region
1539 {
1540 None
1541 } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1542 None
1544 } else {
1545 Some((instantiated_pred, sp))
1546 }
1547 })
1548 .map(|(pred, sp)| {
1549 let pred = wfcx.normalize(sp, None, pred);
1559 let cause = traits::ObligationCause::new(
1560 sp,
1561 wfcx.body_def_id,
1562 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1563 );
1564 Obligation::new(tcx, cause, wfcx.param_env, pred)
1565 });
1566
1567 let predicates = predicates.instantiate_identity(tcx);
1568
1569 let assoc_const_obligations: Vec<_> = predicates
1570 .predicates
1571 .iter()
1572 .copied()
1573 .zip(predicates.spans.iter().copied())
1574 .filter_map(|(clause, sp)| {
1575 let proj = clause.as_projection_clause()?;
1576 let pred_binder = proj
1577 .map_bound(|pred| {
1578 pred.term.as_const().map(|ct| {
1579 let assoc_const_ty = tcx
1580 .type_of(pred.projection_term.def_id)
1581 .instantiate(tcx, pred.projection_term.args);
1582 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1583 })
1584 })
1585 .transpose();
1586 pred_binder.map(|pred_binder| {
1587 let cause = traits::ObligationCause::new(
1588 sp,
1589 wfcx.body_def_id,
1590 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1591 );
1592 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1593 })
1594 })
1595 .collect();
1596
1597 assert_eq!(predicates.predicates.len(), predicates.spans.len());
1598 let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1599 traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1600 });
1601 let obligations: Vec<_> =
1602 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1603 wfcx.register_obligations(obligations);
1604}
1605
1606#[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(1606u32),
::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,
}), 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))]
1607fn check_fn_or_method<'tcx>(
1608 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1609 sig: ty::PolyFnSig<'tcx>,
1610 hir_decl: &hir::FnDecl<'_>,
1611 def_id: LocalDefId,
1612) {
1613 let tcx = wfcx.tcx();
1614 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1615
1616 let arg_span =
1622 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1623
1624 sig.inputs_and_output =
1625 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1626 wfcx.deeply_normalize(
1627 arg_span(idx),
1628 Some(WellFormedLoc::Param {
1629 function: def_id,
1630 param_idx: idx,
1633 }),
1634 ty,
1635 )
1636 }));
1637
1638 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1639 wfcx.register_wf_obligation(
1640 arg_span(idx),
1641 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1642 ty.into(),
1643 );
1644 }
1645
1646 check_where_clauses(wfcx, def_id);
1647
1648 if sig.abi == ExternAbi::RustCall {
1649 let span = tcx.def_span(def_id);
1650 let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1651 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1652 if let Some(ty) = inputs.next() {
1654 wfcx.register_bound(
1655 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1656 wfcx.param_env,
1657 *ty,
1658 tcx.require_lang_item(hir::LangItem::Tuple, span),
1659 );
1660 wfcx.register_bound(
1661 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1662 wfcx.param_env,
1663 *ty,
1664 tcx.require_lang_item(hir::LangItem::Sized, span),
1665 );
1666 } else {
1667 tcx.dcx().span_err(
1668 hir_decl.inputs.last().map_or(span, |input| input.span),
1669 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1670 );
1671 }
1672 if inputs.next().is_some() {
1674 tcx.dcx().span_err(
1675 hir_decl.inputs.last().map_or(span, |input| input.span),
1676 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1677 );
1678 }
1679 }
1680
1681 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1683 let span = match hir_decl.output {
1684 hir::FnRetTy::Return(ty) => ty.span,
1685 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1686 };
1687
1688 wfcx.register_bound(
1689 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1690 wfcx.param_env,
1691 sig.output(),
1692 tcx.require_lang_item(LangItem::Sized, span),
1693 );
1694 }
1695}
1696
1697#[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)]
1699enum ArbitrarySelfTypesLevel {
1700 Basic, WithPointers, }
1703
1704#[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(1704u32),
::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();
let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
let sig = wfcx.normalize(DUMMY_SP, loc, 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:1724",
"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(1724u32),
::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, self_ty);
let receiver_ty = sig.inputs()[0];
let receiver_ty = wfcx.normalize(DUMMY_SP, loc, 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))]
1705fn check_method_receiver<'tcx>(
1706 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1707 fn_sig: &hir::FnSig<'_>,
1708 method: ty::AssocItem,
1709 self_ty: Ty<'tcx>,
1710) -> Result<(), ErrorGuaranteed> {
1711 let tcx = wfcx.tcx();
1712
1713 if !method.is_method() {
1714 return Ok(());
1715 }
1716
1717 let span = fn_sig.decl.inputs[0].span;
1718 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1719
1720 let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1721 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1722 let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1723
1724 debug!("check_method_receiver: sig={:?}", sig);
1725
1726 let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1727
1728 let receiver_ty = sig.inputs()[0];
1729 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1730
1731 receiver_ty.error_reported()?;
1734
1735 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1736 Some(ArbitrarySelfTypesLevel::WithPointers)
1737 } else if tcx.features().arbitrary_self_types() {
1738 Some(ArbitrarySelfTypesLevel::Basic)
1739 } else {
1740 None
1741 };
1742 let generics = tcx.generics_of(method.def_id);
1743
1744 let receiver_validity =
1745 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1746 if let Err(receiver_validity_err) = receiver_validity {
1747 return Err(match arbitrary_self_types_level {
1748 None if receiver_is_valid(
1752 wfcx,
1753 span,
1754 receiver_ty,
1755 self_ty,
1756 Some(ArbitrarySelfTypesLevel::Basic),
1757 generics,
1758 )
1759 .is_ok() =>
1760 {
1761 feature_err(
1763 &tcx.sess,
1764 sym::arbitrary_self_types,
1765 span,
1766 format!(
1767 "`{receiver_ty}` cannot be used as the type of `self` without \
1768 the `arbitrary_self_types` feature",
1769 ),
1770 )
1771 .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>`"))
1772 .emit()
1773 }
1774 None | Some(ArbitrarySelfTypesLevel::Basic)
1775 if receiver_is_valid(
1776 wfcx,
1777 span,
1778 receiver_ty,
1779 self_ty,
1780 Some(ArbitrarySelfTypesLevel::WithPointers),
1781 generics,
1782 )
1783 .is_ok() =>
1784 {
1785 feature_err(
1787 &tcx.sess,
1788 sym::arbitrary_self_types_pointers,
1789 span,
1790 format!(
1791 "`{receiver_ty}` cannot be used as the type of `self` without \
1792 the `arbitrary_self_types_pointers` feature",
1793 ),
1794 )
1795 .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>`"))
1796 .emit()
1797 }
1798 _ =>
1799 {
1801 match receiver_validity_err {
1802 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1803 let hint = match receiver_ty
1804 .builtin_deref(false)
1805 .unwrap_or(receiver_ty)
1806 .ty_adt_def()
1807 .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1808 {
1809 Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1810 Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1811 _ => None,
1812 };
1813
1814 tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1815 }
1816 ReceiverValidityError::DoesNotDeref => {
1817 tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1818 span,
1819 receiver_ty,
1820 })
1821 }
1822 ReceiverValidityError::MethodGenericParamUsed => {
1823 tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1824 }
1825 }
1826 }
1827 });
1828 }
1829 Ok(())
1830}
1831
1832enum ReceiverValidityError {
1836 DoesNotDeref,
1839 MethodGenericParamUsed,
1841}
1842
1843fn confirm_type_is_not_a_method_generic_param(
1846 ty: Ty<'_>,
1847 method_generics: &ty::Generics,
1848) -> Result<(), ReceiverValidityError> {
1849 if let ty::Param(param) = ty.kind() {
1850 if (param.index as usize) >= method_generics.parent_count {
1851 return Err(ReceiverValidityError::MethodGenericParamUsed);
1852 }
1853 }
1854 Ok(())
1855}
1856
1857fn receiver_is_valid<'tcx>(
1867 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1868 span: Span,
1869 receiver_ty: Ty<'tcx>,
1870 self_ty: Ty<'tcx>,
1871 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1872 method_generics: &ty::Generics,
1873) -> Result<(), ReceiverValidityError> {
1874 let infcx = wfcx.infcx;
1875 let tcx = wfcx.tcx();
1876 let cause =
1877 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1878
1879 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1881 let ocx = ObligationCtxt::new(wfcx.infcx);
1882 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1883 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1884 Ok(())
1885 } else {
1886 Err(NoSolution)
1887 }
1888 }) {
1889 return Ok(());
1890 }
1891
1892 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1893
1894 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1895
1896 if arbitrary_self_types_enabled.is_some() {
1900 autoderef = autoderef.use_receiver_trait();
1901 }
1902
1903 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1905 autoderef = autoderef.include_raw_pointers();
1906 }
1907
1908 while let Some((potential_self_ty, _)) = autoderef.next() {
1910 {
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:1910",
"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(1910u32),
::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!(
1911 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1912 potential_self_ty, self_ty
1913 );
1914
1915 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1916
1917 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1920 let ocx = ObligationCtxt::new(wfcx.infcx);
1921 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1922 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1923 Ok(())
1924 } else {
1925 Err(NoSolution)
1926 }
1927 }) {
1928 wfcx.register_obligations(autoderef.into_obligations());
1929 return Ok(());
1930 }
1931
1932 if arbitrary_self_types_enabled.is_none() {
1935 let legacy_receiver_trait_def_id =
1936 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1937 if !legacy_receiver_is_implemented(
1938 wfcx,
1939 legacy_receiver_trait_def_id,
1940 cause.clone(),
1941 potential_self_ty,
1942 ) {
1943 break;
1945 }
1946
1947 wfcx.register_bound(
1949 cause.clone(),
1950 wfcx.param_env,
1951 potential_self_ty,
1952 legacy_receiver_trait_def_id,
1953 );
1954 }
1955 }
1956
1957 {
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:1957",
"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(1957u32),
::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);
1958 Err(ReceiverValidityError::DoesNotDeref)
1959}
1960
1961fn legacy_receiver_is_implemented<'tcx>(
1962 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1963 legacy_receiver_trait_def_id: DefId,
1964 cause: ObligationCause<'tcx>,
1965 receiver_ty: Ty<'tcx>,
1966) -> bool {
1967 let tcx = wfcx.tcx();
1968 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1969
1970 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1971
1972 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1973 true
1974 } else {
1975 {
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:1975",
"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(1975u32),
::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!(
1976 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1977 receiver_ty
1978 );
1979 false
1980 }
1981}
1982
1983pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1984 match tcx.def_kind(def_id) {
1985 DefKind::Enum | DefKind::Struct | DefKind::Union => {
1986 }
1988 DefKind::TyAlias => {
1989 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!(
1990 tcx.type_alias_is_lazy(def_id),
1991 "should not be computing variance of non-free type alias"
1992 );
1993 }
1994 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:?}"),
1995 }
1996
1997 let ty_predicates = tcx.predicates_of(def_id);
1998 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);
1999 let variances = tcx.variances_of(def_id);
2000
2001 let mut constrained_parameters: FxHashSet<_> = variances
2002 .iter()
2003 .enumerate()
2004 .filter(|&(_, &variance)| variance != ty::Bivariant)
2005 .map(|(index, _)| Parameter(index as u32))
2006 .collect();
2007
2008 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
2009
2010 let explicitly_bounded_params = LazyCell::new(|| {
2012 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2013 tcx.hir_node_by_def_id(def_id)
2014 .generics()
2015 .unwrap()
2016 .predicates
2017 .iter()
2018 .filter_map(|predicate| match predicate.kind {
2019 hir::WherePredicateKind::BoundPredicate(predicate) => {
2020 match icx.lower_ty(predicate.bounded_ty).kind() {
2021 ty::Param(data) => Some(Parameter(data.index)),
2022 _ => None,
2023 }
2024 }
2025 _ => None,
2026 })
2027 .collect::<FxHashSet<_>>()
2028 });
2029
2030 for (index, _) in variances.iter().enumerate() {
2031 let parameter = Parameter(index as u32);
2032
2033 if constrained_parameters.contains(¶meter) {
2034 continue;
2035 }
2036
2037 let node = tcx.hir_node_by_def_id(def_id);
2038 let item = node.expect_item();
2039 let hir_generics = node.generics().unwrap();
2040 let hir_param = &hir_generics.params[index];
2041
2042 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2043
2044 if ty_param.def_id != hir_param.def_id.into() {
2045 tcx.dcx().span_delayed_bug(
2053 hir_param.span,
2054 "hir generics and ty generics in different order",
2055 );
2056 continue;
2057 }
2058
2059 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2061 .type_of(def_id)
2062 .instantiate_identity()
2063 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2064 {
2065 continue;
2066 }
2067
2068 match hir_param.name {
2069 hir::ParamName::Error(_) => {
2070 }
2073 _ => {
2074 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2075 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2076 }
2077 }
2078 }
2079}
2080
2081struct HasErrorDeep<'tcx> {
2083 tcx: TyCtxt<'tcx>,
2084 seen: FxHashSet<DefId>,
2085}
2086impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2087 type Result = ControlFlow<ErrorGuaranteed>;
2088
2089 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2090 match *ty.kind() {
2091 ty::Adt(def, _) => {
2092 if self.seen.insert(def.did()) {
2093 for field in def.all_fields() {
2094 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2095 }
2096 }
2097 }
2098 ty::Error(guar) => return ControlFlow::Break(guar),
2099 _ => {}
2100 }
2101 ty.super_visit_with(self)
2102 }
2103
2104 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2105 if let Err(guar) = r.error_reported() {
2106 ControlFlow::Break(guar)
2107 } else {
2108 ControlFlow::Continue(())
2109 }
2110 }
2111
2112 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2113 if let Err(guar) = c.error_reported() {
2114 ControlFlow::Break(guar)
2115 } else {
2116 ControlFlow::Continue(())
2117 }
2118 }
2119}
2120
2121fn report_bivariance<'tcx>(
2122 tcx: TyCtxt<'tcx>,
2123 param: &'tcx hir::GenericParam<'tcx>,
2124 has_explicit_bounds: bool,
2125 item: &'tcx hir::Item<'tcx>,
2126) -> ErrorGuaranteed {
2127 let param_name = param.name.ident();
2128
2129 let help = match item.kind {
2130 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2131 if let Some(def_id) = tcx.lang_items().phantom_data() {
2132 errors::UnusedGenericParameterHelp::Adt {
2133 param_name,
2134 phantom_data: tcx.def_path_str(def_id),
2135 }
2136 } else {
2137 errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2138 }
2139 }
2140 ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2141 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:?}"),
2142 };
2143
2144 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2145 intravisit::walk_item(
2146 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2147 item,
2148 );
2149
2150 if !usage_spans.is_empty() {
2151 let item_def_id = item.owner_id.to_def_id();
2155 let is_probably_cyclical =
2156 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2157 .visit_def(item_def_id)
2158 .is_break();
2159 if is_probably_cyclical {
2168 return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2169 spans: usage_spans,
2170 param_span: param.span,
2171 param_name,
2172 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2173 help,
2174 note: (),
2175 });
2176 }
2177 }
2178
2179 let const_param_help =
2180 #[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);
2181
2182 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2183 span: param.span,
2184 param_name,
2185 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2186 usage_spans,
2187 help,
2188 const_param_help,
2189 });
2190 diag.code(E0392);
2191 if item.kind.recovered() {
2192 diag.delay_as_bug()
2194 } else {
2195 diag.emit()
2196 }
2197}
2198
2199struct IsProbablyCyclical<'tcx> {
2205 tcx: TyCtxt<'tcx>,
2206 item_def_id: DefId,
2207 seen: FxHashSet<DefId>,
2208}
2209
2210impl<'tcx> IsProbablyCyclical<'tcx> {
2211 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2212 match self.tcx.def_kind(def_id) {
2213 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2214 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2215 self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2216 })
2217 }
2218 DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2219 self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2220 }
2221 _ => ControlFlow::Continue(()),
2222 }
2223 }
2224}
2225
2226impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2227 type Result = ControlFlow<(), ()>;
2228
2229 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2230 let def_id = match ty.kind() {
2231 ty::Adt(adt_def, _) => Some(adt_def.did()),
2232 ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2233 _ => None,
2234 };
2235 if let Some(def_id) = def_id {
2236 if def_id == self.item_def_id {
2237 return ControlFlow::Break(());
2238 }
2239 if self.seen.insert(def_id) {
2240 self.visit_def(def_id)?;
2241 }
2242 }
2243 ty.super_visit_with(self)
2244 }
2245}
2246
2247struct CollectUsageSpans<'a> {
2252 spans: &'a mut Vec<Span>,
2253 param_def_id: DefId,
2254}
2255
2256impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2257 type Result = ();
2258
2259 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2260 }
2262
2263 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2264 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2265 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2266 && def_id == self.param_def_id
2267 {
2268 self.spans.push(t.span);
2269 return;
2270 } else if let Res::SelfTyAlias { .. } = qpath.res {
2271 self.spans.push(t.span);
2272 return;
2273 }
2274 }
2275 intravisit::walk_ty(self, t);
2276 }
2277}
2278
2279impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2280 #[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(2282u32),
::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, 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))]
2283 fn check_false_global_bounds(&mut self) {
2284 let tcx = self.ocx.infcx.tcx;
2285 let mut span = tcx.def_span(self.body_def_id);
2286 let empty_env = ty::ParamEnv::empty();
2287
2288 let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2289 let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2291
2292 for (pred, obligation_span) in implied_obligations {
2293 match pred.kind().skip_binder() {
2294 ty::ClauseKind::WellFormed(..)
2298 | ty::ClauseKind::UnstableFeature(..) => continue,
2300 _ => {}
2301 }
2302
2303 if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2305 let pred = self.normalize(span, None, pred);
2306
2307 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2309 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2310 span = predicates
2311 .iter()
2312 .find(|pred| pred.span.contains(obligation_span))
2314 .map(|pred| pred.span)
2315 .unwrap_or(obligation_span);
2316 }
2317
2318 let obligation = Obligation::new(
2319 tcx,
2320 traits::ObligationCause::new(
2321 span,
2322 self.body_def_id,
2323 ObligationCauseCode::TrivialBound,
2324 ),
2325 empty_env,
2326 pred,
2327 );
2328 self.ocx.register_obligation(obligation);
2329 }
2330 }
2331 }
2332}
2333
2334pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2335 let items = tcx.hir_crate_items(());
2336 let res = items
2337 .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2338 .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2339 .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2340 .and(
2341 items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2342 )
2343 .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2344 .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2345 super::entry::check_for_entry_fn(tcx);
2346
2347 res
2348}
2349
2350fn lint_redundant_lifetimes<'tcx>(
2351 tcx: TyCtxt<'tcx>,
2352 owner_id: LocalDefId,
2353 outlives_env: &OutlivesEnvironment<'tcx>,
2354) {
2355 let def_kind = tcx.def_kind(owner_id);
2356 match def_kind {
2357 DefKind::Struct
2358 | DefKind::Union
2359 | DefKind::Enum
2360 | DefKind::Trait
2361 | DefKind::TraitAlias
2362 | DefKind::Fn
2363 | DefKind::Const
2364 | DefKind::Impl { of_trait: _ } => {
2365 }
2367 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2368 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2369 return;
2374 }
2375 }
2376 DefKind::Mod
2377 | DefKind::Variant
2378 | DefKind::TyAlias
2379 | DefKind::ForeignTy
2380 | DefKind::TyParam
2381 | DefKind::ConstParam
2382 | DefKind::Static { .. }
2383 | DefKind::Ctor(_, _)
2384 | DefKind::Macro(_)
2385 | DefKind::ExternCrate
2386 | DefKind::Use
2387 | DefKind::ForeignMod
2388 | DefKind::AnonConst
2389 | DefKind::InlineConst
2390 | DefKind::OpaqueTy
2391 | DefKind::Field
2392 | DefKind::LifetimeParam
2393 | DefKind::GlobalAsm
2394 | DefKind::Closure
2395 | DefKind::SyntheticCoroutineBody => return,
2396 }
2397
2398 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];
2407 lifetimes.extend(
2408 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2409 );
2410 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2412 for (idx, var) in
2413 tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2414 {
2415 let ty::BoundVariableKind::Region(kind) = var else { continue };
2416 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2417 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2418 }
2419 }
2420 lifetimes.retain(|candidate| candidate.is_named(tcx));
2421
2422 let mut shadowed = FxHashSet::default();
2426
2427 for (idx, &candidate) in lifetimes.iter().enumerate() {
2428 if shadowed.contains(&candidate) {
2433 continue;
2434 }
2435
2436 for &victim in &lifetimes[(idx + 1)..] {
2437 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2445 continue;
2446 };
2447
2448 if tcx.parent(def_id) != owner_id.to_def_id() {
2453 continue;
2454 }
2455
2456 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2458 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2459 {
2460 shadowed.insert(victim);
2461 tcx.emit_node_span_lint(
2462 rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2463 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2464 tcx.def_span(def_id),
2465 RedundantLifetimeArgsLint { candidate, victim },
2466 );
2467 }
2468 }
2469 }
2470}
2471
2472#[derive(const _: () =
{
impl<'__a, 'tcx> rustc_errors::LintDiagnostic<'__a, ()> for
RedundantLifetimeArgsLint<'tcx> {
#[track_caller]
fn decorate_lint<'__b>(self,
diag: &'__b mut rustc_errors::Diag<'__a, ()>) {
match self {
RedundantLifetimeArgsLint {
victim: __binding_0, candidate: __binding_1 } => {
diag.primary_message(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
}
};
}
}
};LintDiagnostic)]
2473#[diag("unnecessary lifetime parameter `{$victim}`")]
2474#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2475struct RedundantLifetimeArgsLint<'tcx> {
2476 victim: ty::Region<'tcx>,
2478 candidate: ty::Region<'tcx>,
2480}