1use std::cell::LazyCell;
2use std::ops::{ControlFlow, Deref};
3
4use hir::intravisit::{self, Visitor};
5use rustc_abi::{ExternAbi, ScalableElt};
6use rustc_ast as ast;
7use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
8use rustc_data_structures::transitive_relation::TransitiveRelationBuilder;
9use rustc_errors::codes::*;
10use rustc_errors::{Applicability, ErrorGuaranteed, msg, pluralize, struct_span_code_err};
11use rustc_hir as hir;
12use rustc_hir::attrs::lang_items::LangItem;
13use rustc_hir::attrs::{EiiDecl, EiiImpl, EiiImplResolution};
14use rustc_hir::def::{DefKind, Res};
15use rustc_hir::def_id::{DefId, LocalDefId};
16use rustc_hir::{AmbigArg, ItemKind, find_attr};
17use rustc_infer::infer::outlives::env::OutlivesEnvironment;
18use rustc_infer::infer::{BoundRegionConversionTime, SolverRegionConstraint, TyCtxtInferExt};
19use rustc_infer::traits::{PredicateObligations, TraitErrors};
20use rustc_lint_defs::builtin::{REDUNDANT_LIFETIMES, SHADOWING_SUPERTRAIT_ITEMS};
21use rustc_macros::{Diagnostic, TypeFoldable, TypeVisitable};
22use rustc_middle::mir::interpret::ErrorHandled;
23use rustc_middle::traits::solve::NoSolution;
24use rustc_middle::ty::region_constraint::{And, LeafRegionConstraint, Or};
25use rustc_middle::ty::trait_def::TraitSpecializationKind;
26use rustc_middle::ty::{
27 self, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags, TypeFoldable,
28 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
29 Upcast,
30};
31use rustc_session::diagnostics::feature_err;
32use rustc_span::{DUMMY_SP, Span, bug, span_bug, sym};
33use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
34use rustc_trait_selection::regions::{
35 OutlivesEnvironmentBuildExt, region_known_to_outlive, ty_known_to_outlive,
36};
37use rustc_trait_selection::traits::misc::{
38 ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
39};
40use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
41use rustc_trait_selection::traits::{
42 self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
43 WellFormedLoc,
44};
45use tracing::{debug, instrument};
46
47use super::compare_eii::{compare_eii_function_types, compare_eii_statics};
48use crate::autoderef::Autoderef;
49use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
50use crate::diagnostics;
51use crate::diagnostics::InvalidReceiverTyHint;
52
53pub(super) struct WfCheckingCtxt<'a, 'tcx> {
54 pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
55 body_def_id: LocalDefId,
56 param_env: ty::ParamEnv<'tcx>,
57}
58impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
59 type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
60 fn deref(&self) -> &Self::Target {
61 &self.ocx
62 }
63}
64
65impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
66 fn tcx(&self) -> TyCtxt<'tcx> {
67 self.ocx.infcx.tcx
68 }
69
70 fn normalize<T>(
73 &self,
74 span: Span,
75 loc: Option<WellFormedLoc>,
76 value: Unnormalized<'tcx, T>,
77 ) -> T
78 where
79 T: TypeFoldable<TyCtxt<'tcx>>,
80 {
81 self.ocx.normalize(
82 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
83 self.param_env,
84 value,
85 )
86 }
87
88 pub(super) fn deeply_normalize<T>(
98 &self,
99 span: Span,
100 loc: Option<WellFormedLoc>,
101 value: Unnormalized<'tcx, T>,
102 ) -> T
103 where
104 T: TypeFoldable<TyCtxt<'tcx>>,
105 {
106 if self.infcx.next_trait_solver() {
107 match self.ocx.deeply_normalize(
108 &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
109 self.param_env,
110 value.clone(),
111 ) {
112 Ok(value) => value,
113 Err(errors) => {
114 self.infcx.err_ctxt().report_fulfillment_errors(errors);
115 value.skip_norm_wip()
116 }
117 }
118 } else {
119 self.normalize(span, loc, value)
120 }
121 }
122
123 pub(super) fn register_wf_obligation(
124 &self,
125 span: Span,
126 loc: Option<WellFormedLoc>,
127 term: ty::Term<'tcx>,
128 ) {
129 let cause = traits::ObligationCause::new(
130 span,
131 self.body_def_id,
132 ObligationCauseCode::WellFormed(loc),
133 );
134 self.ocx.register_obligation(Obligation::new(
135 self.tcx(),
136 cause,
137 self.param_env,
138 ty::ClauseKind::WellFormed(term),
139 ));
140 }
141
142 pub(super) fn unnormalized_obligations(
143 &self,
144 span: Span,
145 ty: Ty<'tcx>,
146 ) -> Option<PredicateObligations<'tcx>> {
147 traits::wf::unnormalized_obligations(
148 self.ocx.infcx,
149 self.param_env,
150 ty.into(),
151 span,
152 self.body_def_id,
153 )
154 }
155}
156
157pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
158 tcx: TyCtxt<'tcx>,
159 body_def_id: LocalDefId,
160 f: F,
161) -> Result<(), ErrorGuaranteed>
162where
163 F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
164{
165 let param_env = tcx.param_env(body_def_id);
166 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
167 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
168
169 let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
170
171 let ignore_bounds =
174 tcx.def_kind(body_def_id) == DefKind::TyAlias && !tcx.type_alias_is_checked(body_def_id);
175
176 if !ignore_bounds && !tcx.features().trivial_bounds() {
177 wfcx.check_false_global_bounds()
178 }
179 f(&mut wfcx)?;
180
181 let errors = wfcx.evaluate_obligations_error_on_ambiguity();
182 if let TraitErrors::HasErrors(errors) = errors {
183 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
184 }
185
186 let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
187 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:187",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(187u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("assumed_wf_types")
}> =
::tracing::__macro_support::FieldName::new("assumed_wf_types");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&assumed_wf_types)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?assumed_wf_types);
188
189 let infcx_compat = infcx.fork();
190
191 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
194 &infcx,
195 body_def_id,
196 param_env,
197 assumed_wf_types.iter().copied(),
198 true,
199 );
200
201 lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
202
203 let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
204 if errors.is_empty() {
205 return Ok(());
206 }
207
208 let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
209 &infcx_compat,
210 body_def_id,
211 param_env,
212 assumed_wf_types,
213 false,
216 );
217 let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
218 if errors_compat.is_empty() {
219 Ok(())
222 } else {
223 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
224 }
225}
226
227pub(super) fn check_well_formed(
228 tcx: TyCtxt<'_>,
229 def_id: LocalDefId,
230) -> Result<(), ErrorGuaranteed> {
231 let mut res = crate::check::check::check_item_type(tcx, def_id);
232
233 for param in &tcx.generics_of(def_id).own_params {
234 res = res.and(check_param_wf(tcx, param));
235 }
236
237 res
238}
239
240{}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(253u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn ::tracing::field::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:260",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(260u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.owner_id")
}> =
::tracing::__macro_support::FieldName::new("item.owner_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.name")
}> =
::tracing::__macro_support::FieldName::new("item.name");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item.owner_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tcx.def_path_str(def_id))
as &dyn ::tracing::field::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 {
bug_impl(None,
format_args!("impl_polarity query disagrees with impl\'s polarity in HIR"),
Location::caller());
};
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());
}
}
}
} else { res = res.and(check_impl(tcx, item, impl_)); }
res
}
hir::ItemKind::Fn { sig, .. } =>
check_item_fn(tcx, def_id, sig.decl),
_ =>
bug_impl(Some(item.span),
format_args!("should have been handled by the type based wf check: {0:?}",
item), Location::caller()),
}
}
}
}#[instrument(skip(tcx), level = "debug")]
254pub(super) fn check_item<'tcx>(
255 tcx: TyCtxt<'tcx>,
256 item: &'tcx hir::Item<'tcx>,
257) -> Result<(), ErrorGuaranteed> {
258 let def_id = item.owner_id.def_id;
259
260 debug!(
261 ?item.owner_id,
262 item.name = ? tcx.def_path_str(def_id)
263 );
264
265 match item.kind {
266 hir::ItemKind::Impl(ref impl_) => {
284 crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
285 let mut res = Ok(());
286 if let Some(of_trait) = impl_.of_trait {
287 let header = tcx.impl_trait_header(def_id);
288 let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
289 if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
290 let sp = of_trait.trait_ref.path.span;
291 res = Err(tcx
292 .dcx()
293 .struct_span_err(sp, "impls of auto traits cannot be default")
294 .with_span_labels(of_trait.defaultness_span, "default because of this")
295 .with_span_label(sp, "auto trait")
296 .emit());
297 }
298 match header.polarity {
299 ty::ImplPolarity::Positive => {
300 res = res.and(check_impl(tcx, item, impl_));
301 }
302 ty::ImplPolarity::Negative => {
303 let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
304 bug!("impl_polarity query disagrees with impl's polarity in HIR");
305 };
306 if let hir::Defaultness::Default { .. } = of_trait.defaultness {
308 let mut spans = vec![span];
309 spans.extend(of_trait.defaultness_span);
310 res = Err(struct_span_code_err!(
311 tcx.dcx(),
312 spans,
313 E0750,
314 "negative impls cannot be default impls"
315 )
316 .emit());
317 }
318 }
319 }
320 } else {
321 res = res.and(check_impl(tcx, item, impl_));
322 }
323 res
324 }
325 hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
326 _ => span_bug!(item.span, "should have been handled by the type based wf check: {item:?}"),
328 }
329}
330
331pub(super) fn check_foreign_item<'tcx>(
332 tcx: TyCtxt<'tcx>,
333 item: &'tcx hir::ForeignItem<'tcx>,
334) -> Result<(), ErrorGuaranteed> {
335 let def_id = item.owner_id.def_id;
336
337 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:337",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(337u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.owner_id")
}> =
::tracing::__macro_support::FieldName::new("item.owner_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item.name")
}> =
::tracing::__macro_support::FieldName::new("item.name");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item.owner_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tcx.def_path_str(def_id))
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
338 ?item.owner_id,
339 item.name = ? tcx.def_path_str(def_id)
340 );
341
342 match item.kind {
343 hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
344 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
345 }
346}
347
348pub(crate) fn check_trait_item<'tcx>(
349 tcx: TyCtxt<'tcx>,
350 def_id: LocalDefId,
351) -> Result<(), ErrorGuaranteed> {
352 lint_item_shadowing_supertrait_item(tcx, def_id);
354
355 let mut res = Ok(());
356
357 if tcx.def_kind(def_id) == DefKind::AssocFn {
358 for &assoc_ty_def_id in
359 tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
360 {
361 res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
362 }
363 }
364 res
365}
366
367pub(crate) fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
380 let mut required_bounds_by_item = FxIndexMap::default();
382 let associated_items = tcx.associated_items(trait_def_id);
383
384 loop {
390 let mut should_continue = false;
391 for gat_item in associated_items.in_definition_order() {
392 let gat_def_id = gat_item.def_id.expect_local();
393 let gat_item = tcx.associated_item(gat_def_id);
394 if !gat_item.is_type() {
396 continue;
397 }
398 let gat_generics = tcx.generics_of(gat_def_id);
399 if gat_generics.is_own_empty() {
401 continue;
402 }
403
404 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
408 for item in associated_items.in_definition_order() {
409 let item_def_id = item.def_id.expect_local();
410 if item_def_id == gat_def_id {
412 continue;
413 }
414
415 let param_env = tcx.param_env(item_def_id);
416
417 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
418 ty::AssocKind::Fn { .. } => {
420 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
424 item_def_id.to_def_id(),
425 tcx.fn_sig(item_def_id).instantiate_identity().skip_norm_wip(),
426 );
427 gather_gat_bounds(
428 tcx,
429 param_env,
430 item_def_id,
431 sig.inputs_and_output,
432 &sig.inputs().iter().copied().collect(),
435 gat_def_id,
436 gat_generics,
437 )
438 }
439 ty::AssocKind::Type { .. } => {
441 let param_env = augment_param_env(
445 tcx,
446 param_env,
447 required_bounds_by_item.get(&item_def_id),
448 );
449 gather_gat_bounds(
450 tcx,
451 param_env,
452 item_def_id,
453 tcx.explicit_item_bounds(item_def_id)
454 .iter_identity_copied()
455 .map(Unnormalized::skip_norm_wip)
456 .collect::<Vec<_>>(),
457 &FxIndexSet::default(),
458 gat_def_id,
459 gat_generics,
460 )
461 }
462 ty::AssocKind::Const { .. } => None,
463 };
464
465 if let Some(item_required_bounds) = item_required_bounds {
466 if let Some(new_required_bounds) = &mut new_required_bounds {
472 new_required_bounds.retain(|b| item_required_bounds.contains(b));
473 } else {
474 new_required_bounds = Some(item_required_bounds);
475 }
476 }
477 }
478
479 if let Some(new_required_bounds) = new_required_bounds {
480 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
481 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
482 should_continue = true;
485 }
486 }
487 }
488 if !should_continue {
493 break;
494 }
495 }
496
497 for (gat_def_id, required_bounds) in required_bounds_by_item {
498 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
500 continue;
501 }
502
503 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
504 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:504",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(504u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("required_bounds")
}> =
::tracing::__macro_support::FieldName::new("required_bounds");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&required_bounds)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?required_bounds);
505 let param_env = tcx.param_env(gat_def_id);
506
507 let unsatisfied_bounds: Vec<_> = required_bounds
508 .into_iter()
509 .filter(|clause| match clause.kind().skip_binder() {
510 ty::ClauseKind::RegionOutlives(ty::OutlivesClause(a, b)) => {
511 !region_known_to_outlive(
512 tcx,
513 gat_def_id,
514 param_env,
515 &FxIndexSet::default(),
516 a,
517 b,
518 )
519 }
520 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(a, b)) => {
521 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
522 }
523 _ => bug_impl(None, format_args!("Unexpected ClauseKind"), Location::caller())bug!("Unexpected ClauseKind"),
524 })
525 .map(|clause| clause.to_string())
526 .collect();
527
528 if !unsatisfied_bounds.is_empty() {
529 let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
530 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!(
531 "{} {}",
532 gat_item_hir.generics.add_where_or_trailing_comma(),
533 unsatisfied_bounds.join(", "),
534 );
535 let bound =
536 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
537 tcx.dcx()
538 .struct_span_err(
539 gat_item_hir.span,
540 ::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),
541 )
542 .with_span_suggestion(
543 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
544 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add the required where clause{0}",
plural))
})format!("add the required where clause{plural}"),
545 suggestion,
546 Applicability::MachineApplicable,
547 )
548 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
bound))
})format!(
549 "{bound} currently required to ensure that impls have maximum flexibility"
550 ))
551 .with_note(
552 "we are soliciting feedback, see issue #87479 \
553 <https://github.com/rust-lang/rust/issues/87479> for more information",
554 )
555 .emit();
556 }
557 }
558}
559
560fn augment_param_env<'tcx>(
562 tcx: TyCtxt<'tcx>,
563 param_env: ty::ParamEnv<'tcx>,
564 new_clauses: Option<&FxIndexSet<ty::Clause<'tcx>>>,
565) -> ty::ParamEnv<'tcx> {
566 let Some(new_clauses) = new_clauses else {
567 return param_env;
568 };
569
570 if new_clauses.is_empty() {
571 return param_env;
572 }
573
574 let bounds = param_env.caller_bounds().chain(new_clauses.iter().copied());
575 ty::ParamEnv::new(tcx, bounds)
578}
579
580fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
591 tcx: TyCtxt<'tcx>,
592 param_env: ty::ParamEnv<'tcx>,
593 item_def_id: LocalDefId,
594 to_check: T,
595 wf_tys: &FxIndexSet<Ty<'tcx>>,
596 gat_def_id: LocalDefId,
597 gat_generics: &'tcx ty::Generics,
598) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
599 let mut bounds = FxIndexSet::default();
601
602 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
603
604 if types.is_empty() && regions.is_empty() {
610 return None;
611 }
612
613 for (region_a, region_a_idx) in ®ions {
614 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
618 continue;
619 }
620 for (ty, ty_idx) in &types {
625 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
627 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:627",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(627u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty_idx")
}> =
::tracing::__macro_support::FieldName::new("ty_idx");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_a_idx")
}> =
::tracing::__macro_support::FieldName::new("region_a_idx");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_idx)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_a_idx)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?ty_idx, ?region_a_idx);
628 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:628",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(628u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
ty, region_a) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("required clause: {ty} must outlive {region_a}");
629 let ty_param = gat_generics.param_at(*ty_idx, tcx);
633 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
634 let region_param = gat_generics.param_at(*region_a_idx, tcx);
637 let region_param = ty::Region::new_early_param(
638 tcx,
639 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
640 );
641 bounds.insert(
644 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty_param, region_param))
645 .upcast(tcx),
646 );
647 }
648 }
649
650 for (region_b, region_b_idx) in ®ions {
655 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 {
659 continue;
660 }
661 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
662 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:662",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(662u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_a_idx")
}> =
::tracing::__macro_support::FieldName::new("region_a_idx");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("region_b_idx")
}> =
::tracing::__macro_support::FieldName::new("region_b_idx");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_a_idx)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_b_idx)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?region_a_idx, ?region_b_idx);
663 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:663",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(663u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("required clause: {0} must outlive {1}",
region_a, region_b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("required clause: {region_a} must outlive {region_b}");
664 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
666 let region_a_param = ty::Region::new_early_param(
667 tcx,
668 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
669 );
670 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
672 let region_b_param = ty::Region::new_early_param(
673 tcx,
674 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
675 );
676 bounds.insert(
678 ty::ClauseKind::RegionOutlives(ty::OutlivesClause(
679 region_a_param,
680 region_b_param,
681 ))
682 .upcast(tcx),
683 );
684 }
685 }
686 }
687
688 Some(bounds)
689}
690
691struct GATArgsCollector<'tcx> {
696 gat: DefId,
697 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
699 types: FxIndexSet<(Ty<'tcx>, usize)>,
701}
702
703impl<'tcx> GATArgsCollector<'tcx> {
704 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
705 gat: DefId,
706 t: T,
707 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
708 let mut visitor =
709 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
710 t.visit_with(&mut visitor);
711 (visitor.regions, visitor.types)
712 }
713}
714
715impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
716 fn visit_ty(&mut self, t: Ty<'tcx>) {
717 match t.kind() {
718 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
719 if def_id == self.gat =>
720 {
721 for (idx, arg) in args.iter().enumerate() {
722 match arg.kind() {
723 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
724 self.regions.insert((lt, idx));
725 }
726 GenericArgKind::Type(t) => {
727 self.types.insert((t, idx));
728 }
729 _ => {}
730 }
731 }
732 }
733 _ => {}
734 }
735 t.super_visit_with(self)
736 }
737}
738
739fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
740 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
741 let trait_def_id = tcx.local_parent(trait_item_def_id);
742
743 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
744 .skip(1)
745 .flat_map(|supertrait_def_id| {
746 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
747 })
748 .collect();
749 if !shadowed.is_empty() {
750 let shadowee = if let [shadowed] = shadowed[..] {
751 diagnostics::SupertraitItemShadowee::Labeled {
752 span: tcx.def_span(shadowed.def_id),
753 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
754 }
755 } else {
756 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
757 .iter()
758 .map(|item| {
759 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
760 })
761 .unzip();
762 diagnostics::SupertraitItemShadowee::Several {
763 traits: traits.into(),
764 spans: spans.into(),
765 }
766 };
767
768 tcx.emit_node_span_lint(
769 SHADOWING_SUPERTRAIT_ITEMS,
770 tcx.local_def_id_to_hir_id(trait_item_def_id),
771 tcx.def_span(trait_item_def_id),
772 diagnostics::SupertraitItemShadowing {
773 item: item_name,
774 subtrait: tcx.item_name(trait_def_id.to_def_id()),
775 shadowee,
776 },
777 );
778 }
779}
780
781fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
782 match param.kind {
783 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
785
786 ty::GenericParamDefKind::Const { .. } => {
788 let ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
789 let span = tcx.def_span(param.def_id);
790 let def_id = param.def_id.expect_local();
791
792 if tcx.features().const_param_ty_unchecked() {
793 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
794 wfcx.register_wf_obligation(span, None, ty.into());
795 Ok(())
796 })
797 } else if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
798 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
799 wfcx.register_bound(
800 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
801 wfcx.param_env,
802 ty,
803 tcx.require_lang_item(LangItem::ConstParamTy, span),
804 );
805 Ok(())
806 })
807 } else {
808 let span = || {
809 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
810 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
811 else {
812 bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!()
813 };
814 span
815 };
816 let mut diag = match ty.kind() {
817 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
818 ty::FnPtr(..) => tcx.dcx().struct_span_err(
819 span(),
820 "using function pointers as const generic parameters is forbidden",
821 ),
822 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
823 span(),
824 "using raw pointers as const generic parameters is forbidden",
825 ),
826 _ => {
827 ty.error_reported()?;
829
830 tcx.dcx().struct_span_err(
831 span(),
832 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
833 "`{ty}` is forbidden as the type of a const generic parameter",
834 ),
835 )
836 }
837 };
838
839 diag.note("the only supported types are integers, `bool`, and `char`");
840
841 let cause = ObligationCause::misc(span(), def_id);
842 let adt_const_params_feature_string =
843 " more complex and user defined types".to_string();
844 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
845 tcx,
846 tcx.param_env(param.def_id),
847 ty,
848 cause,
849 ) {
850 Err(
852 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
853 | ConstParamTyImplementationError::NonExhaustive(..)
854 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
855 ) => None,
856 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
857 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params),
(" references to implement the `ConstParamTy` trait".into(),
sym::unsized_const_params)]))vec![
858 (adt_const_params_feature_string, sym::min_adt_const_params),
859 (
860 " references to implement the `ConstParamTy` trait".into(),
861 sym::unsized_const_params,
862 ),
863 ])
864 }
865 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
868 fn ty_is_local(ty: Ty<'_>) -> bool {
869 match ty.kind() {
870 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
871 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
873 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
876 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
879 _ => false,
880 }
881 }
882
883 ty_is_local(ty).then_some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params)]))vec![(
884 adt_const_params_feature_string,
885 sym::min_adt_const_params,
886 )])
887 }
888 Ok(..) => {
890 Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(adt_const_params_feature_string, sym::min_adt_const_params)]))vec![(adt_const_params_feature_string, sym::min_adt_const_params)])
891 }
892 };
893 if let Some(features) = may_suggest_feature {
894 tcx.disabled_nightly_features(&mut diag, features);
895 }
896
897 Err(diag.emit())
898 }
899 }
900 }
901}
902
903{}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(903u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let loc = Some(WellFormedLoc::Ty(def_id));
enter_wf_checking_ctxt(tcx, def_id,
|wfcx|
{
let item = tcx.associated_item(def_id);
tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
let self_ty =
match item.container {
ty::AssocContainer::Trait => tcx.types.self_param,
ty::AssocContainer::InherentImpl |
ty::AssocContainer::TraitImpl(_) => {
tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
}
};
let span = tcx.def_span(def_id);
match item.kind {
ty::AssocKind::Const { .. } => {
let ty = tcx.type_of(def_id).instantiate_identity();
let ty =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
ty);
wfcx.register_wf_obligation(span, loc, ty.into());
check_const_item(wfcx, def_id, ty);
if item.defaultness(tcx).has_value() {
let code = ObligationCauseCode::SizedConstOrStatic;
wfcx.register_bound(ObligationCause::new(span, def_id,
code), wfcx.param_env, ty,
tcx.require_lang_item(LangItem::Sized, span));
}
Ok(())
}
ty::AssocKind::Fn { .. } => {
let sig =
tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
let hir_sig =
tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
check_method_receiver(wfcx, hir_sig, item, self_ty)
}
ty::AssocKind::Type { .. } => {
if let ty::AssocContainer::Trait = item.container {
check_associated_type_bounds(wfcx, item, span)
}
if item.defaultness(tcx).has_value() {
let ty = tcx.type_of(def_id).instantiate_identity();
let ty =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
ty);
wfcx.register_wf_obligation(span, loc, ty.into());
}
Ok(())
}
}
})
}
}
}#[instrument(level = "debug", skip(tcx))]
904pub(crate) fn check_associated_item(
905 tcx: TyCtxt<'_>,
906 def_id: LocalDefId,
907) -> Result<(), ErrorGuaranteed> {
908 let loc = Some(WellFormedLoc::Ty(def_id));
909 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
910 let item = tcx.associated_item(def_id);
911
912 tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
915
916 let self_ty = match item.container {
917 ty::AssocContainer::Trait => tcx.types.self_param,
918 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
919 tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
920 }
921 };
922
923 let span = tcx.def_span(def_id);
924
925 match item.kind {
926 ty::AssocKind::Const { .. } => {
927 let ty = tcx.type_of(def_id).instantiate_identity();
928 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
929 wfcx.register_wf_obligation(span, loc, ty.into());
930 check_const_item(wfcx, def_id, ty);
931
932 if item.defaultness(tcx).has_value() {
933 let code = ObligationCauseCode::SizedConstOrStatic;
934 wfcx.register_bound(
935 ObligationCause::new(span, def_id, code),
936 wfcx.param_env,
937 ty,
938 tcx.require_lang_item(LangItem::Sized, span),
939 );
940 }
941
942 Ok(())
943 }
944 ty::AssocKind::Fn { .. } => {
945 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
946 let hir_sig =
947 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
948 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
949 check_method_receiver(wfcx, hir_sig, item, self_ty)
950 }
951 ty::AssocKind::Type { .. } => {
952 if let ty::AssocContainer::Trait = item.container {
953 check_associated_type_bounds(wfcx, item, span)
954 }
955 if item.defaultness(tcx).has_value() {
956 let ty = tcx.type_of(def_id).instantiate_identity();
957 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
958 wfcx.register_wf_obligation(span, loc, ty.into());
959 }
960 Ok(())
961 }
962 }
963 })
964}
965
966pub(crate) fn check_type_defn<'tcx>(
968 tcx: TyCtxt<'tcx>,
969 item: LocalDefId,
970 all_sized: bool,
971) -> Result<(), ErrorGuaranteed> {
972 tcx.ensure_ok().check_representability(item);
973 let adt_def = tcx.adt_def(item);
974
975 enter_wf_checking_ctxt(tcx, item, |wfcx| {
976 let variants = adt_def.variants();
977 let packed = adt_def.repr().packed();
978
979 for variant in variants.iter() {
980 for field in &variant.fields {
982 if let Some(def_id) = field.value
983 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
984 {
985 if let Some(def_id) = def_id.as_local()
988 && let DefKind::AnonConst = tcx.def_kind(def_id)
989 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
990 && let expr = &tcx.hir_body(anon.body).value
991 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
992 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
993 {
994 } else {
997 let _ = tcx.const_eval_poly(def_id);
1000 }
1001 }
1002 let field_id = field.did.expect_local();
1003 let span = tcx.ty_span(field_id);
1004 let ty = wfcx.deeply_normalize(
1005 span,
1006 None,
1007 tcx.type_of(field.did).instantiate_identity(),
1008 );
1009 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(field_id)), ty.into());
1010
1011 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())
1012 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1013 {
1014 tcx.dcx().span_err(
1017 span,
1018 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1019 "scalable vectors cannot be fields of a {}",
1020 adt_def.variant_descr()
1021 ),
1022 );
1023 }
1024 }
1025
1026 let needs_drop_copy = || {
1029 packed && {
1030 let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1031 let ty = tcx.erase_and_anonymize_regions(ty);
1032 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1033 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1034 }
1035 };
1036 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1038 let unsized_len = if all_sized { 0 } else { 1 };
1039 for (idx, field) in
1040 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1041 {
1042 let last = idx == variant.fields.len() - 1;
1043 let span = tcx.ty_span(field.did.expect_local());
1044 let ty = wfcx.normalize(span, None, tcx.type_of(field.did).instantiate_identity());
1045 wfcx.register_bound(
1046 traits::ObligationCause::new(
1047 span,
1048 wfcx.body_def_id,
1049 ObligationCauseCode::FieldSized {
1050 adt_kind: adt_def.adt_kind(),
1051 span,
1052 last,
1053 },
1054 ),
1055 wfcx.param_env,
1056 ty,
1057 tcx.require_lang_item(LangItem::Sized, span),
1058 );
1059 }
1060
1061 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1063 match tcx.const_eval_poly(discr_def_id) {
1064 Ok(_) => {}
1065 Err(ErrorHandled::Reported(..)) => {}
1066 Err(ErrorHandled::TooGeneric(sp)) => {
1067 bug_impl(Some(sp), format_args!("enum variant discr was too generic to eval"),
Location::caller())span_bug!(sp, "enum variant discr was too generic to eval")
1068 }
1069 }
1070 }
1071 }
1072
1073 check_where_clauses(wfcx, item);
1074 Ok(())
1075 })
1076}
1077
1078{}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1078u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
return Ok(());
}
let trait_def = tcx.trait_def(def_id);
if trait_def.is_marker ||
#[allow(non_exhaustive_omitted_patterns)] match trait_def.specialization_kind
{
TraitSpecializationKind::Marker => true,
_ => false,
} {
for associated_def_id in &*tcx.associated_item_def_ids(def_id)
{
{
tcx.dcx().struct_span_err(tcx.def_span(*associated_def_id),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("marker traits cannot have associated items"))
})).with_code(E0714)
}.emit();
}
}
let res =
enter_wf_checking_ctxt(tcx, def_id,
|wfcx| { check_where_clauses(wfcx, def_id); Ok(()) });
res
}
}
}#[instrument(skip(tcx))]
1079pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1080 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1081 return Ok(());
1083 }
1084
1085 let trait_def = tcx.trait_def(def_id);
1086 if trait_def.is_marker
1087 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1088 {
1089 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1090 struct_span_code_err!(
1091 tcx.dcx(),
1092 tcx.def_span(*associated_def_id),
1093 E0714,
1094 "marker traits cannot have associated items",
1095 )
1096 .emit();
1097 }
1098 }
1099
1100 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1101 check_where_clauses(wfcx, def_id);
1102 Ok(())
1103 });
1104
1105 res
1106}
1107
1108fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1113 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1114
1115 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1115",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1115u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_associated_type_bounds: bounds={0:?}",
bounds) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_associated_type_bounds: bounds={:?}", bounds);
1116 let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1117 |(bound, bound_span)| {
1118 traits::wf::clause_obligations(
1119 wfcx.infcx,
1120 wfcx.param_env,
1121 wfcx.body_def_id,
1122 bound,
1123 bound_span,
1124 )
1125 },
1126 );
1127
1128 wfcx.register_obligations(wf_obligations);
1129}
1130
1131fn check_item_fn(
1132 tcx: TyCtxt<'_>,
1133 def_id: LocalDefId,
1134 decl: &hir::FnDecl<'_>,
1135) -> Result<(), ErrorGuaranteed> {
1136 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1137 check_eiis_fn(tcx, def_id);
1138
1139 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1140 check_fn_or_method(wfcx, sig, decl, def_id);
1141 Ok(())
1142 })
1143}
1144
1145fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1146 if let Some(EiiImpl { resolution, span, .. }) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
break 'done Some(&**i);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1149 let (foreign_item, name) = match resolution {
1150 EiiImplResolution::Macro(def_id) => {
1151 if let Some(foreign_item) =
1154 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
foreign_item: t, .. })) => {
break 'done Some(*t);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1155 {
1156 (foreign_item, tcx.item_name(*def_id))
1157 } else {
1158 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1159 return;
1160 }
1161 }
1162 EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1163 EiiImplResolution::Error(_eg) => return,
1164 };
1165
1166 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1167 }
1168}
1169
1170fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1171 if let Some(EiiImpl { resolution, span, .. }) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiImpl(i)) => {
break 'done Some(&**i);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiImpl(i) => &**i) {
1174 let (foreign_item, name) = match resolution {
1175 EiiImplResolution::Macro(def_id) => {
1176 if let Some(foreign_item) =
1179 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(EiiDecl {
foreign_item: t, .. })) => {
break 'done Some(*t);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, *def_id, EiiDeclaration(EiiDecl {foreign_item: t, ..}) => *t)
1180 {
1181 (foreign_item, tcx.item_name(*def_id))
1182 } else {
1183 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1184 return;
1185 }
1186 }
1187 EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1188 EiiImplResolution::Error(_eg) => return,
1189 };
1190
1191 let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1192 }
1193}
1194
1195{}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1195u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_id")
}> =
::tracing::__macro_support::FieldName::new("item_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("should_check_for_sync")
}> =
::tracing::__macro_support::FieldName::new("should_check_for_sync");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&should_check_for_sync
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
enter_wf_checking_ctxt(tcx, item_id,
|wfcx|
{
if should_check_for_sync {
check_eiis_static(tcx, item_id, ty);
}
let span = tcx.ty_span(item_id);
let loc = Some(WellFormedLoc::Ty(item_id));
let item_ty =
wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
let is_foreign_item = tcx.is_foreign_item(item_id);
let is_structurally_foreign_item =
||
{
let tail =
tcx.struct_tail_raw(item_ty, &ObligationCause::dummy(),
|ty| wfcx.deeply_normalize(span, loc, ty), || {});
#[allow(non_exhaustive_omitted_patterns)]
match tail.kind() { ty::Foreign(_) => true, _ => false, }
};
let forbid_unsized =
!(is_foreign_item && is_structurally_foreign_item());
wfcx.register_wf_obligation(span,
Some(WellFormedLoc::Ty(item_id)), item_ty.into());
if forbid_unsized {
let span = tcx.def_span(item_id);
wfcx.register_bound(traits::ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::SizedConstOrStatic),
wfcx.param_env, item_ty,
tcx.require_lang_item(LangItem::Sized, span));
}
let should_check_for_sync =
should_check_for_sync && !is_foreign_item &&
tcx.static_mutability(item_id.to_def_id()) ==
Some(hir::Mutability::Not) &&
!tcx.is_thread_local_static(item_id.to_def_id());
if should_check_for_sync {
wfcx.register_bound(traits::ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::SharedStatic),
wfcx.param_env, item_ty,
tcx.require_lang_item(LangItem::Sync, span));
}
Ok(())
})
}
}
}#[instrument(level = "debug", skip(tcx))]
1196pub(crate) fn check_static_item<'tcx>(
1197 tcx: TyCtxt<'tcx>,
1198 item_id: LocalDefId,
1199 ty: Ty<'tcx>,
1200 should_check_for_sync: bool,
1201) -> Result<(), ErrorGuaranteed> {
1202 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1203 if should_check_for_sync {
1204 check_eiis_static(tcx, item_id, ty);
1205 }
1206
1207 let span = tcx.ty_span(item_id);
1208 let loc = Some(WellFormedLoc::Ty(item_id));
1209 let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1210
1211 let is_foreign_item = tcx.is_foreign_item(item_id);
1212 let is_structurally_foreign_item = || {
1213 let tail = tcx.struct_tail_raw(
1214 item_ty,
1215 &ObligationCause::dummy(),
1216 |ty| wfcx.deeply_normalize(span, loc, ty),
1217 || {},
1218 );
1219
1220 matches!(tail.kind(), ty::Foreign(_))
1221 };
1222 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1223
1224 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1225 if forbid_unsized {
1226 let span = tcx.def_span(item_id);
1227 wfcx.register_bound(
1228 traits::ObligationCause::new(
1229 span,
1230 wfcx.body_def_id,
1231 ObligationCauseCode::SizedConstOrStatic,
1232 ),
1233 wfcx.param_env,
1234 item_ty,
1235 tcx.require_lang_item(LangItem::Sized, span),
1236 );
1237 }
1238
1239 let should_check_for_sync = should_check_for_sync
1241 && !is_foreign_item
1242 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1243 && !tcx.is_thread_local_static(item_id.to_def_id());
1244
1245 if should_check_for_sync {
1246 wfcx.register_bound(
1247 traits::ObligationCause::new(
1248 span,
1249 wfcx.body_def_id,
1250 ObligationCauseCode::SharedStatic,
1251 ),
1252 wfcx.param_env,
1253 item_ty,
1254 tcx.require_lang_item(LangItem::Sync, span),
1255 );
1256 }
1257 Ok(())
1258 })
1259}
1260
1261{}
#[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_const_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1262u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_ty")
}> =
::tracing::__macro_support::FieldName::new("item_ty");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_ty)
as &dyn ::tracing::field::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 span = tcx.def_span(def_id);
if tcx.is_direct_const(def_id.into()) &&
!tcx.features().const_param_ty_unchecked() {
wfcx.register_bound(ObligationCause::new(span, def_id,
ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
item_ty,
tcx.require_lang_item(LangItem::ConstParamTy, span));
}
if let Some(direct_rhs) = tcx.const_of_item(def_id) {
let raw_ct = direct_rhs.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))));
}
}
}
}#[instrument(level = "debug", skip(wfcx))]
1263pub(super) fn check_const_item<'tcx>(
1264 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1265 def_id: LocalDefId,
1266 item_ty: Ty<'tcx>,
1267) {
1268 let tcx = wfcx.tcx();
1269 let span = tcx.def_span(def_id);
1270
1271 if tcx.is_direct_const(def_id.into()) && !tcx.features().const_param_ty_unchecked() {
1272 wfcx.register_bound(
1273 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1274 wfcx.param_env,
1275 item_ty,
1276 tcx.require_lang_item(LangItem::ConstParamTy, span),
1277 );
1278 }
1279
1280 if let Some(direct_rhs) = tcx.const_of_item(def_id) {
1281 let raw_ct = direct_rhs.instantiate_identity();
1282 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1283 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1284
1285 wfcx.register_obligation(Obligation::new(
1286 tcx,
1287 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1288 wfcx.param_env,
1289 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1290 ));
1291 }
1292}
1293
1294{}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1294u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
enter_wf_checking_ctxt(tcx, item.owner_id.def_id,
|wfcx|
{
match impl_.of_trait {
Some(of_trait) => {
let trait_ref =
tcx.impl_trait_ref(item.owner_id).instantiate_identity();
tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
let trait_span = of_trait.trait_ref.path.span;
let trait_ref =
wfcx.deeply_normalize(trait_span,
Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
trait_ref);
let trait_pred =
ty::TraitClause {
trait_ref,
polarity: ty::ClausePolarity::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1363",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1363u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligations")
}> =
::tracing::__macro_support::FieldName::new("obligations");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligations)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
wfcx.register_obligations(obligations);
}
None => {
let self_ty =
tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
let self_ty =
wfcx.deeply_normalize(item.span,
Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
Unnormalized::new_wip(self_ty));
wfcx.register_wf_obligation(impl_.self_ty.span,
Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
self_ty.into());
}
}
check_where_clauses(wfcx, item.owner_id.def_id);
Ok(())
})
}
}
}#[instrument(level = "debug", skip(tcx, impl_))]
1295fn check_impl<'tcx>(
1296 tcx: TyCtxt<'tcx>,
1297 item: &'tcx hir::Item<'tcx>,
1298 impl_: &hir::Impl<'_>,
1299) -> Result<(), ErrorGuaranteed> {
1300 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1301 match impl_.of_trait {
1302 Some(of_trait) => {
1303 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1304 tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1307 let trait_span = of_trait.trait_ref.path.span;
1308 let trait_ref = wfcx.deeply_normalize(
1309 trait_span,
1310 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1311 trait_ref,
1312 );
1313 let trait_pred =
1314 ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive };
1315 let mut obligations = traits::wf::trait_obligations(
1316 wfcx.infcx,
1317 wfcx.param_env,
1318 wfcx.body_def_id,
1319 trait_pred,
1320 trait_span,
1321 item,
1322 );
1323 for obligation in &mut obligations {
1324 if obligation.cause.span != trait_span {
1325 continue;
1327 }
1328 if let Some(pred) = obligation.predicate.as_trait_clause()
1329 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1330 {
1331 obligation.cause.span = impl_.self_ty.span;
1332 }
1333 if let Some(pred) = obligation.predicate.as_projection_clause()
1334 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1335 {
1336 obligation.cause.span = impl_.self_ty.span;
1337 }
1338 }
1339
1340 if tcx.is_conditionally_const(item.owner_id.def_id) {
1342 for (bound, _) in
1343 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1344 {
1345 let bound = wfcx.normalize(
1346 item.span,
1347 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1348 bound,
1349 );
1350 wfcx.register_obligation(Obligation::new(
1351 tcx,
1352 ObligationCause::new(
1353 impl_.self_ty.span,
1354 wfcx.body_def_id,
1355 ObligationCauseCode::WellFormed(None),
1356 ),
1357 wfcx.param_env,
1358 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1359 ))
1360 }
1361 }
1362
1363 debug!(?obligations);
1364 wfcx.register_obligations(obligations);
1365 }
1366 None => {
1367 let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1368 let self_ty = wfcx.deeply_normalize(
1369 item.span,
1370 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1371 Unnormalized::new_wip(self_ty),
1372 );
1373 wfcx.register_wf_obligation(
1374 impl_.self_ty.span,
1375 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1376 self_ty.into(),
1377 );
1378 }
1379 }
1380
1381 check_where_clauses(wfcx, item.owner_id.def_id);
1382 Ok(())
1383 })
1384}
1385
1386{}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1387u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::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 gen_clauses = tcx.clauses_of(def_id.to_def_id());
let generics = tcx.generics_of(def_id);
for param in &generics.own_params {
if let Some(default) =
param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
{
if !default.has_param() {
wfcx.register_wf_obligation(tcx.def_span(param.def_id),
(#[allow(non_exhaustive_omitted_patterns)] match param.kind
{
GenericParamDefKind::Type { .. } => true,
_ => false,
}).then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
default.as_term().unwrap());
} else {
let GenericArgKind::Const(ct) =
default.kind() else { continue; };
let ct_ty =
match ct.kind() {
ty::ConstKind::Infer(_) | ty::ConstKind::Placeholder(_) |
ty::ConstKind::Bound(_, _) =>
::core::panicking::panic("internal error: entered unreachable code"),
ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) =>
continue,
ty::ConstKind::Value(cv) => cv.ty,
ty::ConstKind::Alias(_, alias_const) => {
alias_const.type_of(infcx.tcx).skip_norm_wip()
}
ty::ConstKind::Param(param_ct) => {
param_ct.find_const_ty_from_env(wfcx.param_env)
}
};
let param_ty =
tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
if !ct_ty.has_param() && !param_ty.has_param() {
let cause =
traits::ObligationCause::new(tcx.def_span(param.def_id),
wfcx.body_def_id, ObligationCauseCode::WellFormed(None));
wfcx.register_obligation(Obligation::new(tcx, cause,
wfcx.param_env,
ty::ClauseKind::ConstArgHasType(ct, param_ty)));
}
}
}
}
let args =
GenericArgs::for_item(tcx, def_id.to_def_id(),
|param, _|
{
if param.index >= generics.parent_count as u32 &&
let Some(default) =
param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
&& !default.has_param() {
return default;
}
tcx.mk_param_from_def(param)
});
let default_obligations =
gen_clauses.clauses.iter().flat_map(|&(clause, 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 =
clause.visit_with(&mut param_count).is_break();
let instantiated_clause =
ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
if instantiated_clause.skip_normalization().has_non_region_param()
|| param_count.params.len() > 1 || has_region {
None
} else if gen_clauses.clauses.iter().any(|&(p, _)|
Unnormalized::new_wip(p) == instantiated_clause) {
None
} else { Some((instantiated_clause, sp)) }
}).map(|(clause, sp)|
{
let clause = wfcx.normalize(sp, None, clause);
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, clause)
});
let gen_clauses = gen_clauses.instantiate_identity(tcx);
let assoc_const_obligations: Vec<_> =
gen_clauses.clauses.iter().copied().zip(gen_clauses.spans.iter().copied()).filter_map(|(clause,
sp)|
{
let clause = clause.skip_norm_wip();
let proj = clause.as_projection_clause()?;
let pred_binder =
proj.map_bound(|pred|
{
pred.term.as_const().map(|ct|
{
let assoc_const_ty =
pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
})
}).transpose();
pred_binder.map(|pred_binder|
{
let cause =
traits::ObligationCause::new(sp, wfcx.body_def_id,
ObligationCauseCode::WhereClause(def_id.to_def_id(), sp));
Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
})
}).collect();
{
match (&gen_clauses.clauses.len(), &gen_clauses.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 =
gen_clauses.into_iter().flat_map(|(p, sp)|
{
traits::wf::clause_obligations(infcx, wfcx.param_env,
wfcx.body_def_id, p.skip_norm_wip(), sp)
});
let obligations: Vec<_> =
wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
wfcx.register_obligations(obligations);
}
}
}#[instrument(level = "debug", skip(wfcx))]
1388pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1389 let infcx = wfcx.infcx;
1390 let tcx = wfcx.tcx();
1391
1392 let gen_clauses = tcx.clauses_of(def_id.to_def_id());
1393 let generics = tcx.generics_of(def_id);
1394
1395 for param in &generics.own_params {
1402 if let Some(default) = param
1403 .default_value(tcx)
1404 .map(ty::EarlyBinder::instantiate_identity)
1405 .map(Unnormalized::skip_norm_wip)
1406 {
1407 if !default.has_param() {
1414 wfcx.register_wf_obligation(
1415 tcx.def_span(param.def_id),
1416 matches!(param.kind, GenericParamDefKind::Type { .. })
1417 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1418 default.as_term().unwrap(),
1419 );
1420 } else {
1421 let GenericArgKind::Const(ct) = default.kind() else {
1424 continue;
1425 };
1426
1427 let ct_ty = match ct.kind() {
1428 ty::ConstKind::Infer(_)
1429 | ty::ConstKind::Placeholder(_)
1430 | ty::ConstKind::Bound(_, _) => unreachable!(),
1431 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1432 ty::ConstKind::Value(cv) => cv.ty,
1433 ty::ConstKind::Alias(_, alias_const) => {
1434 alias_const.type_of(infcx.tcx).skip_norm_wip()
1435 }
1436 ty::ConstKind::Param(param_ct) => {
1437 param_ct.find_const_ty_from_env(wfcx.param_env)
1438 }
1439 };
1440
1441 let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1442 if !ct_ty.has_param() && !param_ty.has_param() {
1443 let cause = traits::ObligationCause::new(
1444 tcx.def_span(param.def_id),
1445 wfcx.body_def_id,
1446 ObligationCauseCode::WellFormed(None),
1447 );
1448 wfcx.register_obligation(Obligation::new(
1449 tcx,
1450 cause,
1451 wfcx.param_env,
1452 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1453 ));
1454 }
1455 }
1456 }
1457 }
1458
1459 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1468 if param.index >= generics.parent_count as u32
1469 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1471 && !default.has_param()
1473 {
1474 return default;
1476 }
1477 tcx.mk_param_from_def(param)
1478 });
1479
1480 let default_obligations = gen_clauses
1482 .clauses
1483 .iter()
1484 .flat_map(|&(clause, sp)| {
1485 #[derive(Default)]
1486 struct CountParams {
1487 params: FxHashSet<u32>,
1488 }
1489 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1490 type Result = ControlFlow<()>;
1491 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1492 if let ty::Param(param) = t.kind() {
1493 self.params.insert(param.index);
1494 }
1495 t.super_visit_with(self)
1496 }
1497
1498 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1499 ControlFlow::Break(())
1500 }
1501
1502 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1503 if let ty::ConstKind::Param(param) = c.kind() {
1504 self.params.insert(param.index);
1505 }
1506 c.super_visit_with(self)
1507 }
1508 }
1509 let mut param_count = CountParams::default();
1510 let has_region = clause.visit_with(&mut param_count).is_break();
1511 let instantiated_clause = ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
1512 if instantiated_clause.skip_normalization().has_non_region_param()
1515 || param_count.params.len() > 1
1516 || has_region
1517 {
1518 None
1519 } else if gen_clauses
1520 .clauses
1521 .iter()
1522 .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_clause)
1523 {
1524 None
1526 } else {
1527 Some((instantiated_clause, sp))
1528 }
1529 })
1530 .map(|(clause, sp)| {
1531 let clause = wfcx.normalize(sp, None, clause);
1541 let cause = traits::ObligationCause::new(
1542 sp,
1543 wfcx.body_def_id,
1544 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1545 );
1546 Obligation::new(tcx, cause, wfcx.param_env, clause)
1547 });
1548
1549 let gen_clauses = gen_clauses.instantiate_identity(tcx);
1550
1551 let assoc_const_obligations: Vec<_> = gen_clauses
1552 .clauses
1553 .iter()
1554 .copied()
1555 .zip(gen_clauses.spans.iter().copied())
1556 .filter_map(|(clause, sp)| {
1557 let clause = clause.skip_norm_wip();
1558 let proj = clause.as_projection_clause()?;
1559 let pred_binder = proj
1560 .map_bound(|pred| {
1561 pred.term.as_const().map(|ct| {
1562 let assoc_const_ty =
1563 pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
1564 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1565 })
1566 })
1567 .transpose();
1568 pred_binder.map(|pred_binder| {
1569 let cause = traits::ObligationCause::new(
1570 sp,
1571 wfcx.body_def_id,
1572 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1573 );
1574 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1575 })
1576 })
1577 .collect();
1578
1579 assert_eq!(gen_clauses.clauses.len(), gen_clauses.spans.len());
1580 let wf_obligations = gen_clauses.into_iter().flat_map(|(p, sp)| {
1581 traits::wf::clause_obligations(
1582 infcx,
1583 wfcx.param_env,
1584 wfcx.body_def_id,
1585 p.skip_norm_wip(),
1586 sp,
1587 )
1588 });
1589 let obligations: Vec<_> =
1590 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1591 wfcx.register_obligations(obligations);
1592}
1593
1594{}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1594u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("sig")
}> =
::tracing::__macro_support::FieldName::new("sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = wfcx.tcx();
let mut sig =
tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
let arg_span =
|idx|
hir_decl.inputs.get(idx).map_or(hir_decl.output.span(),
|arg: &hir::Ty<'_>| arg.span);
sig.inputs_and_output =
tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx,
ty)|
{
wfcx.deeply_normalize(arg_span(idx),
Some(WellFormedLoc::Param {
function: def_id,
param_idx: idx,
}), Unnormalized::new_wip(ty))
}));
for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
wfcx.register_wf_obligation(arg_span(idx),
Some(WellFormedLoc::Param {
function: def_id,
param_idx: idx,
}), ty.into());
}
check_where_clauses(wfcx, def_id);
if sig.abi() == ExternAbi::RustCall {
let span = tcx.def_span(def_id);
let has_implicit_self =
hir_decl.implicit_self().has_implicit_self();
let mut inputs =
sig.inputs().iter().skip(if has_implicit_self {
1
} else { 0 });
if let Some(ty) = inputs.next() {
wfcx.register_bound(ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::RustCall),
wfcx.param_env, *ty,
tcx.require_lang_item(LangItem::Tuple, span));
wfcx.register_bound(ObligationCause::new(span,
wfcx.body_def_id, ObligationCauseCode::RustCall),
wfcx.param_env, *ty,
tcx.require_lang_item(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))]
1595fn check_fn_or_method<'tcx>(
1596 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1597 sig: ty::PolyFnSig<'tcx>,
1598 hir_decl: &hir::FnDecl<'_>,
1599 def_id: LocalDefId,
1600) {
1601 let tcx = wfcx.tcx();
1602 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1603
1604 let arg_span =
1610 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1611
1612 sig.inputs_and_output =
1613 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1614 wfcx.deeply_normalize(
1615 arg_span(idx),
1616 Some(WellFormedLoc::Param {
1617 function: def_id,
1618 param_idx: idx,
1621 }),
1622 Unnormalized::new_wip(ty),
1623 )
1624 }));
1625
1626 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1627 wfcx.register_wf_obligation(
1628 arg_span(idx),
1629 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1630 ty.into(),
1631 );
1632 }
1633
1634 check_where_clauses(wfcx, def_id);
1635
1636 if sig.abi() == ExternAbi::RustCall {
1637 let span = tcx.def_span(def_id);
1638 let has_implicit_self = hir_decl.implicit_self().has_implicit_self();
1639 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1640 if let Some(ty) = inputs.next() {
1642 wfcx.register_bound(
1643 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1644 wfcx.param_env,
1645 *ty,
1646 tcx.require_lang_item(LangItem::Tuple, span),
1647 );
1648 wfcx.register_bound(
1649 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1650 wfcx.param_env,
1651 *ty,
1652 tcx.require_lang_item(LangItem::Sized, span),
1653 );
1654 } else {
1655 tcx.dcx().span_err(
1656 hir_decl.inputs.last().map_or(span, |input| input.span),
1657 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1658 );
1659 }
1660 if inputs.next().is_some() {
1662 tcx.dcx().span_err(
1663 hir_decl.inputs.last().map_or(span, |input| input.span),
1664 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1665 );
1666 }
1667 }
1668
1669 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1671 let span = match hir_decl.output {
1672 hir::FnRetTy::Return(ty) => ty.span,
1673 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1674 };
1675
1676 wfcx.register_bound(
1677 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1678 wfcx.param_env,
1679 sig.output(),
1680 tcx.require_lang_item(LangItem::Sized, span),
1681 );
1682 }
1683}
1684
1685#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ArbitrarySelfTypesLevel { }
#[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::marker::StructuralPartialEq for ArbitrarySelfTypesLevel { }
#[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)]
1687enum ArbitrarySelfTypesLevel {
1688 Basic, WithPointers, }
1691
1692{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_method_receiver",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1692u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fn_sig")
}> =
::tracing::__macro_support::FieldName::new("fn_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("method")
}> =
::tracing::__macro_support::FieldName::new("method");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self_ty")
}> =
::tracing::__macro_support::FieldName::new("self_ty");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = wfcx.tcx();
if !method.is_method() { return Ok(()); }
let span = fn_sig.decl.inputs[0].span;
let loc =
Some(WellFormedLoc::Param {
function: method.def_id.expect_local(),
param_idx: 0,
});
let sig =
tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
let sig =
wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1712",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1712u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_method_receiver: sig={0:?}",
sig) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let self_ty =
wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
let receiver_ty = sig.inputs()[0];
let receiver_ty =
wfcx.normalize(DUMMY_SP, loc,
Unnormalized::new_wip(receiver_ty));
receiver_ty.error_reported()?;
let arbitrary_self_types_level =
if tcx.features().arbitrary_self_types_pointers() {
Some(ArbitrarySelfTypesLevel::WithPointers)
} else if tcx.features().arbitrary_self_types() {
Some(ArbitrarySelfTypesLevel::Basic)
} else { None };
let generics = tcx.generics_of(method.def_id);
let receiver_validity =
receiver_is_valid(wfcx, span, receiver_ty, self_ty,
arbitrary_self_types_level, generics);
if let Err(receiver_validity_err) = receiver_validity {
return Err(match arbitrary_self_types_level {
None if
receiver_is_valid(wfcx, span, receiver_ty, self_ty,
Some(ArbitrarySelfTypesLevel::Basic), generics).is_ok() => {
feature_err(&tcx.sess, sym::arbitrary_self_types, span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types` feature",
receiver_ty))
})).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit()
}
None | Some(ArbitrarySelfTypesLevel::Basic) if
receiver_is_valid(wfcx, span, receiver_ty, self_ty,
Some(ArbitrarySelfTypesLevel::WithPointers),
generics).is_ok() => {
feature_err(&tcx.sess, sym::arbitrary_self_types_pointers,
span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` cannot be used as the type of `self` without the `arbitrary_self_types_pointers` feature",
receiver_ty))
})).with_help(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`"))).emit()
}
_ => {
match receiver_validity_err {
ReceiverValidityError::DoesNotDeref if
arbitrary_self_types_level.is_some() => {
let adt_def =
receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def();
let hint =
match adt_def {
Some(adt) => {
if tcx.is_lang_item(adt.did(), LangItem::NonNull) {
Some(InvalidReceiverTyHint::NonNull)
} else {
match tcx.get_diagnostic_name(adt.did()) {
Some(sym::RcWeak | sym::ArcWeak) => {
Some(InvalidReceiverTyHint::Weak)
}
_ => None,
}
}
}
_ => None,
};
tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
span,
receiver_ty,
hint,
})
}
ReceiverValidityError::DoesNotDeref => {
tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
span,
receiver_ty,
})
}
ReceiverValidityError::MethodGenericParamUsed =>
tcx.dcx().emit_err(diagnostics::InvalidGenericReceiverTy {
span,
receiver_ty,
}),
}
}
});
}
Ok(())
}
}
}#[instrument(level = "debug", skip(wfcx))]
1693fn check_method_receiver<'tcx>(
1694 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1695 fn_sig: &hir::FnSig<'_>,
1696 method: ty::AssocItem,
1697 self_ty: Ty<'tcx>,
1698) -> Result<(), ErrorGuaranteed> {
1699 let tcx = wfcx.tcx();
1700
1701 if !method.is_method() {
1702 return Ok(());
1703 }
1704
1705 let span = fn_sig.decl.inputs[0].span;
1706 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1707
1708 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1709 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1710 let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1711
1712 debug!("check_method_receiver: sig={:?}", sig);
1713
1714 let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1715
1716 let receiver_ty = sig.inputs()[0];
1717 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1718
1719 receiver_ty.error_reported()?;
1722
1723 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1724 Some(ArbitrarySelfTypesLevel::WithPointers)
1725 } else if tcx.features().arbitrary_self_types() {
1726 Some(ArbitrarySelfTypesLevel::Basic)
1727 } else {
1728 None
1729 };
1730 let generics = tcx.generics_of(method.def_id);
1731
1732 let receiver_validity =
1733 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1734 if let Err(receiver_validity_err) = receiver_validity {
1735 return Err(match arbitrary_self_types_level {
1736 None if receiver_is_valid(
1740 wfcx,
1741 span,
1742 receiver_ty,
1743 self_ty,
1744 Some(ArbitrarySelfTypesLevel::Basic),
1745 generics,
1746 )
1747 .is_ok() =>
1748 {
1749 feature_err(
1751 &tcx.sess,
1752 sym::arbitrary_self_types,
1753 span,
1754 format!(
1755 "`{receiver_ty}` cannot be used as the type of `self` without \
1756 the `arbitrary_self_types` feature",
1757 ),
1758 )
1759 .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>`"))
1760 .emit()
1761 }
1762 None | Some(ArbitrarySelfTypesLevel::Basic)
1763 if receiver_is_valid(
1764 wfcx,
1765 span,
1766 receiver_ty,
1767 self_ty,
1768 Some(ArbitrarySelfTypesLevel::WithPointers),
1769 generics,
1770 )
1771 .is_ok() =>
1772 {
1773 feature_err(
1775 &tcx.sess,
1776 sym::arbitrary_self_types_pointers,
1777 span,
1778 format!(
1779 "`{receiver_ty}` cannot be used as the type of `self` without \
1780 the `arbitrary_self_types_pointers` feature",
1781 ),
1782 )
1783 .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>`"))
1784 .emit()
1785 }
1786 _ =>
1787 {
1789 match receiver_validity_err {
1790 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1791 let adt_def =
1792 receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def();
1793
1794 let hint = match adt_def {
1795 Some(adt) => {
1796 if tcx.is_lang_item(adt.did(), LangItem::NonNull) {
1797 Some(InvalidReceiverTyHint::NonNull)
1798 } else {
1799 match tcx.get_diagnostic_name(adt.did()) {
1800 Some(sym::RcWeak | sym::ArcWeak) => {
1801 Some(InvalidReceiverTyHint::Weak)
1802 }
1803 _ => None,
1804 }
1805 }
1806 }
1807 _ => None,
1808 };
1809
1810 tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
1811 span,
1812 receiver_ty,
1813 hint,
1814 })
1815 }
1816 ReceiverValidityError::DoesNotDeref => {
1817 tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
1818 span,
1819 receiver_ty,
1820 })
1821 }
1822 ReceiverValidityError::MethodGenericParamUsed => tcx
1823 .dcx()
1824 .emit_err(diagnostics::InvalidGenericReceiverTy { span, receiver_ty }),
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().no_errors() {
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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1910",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: potential self type `{0:?}` to match `{1:?}`",
potential_self_ty, self_ty) as
&dyn ::tracing::field::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().no_errors() {
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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1957",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_valid: type `{0:?}` does not deref to `{1:?}`",
receiver_ty, self_ty) as &dyn ::tracing::field::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs:1975",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("receiver_is_implemented: type `{0:?}` does not implement `LegacyReceiver` trait",
receiver_ty) as &dyn ::tracing::field::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 kind => bug_impl(Some(tcx.def_span(def_id)),
format_args!("cannot compute the variances of {0:?}", kind),
Location::caller())span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1989 }
1990
1991 let ty_clauses = tcx.clauses_of(def_id);
1992 {
match (&ty_clauses.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_clauses.parent, None);
1993 let variances = tcx.variances_of(def_id);
1994
1995 let mut constrained_parameters: FxHashSet<_> = variances
1996 .iter()
1997 .enumerate()
1998 .filter(|&(_, &variance)| variance != ty::Bivariant)
1999 .map(|(index, _)| Parameter(index as u32))
2000 .collect();
2001
2002 identify_constrained_generic_params(tcx, ty_clauses, None, &mut constrained_parameters);
2003
2004 let explicitly_bounded_params = LazyCell::new(|| {
2006 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2007 tcx.hir_node_by_def_id(def_id)
2008 .generics()
2009 .unwrap()
2010 .predicates
2011 .iter()
2012 .filter_map(|predicate| match predicate.kind {
2013 hir::WherePredicateKind::BoundPredicate(predicate) => {
2014 match icx.lower_ty(predicate.bounded_ty).kind() {
2015 ty::Param(data) => Some(Parameter(data.index)),
2016 _ => None,
2017 }
2018 }
2019 _ => None,
2020 })
2021 .collect::<FxHashSet<_>>()
2022 });
2023
2024 for (index, _) in variances.iter().enumerate() {
2025 let parameter = Parameter(index as u32);
2026
2027 if constrained_parameters.contains(¶meter) {
2028 continue;
2029 }
2030
2031 let node = tcx.hir_node_by_def_id(def_id);
2032 let item = node.expect_item();
2033 let hir_generics = node.generics().unwrap();
2034 let hir_param = &hir_generics.params[index];
2035
2036 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2037
2038 if ty_param.def_id != hir_param.def_id.into() {
2039 tcx.dcx().span_delayed_bug(
2047 hir_param.span,
2048 "hir generics and ty generics in different order",
2049 );
2050 continue;
2051 }
2052
2053 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2055 .type_of(def_id)
2056 .instantiate_identity()
2057 .skip_norm_wip()
2058 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2059 {
2060 continue;
2061 }
2062
2063 match hir_param.name {
2064 hir::ParamName::Error(_) => {
2065 }
2068 _ => {
2069 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2070 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2071 }
2072 }
2073 }
2074}
2075
2076struct HasErrorDeep<'tcx> {
2078 tcx: TyCtxt<'tcx>,
2079 seen: FxHashSet<DefId>,
2080}
2081impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2082 type Result = ControlFlow<ErrorGuaranteed>;
2083
2084 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2085 match *ty.kind() {
2086 ty::Adt(def, _) => {
2087 if self.seen.insert(def.did()) {
2088 for field in def.all_fields() {
2089 self.tcx
2090 .type_of(field.did)
2091 .instantiate_identity()
2092 .skip_norm_wip()
2093 .visit_with(self)?;
2094 }
2095 }
2096 }
2097 ty::Error(guar) => return ControlFlow::Break(guar),
2098 _ => {}
2099 }
2100 ty.super_visit_with(self)
2101 }
2102
2103 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2104 if let Err(guar) = r.error_reported() {
2105 ControlFlow::Break(guar)
2106 } else {
2107 ControlFlow::Continue(())
2108 }
2109 }
2110
2111 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2112 if let Err(guar) = c.error_reported() {
2113 ControlFlow::Break(guar)
2114 } else {
2115 ControlFlow::Continue(())
2116 }
2117 }
2118}
2119
2120fn report_bivariance<'tcx>(
2121 tcx: TyCtxt<'tcx>,
2122 param: &'tcx hir::GenericParam<'tcx>,
2123 has_explicit_bounds: bool,
2124 item: &'tcx hir::Item<'tcx>,
2125) -> ErrorGuaranteed {
2126 let param_name = param.name.ident();
2127
2128 let help = match item.kind {
2129 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2130 if let Some(def_id) = tcx.lang_items().phantom_data() {
2131 diagnostics::UnusedGenericParameterHelp::Adt {
2132 param_name,
2133 phantom_data: tcx.def_path_str(def_id),
2134 }
2135 } else {
2136 diagnostics::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2137 }
2138 }
2139 item_kind => bug_impl(None,
format_args!("report_bivariance: unexpected item kind: {0:?}", item_kind),
Location::caller())bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2140 };
2141
2142 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2143 intravisit::walk_item(
2144 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2145 item,
2146 );
2147
2148 if !usage_spans.is_empty() {
2149 let item_def_id = item.owner_id.to_def_id();
2153 let is_probably_cyclical =
2154 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2155 .visit_def(item_def_id)
2156 .is_break();
2157 if is_probably_cyclical {
2166 return tcx.dcx().emit_err(diagnostics::RecursiveGenericParameter {
2167 spans: usage_spans,
2168 param_span: param.span,
2169 param_name,
2170 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2171 help,
2172 note: (),
2173 });
2174 }
2175 }
2176
2177 let const_param_help =
2178 #[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);
2179
2180 let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2181 span: param.span,
2182 param_name,
2183 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2184 usage_spans,
2185 help,
2186 const_param_help,
2187 });
2188 diag.code(E0392);
2189 if item.kind.recovered() {
2190 diag.delay_as_bug()
2192 } else {
2193 diag.emit()
2194 }
2195}
2196
2197struct IsProbablyCyclical<'tcx> {
2203 tcx: TyCtxt<'tcx>,
2204 item_def_id: DefId,
2205 seen: FxHashSet<DefId>,
2206}
2207
2208impl<'tcx> IsProbablyCyclical<'tcx> {
2209 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2210 match self.tcx.def_kind(def_id) {
2211 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2212 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2213 self.tcx
2214 .type_of(field.did)
2215 .instantiate_identity()
2216 .skip_norm_wip()
2217 .visit_with(self)
2218 })
2219 }
2220 _ => ControlFlow::Continue(()),
2221 }
2222 }
2223}
2224
2225impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2226 type Result = ControlFlow<(), ()>;
2227
2228 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2229 if let Some(adt_def) = ty.ty_adt_def() {
2230 if adt_def.did() == self.item_def_id {
2231 return ControlFlow::Break(());
2232 }
2233 if self.seen.insert(adt_def.did()) {
2234 self.visit_def(adt_def.did())?;
2235 }
2236 }
2237 ty.super_visit_with(self)
2238 }
2239}
2240
2241struct CollectUsageSpans<'a> {
2246 spans: &'a mut Vec<Span>,
2247 param_def_id: DefId,
2248}
2249
2250impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2251 type Result = ();
2252
2253 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2254 }
2256
2257 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2258 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2259 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2260 && def_id == self.param_def_id
2261 {
2262 self.spans.push(t.span);
2263 return;
2264 } else if let Res::SelfTyAlias { .. } = qpath.res {
2265 self.spans.push(t.span);
2266 return;
2267 }
2268 }
2269 intravisit::walk_ty(self, t);
2270 }
2271}
2272
2273impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2274 {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2276u32),
::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_all(&[]) })
} 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 clauses_with_span =
tcx.clauses_of(self.body_def_id).clauses.iter().copied();
let implied_obligations =
traits::elaborate(tcx, clauses_with_span);
for (clause, obligation_span) in implied_obligations {
match clause.kind().skip_binder() {
ty::ClauseKind::WellFormed(..) |
ty::ClauseKind::UnstableFeature(..) => continue,
_ => {}
}
if clause.is_global() &&
!clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
let clause =
self.normalize(span, None, Unnormalized::new_wip(clause));
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, clause);
self.ocx.register_obligation(obligation);
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2277 fn check_false_global_bounds(&mut self) {
2278 let tcx = self.ocx.infcx.tcx;
2279 let mut span = tcx.def_span(self.body_def_id);
2280 let empty_env = ty::ParamEnv::empty();
2281
2282 let clauses_with_span = tcx.clauses_of(self.body_def_id).clauses.iter().copied();
2283 let implied_obligations = traits::elaborate(tcx, clauses_with_span);
2285
2286 for (clause, obligation_span) in implied_obligations {
2287 match clause.kind().skip_binder() {
2288 ty::ClauseKind::WellFormed(..)
2292 | ty::ClauseKind::UnstableFeature(..) => continue,
2294 _ => {}
2295 }
2296
2297 if clause.is_global() && !clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2299 let clause = self.normalize(span, None, Unnormalized::new_wip(clause));
2300
2301 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2303 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2304 span = predicates
2305 .iter()
2306 .find(|pred| pred.span.contains(obligation_span))
2308 .map(|pred| pred.span)
2309 .unwrap_or(obligation_span);
2310 }
2311
2312 let obligation = Obligation::new(
2313 tcx,
2314 traits::ObligationCause::new(
2315 span,
2316 self.body_def_id,
2317 ObligationCauseCode::TrivialBound,
2318 ),
2319 empty_env,
2320 clause,
2321 );
2322 self.ocx.register_obligation(obligation);
2323 }
2324 }
2325 }
2326
2327 {}
#[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_test_binder_body",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2327u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("body")
}> =
::tracing::__macro_support::FieldName::new("body");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body)
as &dyn ::tracing::field::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 TestBinderBody { foralls, exists, constraints, predicates } =
body;
if !predicates.is_empty() {
for (predicate, span) in predicates {
let cause =
traits::ObligationCause::misc(span, self.body_def_id);
let obligation =
Obligation::new(self.tcx(), cause, self.param_env,
predicate);
self.register_obligation(obligation);
}
match self.ocx.evaluate_obligations_error_on_ambiguity() {
TraitErrors::NoErrors => (),
TraitErrors::HasErrors(errors) => {
self.infcx.err_ctxt().report_fulfillment_errors(errors);
return;
}
}
}
let constraints =
match validate(self.tcx(), &constraints) {
Ok(()) => constraints,
Err(_guar) =>
ty::region_constraint::RegionConstraint::new_true(),
};
self.infcx.register_solver_region_constraint(constraints);
for forall in foralls { self.check_test_binder_forall(forall); }
for exists in exists { self.check_test_binder_exists(exists); }
fn validate<'tcx>(tcx: TyCtxt<'tcx>,
constraint: &SolverRegionConstraint<'tcx>)
-> Result<(), ErrorGuaranteed> {
let mut r = Ok(());
let mut validate_and =
|and: &And<TyCtxt<'_>, _>|
{
for c in and.0.iter() {
match c {
LeafRegionConstraint::Ambiguity(_) |
LeafRegionConstraint::RegionOutlives(..) |
LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (),
LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) =>
{
if let ty::Placeholder(_) | ty::Param(_) = ty.kind()
{} else {
let mut err =
tcx.dcx().struct_span_err(*span,
"the lhs of a ty outlives must be a placeholder");
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("it is a {0}", ty))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and here it is `Debug`ged :3 {0:?}",
ty))
}));
r = Err(err.emit());
}
}
}
}
};
validate_and(&constraint.and_constraint);
for and in constraint.or_constraint.0.iter() {
validate_and(and);
}
r
}
}
}
}#[instrument(level = "debug", skip(self))]
2328 pub(super) fn check_test_binder_body(&self, body: TestBinderBody<'tcx>) {
2329 let TestBinderBody { foralls, exists, constraints, predicates } = body;
2330 if !predicates.is_empty() {
2331 for (predicate, span) in predicates {
2332 let cause = traits::ObligationCause::misc(span, self.body_def_id);
2333 let obligation = Obligation::new(self.tcx(), cause, self.param_env, predicate);
2334 self.register_obligation(obligation);
2335 }
2336 match self.ocx.evaluate_obligations_error_on_ambiguity() {
2337 TraitErrors::NoErrors => (),
2338 TraitErrors::HasErrors(errors) => {
2339 self.infcx.err_ctxt().report_fulfillment_errors(errors);
2340 return;
2341 }
2342 }
2343 }
2344
2345 let constraints = match validate(self.tcx(), &constraints) {
2346 Ok(()) => constraints,
2347 Err(_guar) => ty::region_constraint::RegionConstraint::new_true(),
2348 };
2349
2350 self.infcx.register_solver_region_constraint(constraints);
2351
2352 for forall in foralls {
2353 self.check_test_binder_forall(forall);
2354 }
2355 for exists in exists {
2356 self.check_test_binder_exists(exists);
2357 }
2358
2359 fn validate<'tcx>(
2360 tcx: TyCtxt<'tcx>,
2361 constraint: &SolverRegionConstraint<'tcx>,
2362 ) -> Result<(), ErrorGuaranteed> {
2363 let mut r = Ok(());
2364
2365 let mut validate_and = |and: &And<TyCtxt<'_>, _>| {
2366 for c in and.0.iter() {
2367 match c {
2368 LeafRegionConstraint::Ambiguity(_)
2369 | LeafRegionConstraint::RegionOutlives(..)
2370 | LeafRegionConstraint::AliasTyOutlivesViaEnv(..) => (), LeafRegionConstraint::PlaceholderTyOutlives(ty, _, span) => {
2372 if let ty::Placeholder(_) | ty::Param(_) = ty.kind() {
2375 } else {
2377 let mut err = tcx.dcx().struct_span_err(
2378 *span,
2379 "the lhs of a ty outlives must be a placeholder",
2380 );
2381 err.note(format!("it is a {ty}"));
2382 err.note(format!("and here it is `Debug`ged :3 {ty:?}"));
2383 r = Err(err.emit());
2384 }
2385 }
2386 }
2387 }
2388 };
2389
2390 validate_and(&constraint.and_constraint);
2391 for and in constraint.or_constraint.0.iter() {
2392 validate_and(and);
2393 }
2394
2395 r
2396 }
2397 }
2398
2399 {}
#[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_test_binder_forall",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2399u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("forall")
}> =
::tracing::__macro_support::FieldName::new("forall");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&forall)
as &dyn ::tracing::field::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;
}
{
self.infcx.enter_forall(forall.binder,
|body|
{
let u = self.infcx.universe();
let mut builder = TransitiveRelationBuilder::default();
for &(r1, r2) in &body.region_outlives {
builder.add(r1, r2);
}
let assumptions =
ty::region_constraint::Assumptions::new_unelaborated(body.type_outlives,
builder.freeze());
self.infcx.insert_placeholder_assumptions(u,
Some(assumptions));
self.check_test_binder_body(body.value);
let solver_region_constraint =
self.infcx.get_solver_region_constraint();
let constraint =
ty::region_constraint::eagerly_handle_placeholders_in_universe(self.infcx,
solver_region_constraint.without_spans(),
u).with_spans(forall.span);
if let Some(assert_on_exit) = &forall.assert_on_exit {
self.check_test_binder_region_constraints(forall.span,
assert_on_exit, &constraint);
}
self.infcx.overwrite_solver_region_constraint(constraint);
});
}
}
}#[instrument(level = "debug", skip(self))]
2400 fn check_test_binder_forall(&self, forall: TestBinderForall<'tcx>) {
2401 self.infcx.enter_forall(forall.binder, |body| {
2402 let u = self.infcx.universe();
2403 let mut builder = TransitiveRelationBuilder::default();
2404 for &(r1, r2) in &body.region_outlives {
2405 builder.add(r1, r2);
2406 }
2407 let assumptions = ty::region_constraint::Assumptions::new_unelaborated(
2410 body.type_outlives,
2411 builder.freeze(),
2412 );
2413 self.infcx.insert_placeholder_assumptions(u, Some(assumptions));
2414 self.check_test_binder_body(body.value);
2415 let solver_region_constraint = self.infcx.get_solver_region_constraint();
2416 let constraint = ty::region_constraint::eagerly_handle_placeholders_in_universe(
2417 self.infcx,
2418 solver_region_constraint.without_spans(),
2419 u,
2420 )
2421 .with_spans(forall.span);
2422 if let Some(assert_on_exit) = &forall.assert_on_exit {
2423 self.check_test_binder_region_constraints(forall.span, assert_on_exit, &constraint);
2424 }
2425 self.infcx.overwrite_solver_region_constraint(constraint);
2426 });
2427 }
2428
2429 {}
#[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_test_binder_region_constraints",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2429u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fallback_span")
}> =
::tracing::__macro_support::FieldName::new("fallback_span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("actual")
}> =
::tracing::__macro_support::FieldName::new("actual");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fallback_span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&actual)
as &dyn ::tracing::field::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;
}
{
fn err<'tcx>(tcx: TyCtxt<'tcx>, expected_span: Span,
expected: impl std::fmt::Debug, actual_span: Option<Span>,
actual: impl std::fmt::Debug) {
let mut err =
tcx.dcx().struct_span_err(expected_span,
"forall expect clause failed");
if let Some(actual_span) = actual_span {
err.span_note(actual_span, "constraint from here");
}
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected: {0:#?}",
expected))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("actual: {0:#?}", actual))
}));
err.emit();
}
let span_of_and =
|c: &And<_, _>|
{
c.0.iter().map(|leaf|
leaf.span()).reduce(|span: Span, acc| acc.to(span))
};
let span_of_or =
|c: &Or<_, _>|
{
c.0.iter().flat_map(|and|
span_of_and(and)).reduce(|span, acc| acc.to(span))
};
let check_leaf_constraint =
|expected: LeafRegionConstraint<_, _>,
actual: LeafRegionConstraint<_, _>|
{
if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected,
expected_span) = expected &&
let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual,
actual_span) = actual {
let expected_anon =
self.tcx().anonymize_bound_vars(expected);
let actual_anon = self.tcx().anonymize_bound_vars(actual);
if expected_anon != actual_anon {
let mut err =
self.tcx().dcx().struct_span_err(expected_span,
"forall expect clause failed");
err.span_note(actual_span, "constraint from here");
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected: {0:#?}",
expected))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("actual: {0:#?}", actual))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected_anon: {0:#?}",
expected_anon))
}));
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("actual_anon: {0:#?}",
actual_anon))
}));
err.emit();
}
} else if expected.clone().without_span() !=
actual.clone().without_span() {
err(self.tcx(), expected.span(), expected,
Some(actual.span()), actual);
}
};
let check_and_constraint =
|expected: And<_, _>, actual: And<_, _>|
{
if expected.0.len() != actual.0.len() {
err(self.tcx(),
span_of_and(&expected).unwrap_or(fallback_span), expected,
span_of_and(&actual), actual)
} else {
for (expected, actual) in
expected.0.into_iter().zip(actual.0.into_iter()) {
check_leaf_constraint(expected, actual);
}
}
};
let check_or_constraint =
|expected: Or<_, _>, actual: Or<_, _>|
{
if expected.0.len() != actual.0.len() {
err(self.tcx(),
span_of_or(&expected).unwrap_or(fallback_span), expected,
span_of_or(&actual), actual)
} else {
for (expected, actual) in
expected.0.into_iter().zip(actual.0.into_iter()) {
check_and_constraint(expected, actual);
}
}
};
check_or_constraint(expected.or_constraint.clone(),
actual.or_constraint.clone());
check_and_constraint(expected.and_constraint.clone(),
actual.and_constraint.clone());
}
}
}#[instrument(level = "debug", skip(self))]
2430 fn check_test_binder_region_constraints(
2431 &self,
2432 fallback_span: Span,
2433 expected: &SolverRegionConstraint<'tcx>,
2434 actual: &SolverRegionConstraint<'tcx>,
2435 ) {
2436 fn err<'tcx>(
2437 tcx: TyCtxt<'tcx>,
2438 expected_span: Span,
2439 expected: impl std::fmt::Debug,
2440 actual_span: Option<Span>,
2441 actual: impl std::fmt::Debug,
2442 ) {
2443 let mut err = tcx.dcx().struct_span_err(expected_span, "forall expect clause failed");
2444 if let Some(actual_span) = actual_span {
2445 err.span_note(actual_span, "constraint from here");
2446 }
2447 err.note(format!("expected: {expected:#?}"));
2448 err.note(format!("actual: {actual:#?}"));
2449 err.emit();
2450 }
2451
2452 let span_of_and = |c: &And<_, _>| {
2453 c.0.iter().map(|leaf| leaf.span()).reduce(|span: Span, acc| acc.to(span))
2454 };
2455
2456 let span_of_or = |c: &Or<_, _>| {
2457 c.0.iter().flat_map(|and| span_of_and(and)).reduce(|span, acc| acc.to(span))
2458 };
2459
2460 let check_leaf_constraint =
2461 |expected: LeafRegionConstraint<_, _>, actual: LeafRegionConstraint<_, _>| {
2462 if let LeafRegionConstraint::AliasTyOutlivesViaEnv(expected, expected_span) =
2463 expected
2464 && let LeafRegionConstraint::AliasTyOutlivesViaEnv(actual, actual_span) = actual
2465 {
2466 let expected_anon = self.tcx().anonymize_bound_vars(expected);
2467 let actual_anon = self.tcx().anonymize_bound_vars(actual);
2468 if expected_anon != actual_anon {
2469 let mut err = self
2470 .tcx()
2471 .dcx()
2472 .struct_span_err(expected_span, "forall expect clause failed");
2473 err.span_note(actual_span, "constraint from here");
2474 err.note(format!("expected: {expected:#?}"));
2475 err.note(format!("actual: {actual:#?}"));
2476 err.note(format!("expected_anon: {expected_anon:#?}"));
2477 err.note(format!("actual_anon: {actual_anon:#?}"));
2478 err.emit();
2479 }
2480 } else if expected.clone().without_span() != actual.clone().without_span() {
2481 err(self.tcx(), expected.span(), expected, Some(actual.span()), actual);
2482 }
2483 };
2484
2485 let check_and_constraint = |expected: And<_, _>, actual: And<_, _>| {
2486 if expected.0.len() != actual.0.len() {
2487 err(
2488 self.tcx(),
2489 span_of_and(&expected).unwrap_or(fallback_span),
2490 expected,
2491 span_of_and(&actual),
2492 actual,
2493 )
2494 } else {
2495 for (expected, actual) in expected.0.into_iter().zip(actual.0.into_iter()) {
2496 check_leaf_constraint(expected, actual);
2497 }
2498 }
2499 };
2500
2501 let check_or_constraint = |expected: Or<_, _>, actual: Or<_, _>| {
2502 if expected.0.len() != actual.0.len() {
2503 err(
2504 self.tcx(),
2505 span_of_or(&expected).unwrap_or(fallback_span),
2506 expected,
2507 span_of_or(&actual),
2508 actual,
2509 )
2510 } else {
2511 for (expected, actual) in expected.0.into_iter().zip(actual.0.into_iter()) {
2512 check_and_constraint(expected, actual);
2513 }
2514 }
2515 };
2516
2517 check_or_constraint(expected.or_constraint.clone(), actual.or_constraint.clone());
2518 check_and_constraint(expected.and_constraint.clone(), actual.and_constraint.clone());
2519 }
2520
2521 {}
#[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_test_binder_exists",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2521u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("exists")
}> =
::tracing::__macro_support::FieldName::new("exists");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&exists)
as &dyn ::tracing::field::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 body =
self.infcx.instantiate_binder_with_fresh_vars(exists.span,
BoundRegionConversionTime::HigherRankedType, exists.binder);
self.check_test_binder_body(body);
}
}
}#[instrument(level = "debug", skip(self))]
2522 fn check_test_binder_exists(&self, exists: TestBinderExists<'tcx>) {
2523 let body = self.infcx.instantiate_binder_with_fresh_vars(
2524 exists.span,
2525 BoundRegionConversionTime::HigherRankedType,
2526 exists.binder,
2527 );
2528 self.check_test_binder_body(body);
2529 }
2530}
2531
2532pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2533 let items = tcx.hir_crate_items(());
2534 let res =
2535 items
2536 .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2537 .and(
2538 items.par_impl_items(|item| {
2539 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2540 }),
2541 )
2542 .and(items.par_trait_items(|item| {
2543 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2544 }))
2545 .and(items.par_foreign_items(|item| {
2546 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2547 }))
2548 .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2549 .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2550
2551 super::entry::check_for_entry_fn(tcx)?;
2552
2553 res
2554}
2555
2556fn lint_redundant_lifetimes<'tcx>(
2557 tcx: TyCtxt<'tcx>,
2558 owner_id: LocalDefId,
2559 outlives_env: &OutlivesEnvironment<'tcx>,
2560) {
2561 let def_kind = tcx.def_kind(owner_id);
2562 match def_kind {
2563 DefKind::Struct
2564 | DefKind::Union
2565 | DefKind::Enum
2566 | DefKind::Trait
2567 | DefKind::TraitAlias
2568 | DefKind::Fn
2569 | DefKind::Const
2570 | DefKind::Impl { of_trait: _ }
2571 | DefKind::TestBinderConstraints => {
2572 }
2574 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2575 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2576 return;
2581 }
2582 }
2583 DefKind::Mod
2584 | DefKind::Variant
2585 | DefKind::TyAlias
2586 | DefKind::ForeignTy
2587 | DefKind::TyParam
2588 | DefKind::ConstParam
2589 | DefKind::Static { .. }
2590 | DefKind::Ctor(_, _)
2591 | DefKind::Macro(_)
2592 | DefKind::ExternCrate
2593 | DefKind::Use
2594 | DefKind::ForeignMod
2595 | DefKind::AnonConst
2596 | DefKind::OpaqueTy
2597 | DefKind::Field
2598 | DefKind::LifetimeParam
2599 | DefKind::GlobalAsm
2600 | DefKind::Closure
2601 | DefKind::SyntheticCoroutineBody => return,
2602 }
2603
2604 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];
2613 lifetimes.extend(
2614 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2615 );
2616 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2618 for (idx, var) in tcx
2619 .fn_sig(owner_id)
2620 .instantiate_identity()
2621 .skip_norm_wip()
2622 .bound_vars()
2623 .iter()
2624 .enumerate()
2625 {
2626 let ty::BoundVariableKind::Region(kind) = var else { continue };
2627 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2628 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2629 }
2630 }
2631 lifetimes.retain(|candidate| candidate.is_named(tcx));
2632
2633 let mut shadowed = FxHashSet::default();
2637
2638 for (idx, &candidate) in lifetimes.iter().enumerate() {
2639 if shadowed.contains(&candidate) {
2644 continue;
2645 }
2646
2647 for &victim in &lifetimes[(idx + 1)..] {
2648 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2656 continue;
2657 };
2658
2659 if tcx.parent(def_id) != owner_id.to_def_id() {
2664 continue;
2665 }
2666
2667 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2669 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2670 {
2671 shadowed.insert(victim);
2672 tcx.emit_node_span_lint(
2673 REDUNDANT_LIFETIMES,
2674 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2675 tcx.def_span(def_id),
2676 RedundantLifetimeArgsLint { candidate, victim },
2677 );
2678 }
2679 }
2680 }
2681}
2682
2683#[derive(const _: () =
{
impl<'_sess, 'tcx, G> rustc_errors::Diagnostic<'_sess, G> for
RedundantLifetimeArgsLint<'tcx> {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
RedundantLifetimeArgsLint {
victim: __binding_0, candidate: __binding_1 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unnecessary lifetime parameter `{$victim}`")));
diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")));
;
diag.arg("victim", __binding_0);
diag.arg("candidate", __binding_1);
diag
}
}
}
}
};Diagnostic)]
2684#[diag("unnecessary lifetime parameter `{$victim}`")]
2685#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2686struct RedundantLifetimeArgsLint<'tcx> {
2687 victim: ty::Region<'tcx>,
2689 candidate: ty::Region<'tcx>,
2691}
2692
2693#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderBody<'tcx> {
#[inline]
fn clone(&self) -> TestBinderBody<'tcx> {
TestBinderBody {
foralls: ::core::clone::Clone::clone(&self.foralls),
exists: ::core::clone::Clone::clone(&self.exists),
constraints: ::core::clone::Clone::clone(&self.constraints),
predicates: ::core::clone::Clone::clone(&self.predicates),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderBody<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"TestBinderBody", "foralls", &self.foralls, "exists",
&self.exists, "constraints", &self.constraints, "predicates",
&&self.predicates)
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderBody<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
TestBinderBody {
foralls: __binding_0,
exists: __binding_1,
constraints: __binding_2,
predicates: __binding_3 } => {
TestBinderBody {
foralls: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
exists: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
constraints: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
__folder)?,
predicates: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_3,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
TestBinderBody {
foralls: __binding_0,
exists: __binding_1,
constraints: __binding_2,
predicates: __binding_3 } => {
TestBinderBody {
foralls: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
exists: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
constraints: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
__folder),
predicates: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_3,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderBody<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TestBinderBody {
foralls: ref __binding_0,
exists: ref __binding_1,
constraints: ref __binding_2,
predicates: ref __binding_3 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_3,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
2694pub(crate) struct TestBinderBody<'tcx> {
2695 pub foralls: Vec<TestBinderForall<'tcx>>,
2696 pub exists: Vec<TestBinderExists<'tcx>>,
2697 pub constraints: SolverRegionConstraint<'tcx>,
2699 pub predicates: Vec<(ty::Binder<'tcx, ty::ClauseKind<'tcx>>, Span)>,
2701}
2702
2703#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderForall<'tcx> {
#[inline]
fn clone(&self) -> TestBinderForall<'tcx> {
TestBinderForall {
span: ::core::clone::Clone::clone(&self.span),
binder: ::core::clone::Clone::clone(&self.binder),
assert_on_exit: ::core::clone::Clone::clone(&self.assert_on_exit),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderForall<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"TestBinderForall", "span", &self.span, "binder", &self.binder,
"assert_on_exit", &&self.assert_on_exit)
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderForall<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
TestBinderForall {
span: __binding_0,
binder: __binding_1,
assert_on_exit: __binding_2 } => {
TestBinderForall {
span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
assert_on_exit: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
TestBinderForall {
span: __binding_0,
binder: __binding_1,
assert_on_exit: __binding_2 } => {
TestBinderForall {
span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
assert_on_exit: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderForall<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TestBinderForall {
span: ref __binding_0,
binder: ref __binding_1,
assert_on_exit: ref __binding_2 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
2704pub(crate) struct TestBinderForall<'tcx> {
2705 pub span: Span,
2706 pub binder: ty::Binder<'tcx, WithWhereClauses<'tcx, TestBinderBody<'tcx>>>,
2707 pub assert_on_exit: Option<SolverRegionConstraint<'tcx>>,
2708}
2709
2710#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for TestBinderExists<'tcx> {
#[inline]
fn clone(&self) -> TestBinderExists<'tcx> {
TestBinderExists {
span: ::core::clone::Clone::clone(&self.span),
binder: ::core::clone::Clone::clone(&self.binder),
}
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TestBinderExists<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"TestBinderExists", "span", &self.span, "binder", &&self.binder)
}
}Debug, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderExists<'tcx> {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
TestBinderExists { span: __binding_0, binder: __binding_1 }
=> {
TestBinderExists {
span: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
binder: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
TestBinderExists { span: __binding_0, binder: __binding_1 }
=> {
TestBinderExists {
span: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
binder: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for TestBinderExists<'tcx> {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
TestBinderExists {
span: ref __binding_0, binder: ref __binding_1 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
2711pub(crate) struct TestBinderExists<'tcx> {
2712 pub span: Span,
2713 pub binder: ty::Binder<'tcx, TestBinderBody<'tcx>>,
2714}
2715
2716#[derive(#[automatically_derived]
impl<'tcx, T: ::core::clone::Clone> ::core::clone::Clone for
WithWhereClauses<'tcx, T> {
#[inline]
fn clone(&self) -> WithWhereClauses<'tcx, T> {
WithWhereClauses {
value: ::core::clone::Clone::clone(&self.value),
type_outlives: ::core::clone::Clone::clone(&self.type_outlives),
region_outlives: ::core::clone::Clone::clone(&self.region_outlives),
}
}
}Clone, #[automatically_derived]
impl<'tcx, T: ::core::fmt::Debug> ::core::fmt::Debug for
WithWhereClauses<'tcx, T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"WithWhereClauses", "value", &self.value, "type_outlives",
&self.type_outlives, "region_outlives", &&self.region_outlives)
}
}Debug, const _: () =
{
impl<'tcx, T>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for WithWhereClauses<'tcx, T> where
T: ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
{
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
WithWhereClauses {
value: __binding_0,
type_outlives: __binding_1,
region_outlives: __binding_2 } => {
WithWhereClauses {
value: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
type_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
region_outlives: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
WithWhereClauses {
value: __binding_0,
type_outlives: __binding_1,
region_outlives: __binding_2 } => {
WithWhereClauses {
value: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
type_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
region_outlives: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx, T>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for WithWhereClauses<'tcx, T> where
T: ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
{
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
WithWhereClauses {
value: ref __binding_0,
type_outlives: ref __binding_1,
region_outlives: ref __binding_2 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable)]
2717pub(crate) struct WithWhereClauses<'tcx, T> {
2718 pub value: T,
2719
2720 pub type_outlives: Vec<ty::Binder<'tcx, ty::OutlivesClause<'tcx, Ty<'tcx>>>>,
2723 pub region_outlives: Vec<(ty::Region<'tcx>, ty::Region<'tcx>)>,
2724}