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::trait_def::TraitSpecializationKind;
25use rustc_middle::ty::{
26 self, GenericArgKind, GenericArgs, GenericParamDefKind, RegionExt, Ty, TyCtxt, TypeFlags,
27 TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
28 Unnormalized, Upcast,
29};
30use rustc_middle::{bug, span_bug};
31use rustc_session::diagnostics::feature_err;
32use rustc_span::{DUMMY_SP, Span, 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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:187",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(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, tcx.def_span(body_def_id));
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 =
218 infcx_compat.resolve_regions_with_outlives_env(&outlives_env, tcx.def_span(body_def_id));
219 if errors_compat.is_empty() {
220 Ok(())
223 } else {
224 Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
225 }
226}
227
228pub(super) fn check_well_formed(
229 tcx: TyCtxt<'_>,
230 def_id: LocalDefId,
231) -> Result<(), ErrorGuaranteed> {
232 let mut res = crate::check::check::check_item_type(tcx, def_id);
233
234 for param in &tcx.generics_of(def_id).own_params {
235 res = res.and(check_param_wf(tcx, param));
236 }
237
238 res
239}
240
241{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(254u32),
::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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:261",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(261u32),
::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 {
::rustc_middle::util::bug::bug_fmt(format_args!("impl_polarity query disagrees with impl\'s polarity in HIR"));
};
if let hir::Defaultness::Default { .. } =
of_trait.defaultness {
let mut spans =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[span]));
spans.extend(of_trait.defaultness_span);
res =
Err({
tcx.dcx().struct_span_err(spans,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("negative impls cannot be default impls"))
})).with_code(E0750)
}.emit());
}
}
}
} else { res = res.and(check_impl(tcx, item, impl_)); }
res
}
hir::ItemKind::Fn { sig, .. } =>
check_item_fn(tcx, def_id, sig.decl),
_ =>
::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("should have been handled by the type based wf check: {0:?}",
item)),
}
}
}
}#[instrument(skip(tcx), level = "debug")]
255pub(super) fn check_item<'tcx>(
256 tcx: TyCtxt<'tcx>,
257 item: &'tcx hir::Item<'tcx>,
258) -> Result<(), ErrorGuaranteed> {
259 let def_id = item.owner_id.def_id;
260
261 debug!(
262 ?item.owner_id,
263 item.name = ? tcx.def_path_str(def_id)
264 );
265
266 match item.kind {
267 hir::ItemKind::Impl(ref impl_) => {
285 crate::impl_wf_check::check_impl_wf(tcx, def_id, impl_.of_trait.is_some())?;
286 let mut res = Ok(());
287 if let Some(of_trait) = impl_.of_trait {
288 let header = tcx.impl_trait_header(def_id);
289 let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
290 if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
291 let sp = of_trait.trait_ref.path.span;
292 res = Err(tcx
293 .dcx()
294 .struct_span_err(sp, "impls of auto traits cannot be default")
295 .with_span_labels(of_trait.defaultness_span, "default because of this")
296 .with_span_label(sp, "auto trait")
297 .emit());
298 }
299 match header.polarity {
300 ty::ImplPolarity::Positive => {
301 res = res.and(check_impl(tcx, item, impl_));
302 }
303 ty::ImplPolarity::Negative => {
304 let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
305 bug!("impl_polarity query disagrees with impl's polarity in HIR");
306 };
307 if let hir::Defaultness::Default { .. } = of_trait.defaultness {
309 let mut spans = vec![span];
310 spans.extend(of_trait.defaultness_span);
311 res = Err(struct_span_code_err!(
312 tcx.dcx(),
313 spans,
314 E0750,
315 "negative impls cannot be default impls"
316 )
317 .emit());
318 }
319 }
320 }
321 } else {
322 res = res.and(check_impl(tcx, item, impl_));
323 }
324 res
325 }
326 hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
327 _ => span_bug!(item.span, "should have been handled by the type based wf check: {item:?}"),
329 }
330}
331
332pub(super) fn check_foreign_item<'tcx>(
333 tcx: TyCtxt<'tcx>,
334 item: &'tcx hir::ForeignItem<'tcx>,
335) -> Result<(), ErrorGuaranteed> {
336 let def_id = item.owner_id.def_id;
337
338 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:338",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(338u32),
::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!(
339 ?item.owner_id,
340 item.name = ? tcx.def_path_str(def_id)
341 );
342
343 match item.kind {
344 hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
345 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
346 }
347}
348
349pub(crate) fn check_trait_item<'tcx>(
350 tcx: TyCtxt<'tcx>,
351 def_id: LocalDefId,
352) -> Result<(), ErrorGuaranteed> {
353 lint_item_shadowing_supertrait_item(tcx, def_id);
355
356 let mut res = Ok(());
357
358 if tcx.def_kind(def_id) == DefKind::AssocFn {
359 for &assoc_ty_def_id in
360 tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
361 {
362 res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
363 }
364 }
365 res
366}
367
368pub(crate) fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
381 let mut required_bounds_by_item = FxIndexMap::default();
383 let associated_items = tcx.associated_items(trait_def_id);
384
385 loop {
391 let mut should_continue = false;
392 for gat_item in associated_items.in_definition_order() {
393 let gat_def_id = gat_item.def_id.expect_local();
394 let gat_item = tcx.associated_item(gat_def_id);
395 if !gat_item.is_type() {
397 continue;
398 }
399 let gat_generics = tcx.generics_of(gat_def_id);
400 if gat_generics.is_own_empty() {
402 continue;
403 }
404
405 let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
409 for item in associated_items.in_definition_order() {
410 let item_def_id = item.def_id.expect_local();
411 if item_def_id == gat_def_id {
413 continue;
414 }
415
416 let param_env = tcx.param_env(item_def_id);
417
418 let item_required_bounds = match tcx.associated_item(item_def_id).kind {
419 ty::AssocKind::Fn { .. } => {
421 let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
425 item_def_id.to_def_id(),
426 tcx.fn_sig(item_def_id).instantiate_identity().skip_norm_wip(),
427 );
428 gather_gat_bounds(
429 tcx,
430 param_env,
431 item_def_id,
432 sig.inputs_and_output,
433 &sig.inputs().iter().copied().collect(),
436 gat_def_id,
437 gat_generics,
438 )
439 }
440 ty::AssocKind::Type { .. } => {
442 let param_env = augment_param_env(
446 tcx,
447 param_env,
448 required_bounds_by_item.get(&item_def_id),
449 );
450 gather_gat_bounds(
451 tcx,
452 param_env,
453 item_def_id,
454 tcx.explicit_item_bounds(item_def_id)
455 .iter_identity_copied()
456 .map(Unnormalized::skip_norm_wip)
457 .collect::<Vec<_>>(),
458 &FxIndexSet::default(),
459 gat_def_id,
460 gat_generics,
461 )
462 }
463 ty::AssocKind::Const { .. } => None,
464 };
465
466 if let Some(item_required_bounds) = item_required_bounds {
467 if let Some(new_required_bounds) = &mut new_required_bounds {
473 new_required_bounds.retain(|b| item_required_bounds.contains(b));
474 } else {
475 new_required_bounds = Some(item_required_bounds);
476 }
477 }
478 }
479
480 if let Some(new_required_bounds) = new_required_bounds {
481 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
482 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
483 should_continue = true;
486 }
487 }
488 }
489 if !should_continue {
494 break;
495 }
496 }
497
498 for (gat_def_id, required_bounds) in required_bounds_by_item {
499 if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
501 continue;
502 }
503
504 let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
505 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:505",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(505u32),
::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);
506 let param_env = tcx.param_env(gat_def_id);
507
508 let unsatisfied_bounds: Vec<_> = required_bounds
509 .into_iter()
510 .filter(|clause| match clause.kind().skip_binder() {
511 ty::ClauseKind::RegionOutlives(ty::OutlivesClause(a, b)) => {
512 !region_known_to_outlive(
513 tcx,
514 gat_def_id,
515 param_env,
516 &FxIndexSet::default(),
517 a,
518 b,
519 )
520 }
521 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(a, b)) => {
522 !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
523 }
524 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected ClauseKind"))bug!("Unexpected ClauseKind"),
525 })
526 .map(|clause| clause.to_string())
527 .collect();
528
529 if !unsatisfied_bounds.is_empty() {
530 let plural = if unsatisfied_bounds.len() == 1 { "" } else { "s" }pluralize!(unsatisfied_bounds.len());
531 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!(
532 "{} {}",
533 gat_item_hir.generics.add_where_or_trailing_comma(),
534 unsatisfied_bounds.join(", "),
535 );
536 let bound =
537 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
538 tcx.dcx()
539 .struct_span_err(
540 gat_item_hir.span,
541 ::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),
542 )
543 .with_span_suggestion(
544 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
545 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add the required where clause{0}",
plural))
})format!("add the required where clause{plural}"),
546 suggestion,
547 Applicability::MachineApplicable,
548 )
549 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} currently required to ensure that impls have maximum flexibility",
bound))
})format!(
550 "{bound} currently required to ensure that impls have maximum flexibility"
551 ))
552 .with_note(
553 "we are soliciting feedback, see issue #87479 \
554 <https://github.com/rust-lang/rust/issues/87479> for more information",
555 )
556 .emit();
557 }
558 }
559}
560
561fn augment_param_env<'tcx>(
563 tcx: TyCtxt<'tcx>,
564 param_env: ty::ParamEnv<'tcx>,
565 new_clauses: Option<&FxIndexSet<ty::Clause<'tcx>>>,
566) -> ty::ParamEnv<'tcx> {
567 let Some(new_clauses) = new_clauses else {
568 return param_env;
569 };
570
571 if new_clauses.is_empty() {
572 return param_env;
573 }
574
575 let bounds = param_env.caller_bounds().chain(new_clauses.iter().copied());
576 ty::ParamEnv::new(tcx, bounds)
579}
580
581fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
592 tcx: TyCtxt<'tcx>,
593 param_env: ty::ParamEnv<'tcx>,
594 item_def_id: LocalDefId,
595 to_check: T,
596 wf_tys: &FxIndexSet<Ty<'tcx>>,
597 gat_def_id: LocalDefId,
598 gat_generics: &'tcx ty::Generics,
599) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
600 let mut bounds = FxIndexSet::default();
602
603 let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
604
605 if types.is_empty() && regions.is_empty() {
611 return None;
612 }
613
614 for (region_a, region_a_idx) in ®ions {
615 if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
619 continue;
620 }
621 for (ty, ty_idx) in &types {
626 if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
628 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:628",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(628u32),
::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);
629 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:629",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(629u32),
::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}");
630 let ty_param = gat_generics.param_at(*ty_idx, tcx);
634 let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
635 let region_param = gat_generics.param_at(*region_a_idx, tcx);
638 let region_param = ty::Region::new_early_param(
639 tcx,
640 ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
641 );
642 bounds.insert(
645 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty_param, region_param))
646 .upcast(tcx),
647 );
648 }
649 }
650
651 for (region_b, region_b_idx) in ®ions {
656 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 {
660 continue;
661 }
662 if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
663 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:663",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(663u32),
::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);
664 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:664",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(664u32),
::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}");
665 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
667 let region_a_param = ty::Region::new_early_param(
668 tcx,
669 ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
670 );
671 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
673 let region_b_param = ty::Region::new_early_param(
674 tcx,
675 ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
676 );
677 bounds.insert(
679 ty::ClauseKind::RegionOutlives(ty::OutlivesClause(
680 region_a_param,
681 region_b_param,
682 ))
683 .upcast(tcx),
684 );
685 }
686 }
687 }
688
689 Some(bounds)
690}
691
692struct GATArgsCollector<'tcx> {
697 gat: DefId,
698 regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
700 types: FxIndexSet<(Ty<'tcx>, usize)>,
702}
703
704impl<'tcx> GATArgsCollector<'tcx> {
705 fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
706 gat: DefId,
707 t: T,
708 ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
709 let mut visitor =
710 GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
711 t.visit_with(&mut visitor);
712 (visitor.regions, visitor.types)
713 }
714}
715
716impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
717 fn visit_ty(&mut self, t: Ty<'tcx>) {
718 match t.kind() {
719 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, args, .. })
720 if def_id == self.gat =>
721 {
722 for (idx, arg) in args.iter().enumerate() {
723 match arg.kind() {
724 GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
725 self.regions.insert((lt, idx));
726 }
727 GenericArgKind::Type(t) => {
728 self.types.insert((t, idx));
729 }
730 _ => {}
731 }
732 }
733 }
734 _ => {}
735 }
736 t.super_visit_with(self)
737 }
738}
739
740fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
741 let item_name = tcx.item_name(trait_item_def_id.to_def_id());
742 let trait_def_id = tcx.local_parent(trait_item_def_id);
743
744 let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
745 .skip(1)
746 .flat_map(|supertrait_def_id| {
747 tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
748 })
749 .collect();
750 if !shadowed.is_empty() {
751 let shadowee = if let [shadowed] = shadowed[..] {
752 diagnostics::SupertraitItemShadowee::Labeled {
753 span: tcx.def_span(shadowed.def_id),
754 supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
755 }
756 } else {
757 let (traits, spans): (Vec<_>, Vec<_>) = shadowed
758 .iter()
759 .map(|item| {
760 (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
761 })
762 .unzip();
763 diagnostics::SupertraitItemShadowee::Several {
764 traits: traits.into(),
765 spans: spans.into(),
766 }
767 };
768
769 tcx.emit_node_span_lint(
770 SHADOWING_SUPERTRAIT_ITEMS,
771 tcx.local_def_id_to_hir_id(trait_item_def_id),
772 tcx.def_span(trait_item_def_id),
773 diagnostics::SupertraitItemShadowing {
774 item: item_name,
775 subtrait: tcx.item_name(trait_def_id.to_def_id()),
776 shadowee,
777 },
778 );
779 }
780}
781
782fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
783 match param.kind {
784 ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
786
787 ty::GenericParamDefKind::Const { .. } => {
789 let ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
790 let span = tcx.def_span(param.def_id);
791 let def_id = param.def_id.expect_local();
792
793 if tcx.features().const_param_ty_unchecked() {
794 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
795 wfcx.register_wf_obligation(span, None, ty.into());
796 Ok(())
797 })
798 } else if tcx.features().adt_const_params() || tcx.features().min_adt_const_params() {
799 enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
800 wfcx.register_bound(
801 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
802 wfcx.param_env,
803 ty,
804 tcx.require_lang_item(LangItem::ConstParamTy, span),
805 );
806 Ok(())
807 })
808 } else {
809 let span = || {
810 let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
811 tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
812 else {
813 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
814 };
815 span
816 };
817 let mut diag = match ty.kind() {
818 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
819 ty::FnPtr(..) => tcx.dcx().struct_span_err(
820 span(),
821 "using function pointers as const generic parameters is forbidden",
822 ),
823 ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
824 span(),
825 "using raw pointers as const generic parameters is forbidden",
826 ),
827 _ => {
828 ty.error_reported()?;
830
831 tcx.dcx().struct_span_err(
832 span(),
833 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty))
})format!(
834 "`{ty}` is forbidden as the type of a const generic parameter",
835 ),
836 )
837 }
838 };
839
840 diag.note("the only supported types are integers, `bool`, and `char`");
841
842 let cause = ObligationCause::misc(span(), def_id);
843 let adt_const_params_feature_string =
844 " more complex and user defined types".to_string();
845 let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
846 tcx,
847 tcx.param_env(param.def_id),
848 ty,
849 cause,
850 ) {
851 Err(
853 ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
854 | ConstParamTyImplementationError::NonExhaustive(..)
855 | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
856 ) => None,
857 Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
858 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![
859 (adt_const_params_feature_string, sym::min_adt_const_params),
860 (
861 " references to implement the `ConstParamTy` trait".into(),
862 sym::unsized_const_params,
863 ),
864 ])
865 }
866 Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
869 fn ty_is_local(ty: Ty<'_>) -> bool {
870 match ty.kind() {
871 ty::Adt(adt_def, ..) => adt_def.did().is_local(),
872 ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
874 ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
877 ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
880 _ => false,
881 }
882 }
883
884 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![(
885 adt_const_params_feature_string,
886 sym::min_adt_const_params,
887 )])
888 }
889 Ok(..) => {
891 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)])
892 }
893 };
894 if let Some(features) = may_suggest_feature {
895 tcx.disabled_nightly_features(&mut diag, features);
896 }
897
898 Err(diag.emit())
899 }
900 }
901 }
902}
903
904{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_associated_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(904u32),
::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());
let has_value = item.defaultness(tcx).has_value();
if tcx.is_type_const(def_id) {
check_type_const(wfcx, def_id, ty, has_value)?;
}
if has_value {
let code = ObligationCauseCode::SizedConstOrStatic;
wfcx.register_bound(ObligationCause::new(span, def_id,
code), wfcx.param_env, ty,
tcx.require_lang_item(LangItem::Sized, span));
}
Ok(())
}
ty::AssocKind::Fn { .. } => {
let sig =
tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
let hir_sig =
tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
check_method_receiver(wfcx, hir_sig, item, self_ty)
}
ty::AssocKind::Type { .. } => {
if let ty::AssocContainer::Trait = item.container {
check_associated_type_bounds(wfcx, item, span)
}
if item.defaultness(tcx).has_value() {
let ty = tcx.type_of(def_id).instantiate_identity();
let ty =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
ty);
wfcx.register_wf_obligation(span, loc, ty.into());
}
Ok(())
}
}
})
}
}
}#[instrument(level = "debug", skip(tcx))]
905pub(crate) fn check_associated_item(
906 tcx: TyCtxt<'_>,
907 def_id: LocalDefId,
908) -> Result<(), ErrorGuaranteed> {
909 let loc = Some(WellFormedLoc::Ty(def_id));
910 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
911 let item = tcx.associated_item(def_id);
912
913 tcx.ensure_result().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
916
917 let self_ty = match item.container {
918 ty::AssocContainer::Trait => tcx.types.self_param,
919 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
920 tcx.type_of(item.container_id(tcx)).instantiate_identity().skip_norm_wip()
921 }
922 };
923
924 let span = tcx.def_span(def_id);
925
926 match item.kind {
927 ty::AssocKind::Const { .. } => {
928 let ty = tcx.type_of(def_id).instantiate_identity();
929 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
930 wfcx.register_wf_obligation(span, loc, ty.into());
931
932 let has_value = item.defaultness(tcx).has_value();
933 if tcx.is_type_const(def_id) {
934 check_type_const(wfcx, def_id, ty, has_value)?;
935 }
936
937 if has_value {
938 let code = ObligationCauseCode::SizedConstOrStatic;
939 wfcx.register_bound(
940 ObligationCause::new(span, def_id, code),
941 wfcx.param_env,
942 ty,
943 tcx.require_lang_item(LangItem::Sized, span),
944 );
945 }
946
947 Ok(())
948 }
949 ty::AssocKind::Fn { .. } => {
950 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
951 let hir_sig =
952 tcx.hir_node_by_def_id(def_id).fn_sig().expect("bad signature for method");
953 check_fn_or_method(wfcx, sig, hir_sig.decl, def_id);
954 check_method_receiver(wfcx, hir_sig, item, self_ty)
955 }
956 ty::AssocKind::Type { .. } => {
957 if let ty::AssocContainer::Trait = item.container {
958 check_associated_type_bounds(wfcx, item, span)
959 }
960 if item.defaultness(tcx).has_value() {
961 let ty = tcx.type_of(def_id).instantiate_identity();
962 let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
963 wfcx.register_wf_obligation(span, loc, ty.into());
964 }
965 Ok(())
966 }
967 }
968 })
969}
970
971pub(crate) fn check_type_defn<'tcx>(
973 tcx: TyCtxt<'tcx>,
974 item: LocalDefId,
975 all_sized: bool,
976) -> Result<(), ErrorGuaranteed> {
977 tcx.ensure_ok().check_representability(item);
978 let adt_def = tcx.adt_def(item);
979
980 enter_wf_checking_ctxt(tcx, item, |wfcx| {
981 let variants = adt_def.variants();
982 let packed = adt_def.repr().packed();
983
984 for variant in variants.iter() {
985 for field in &variant.fields {
987 if let Some(def_id) = field.value
988 && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
989 {
990 if let Some(def_id) = def_id.as_local()
993 && let DefKind::AnonConst = tcx.def_kind(def_id)
994 && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
995 && let expr = &tcx.hir_body(anon.body).value
996 && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
997 && let Res::Def(DefKind::ConstParam, _def_id) = path.res
998 {
999 } else {
1002 let _ = tcx.const_eval_poly(def_id);
1005 }
1006 }
1007 let field_id = field.did.expect_local();
1008 let span = tcx.ty_span(field_id);
1009 let ty = wfcx.deeply_normalize(
1010 span,
1011 None,
1012 tcx.type_of(field.did).instantiate_identity(),
1013 );
1014 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(field_id)), ty.into());
1015
1016 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())
1017 && !#[allow(non_exhaustive_omitted_patterns)] match adt_def.repr().scalable {
Some(ScalableElt::Container) => true,
_ => false,
}matches!(adt_def.repr().scalable, Some(ScalableElt::Container))
1018 {
1019 tcx.dcx().span_err(
1022 span,
1023 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("scalable vectors cannot be fields of a {0}",
adt_def.variant_descr()))
})format!(
1024 "scalable vectors cannot be fields of a {}",
1025 adt_def.variant_descr()
1026 ),
1027 );
1028 }
1029 }
1030
1031 let needs_drop_copy = || {
1034 packed && {
1035 let ty = tcx.type_of(variant.tail().did).instantiate_identity().skip_norm_wip();
1036 let ty = tcx.erase_and_anonymize_regions(ty);
1037 if !!ty.has_infer() {
::core::panicking::panic("assertion failed: !ty.has_infer()")
};assert!(!ty.has_infer());
1038 ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1039 }
1040 };
1041 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1043 let unsized_len = if all_sized { 0 } else { 1 };
1044 for (idx, field) in
1045 variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1046 {
1047 let last = idx == variant.fields.len() - 1;
1048 let span = tcx.ty_span(field.did.expect_local());
1049 let ty = wfcx.normalize(span, None, tcx.type_of(field.did).instantiate_identity());
1050 wfcx.register_bound(
1051 traits::ObligationCause::new(
1052 span,
1053 wfcx.body_def_id,
1054 ObligationCauseCode::FieldSized {
1055 adt_kind: adt_def.adt_kind(),
1056 span,
1057 last,
1058 },
1059 ),
1060 wfcx.param_env,
1061 ty,
1062 tcx.require_lang_item(LangItem::Sized, span),
1063 );
1064 }
1065
1066 if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1068 match tcx.const_eval_poly(discr_def_id) {
1069 Ok(_) => {}
1070 Err(ErrorHandled::Reported(..)) => {}
1071 Err(ErrorHandled::TooGeneric(sp)) => {
1072 ::rustc_middle::util::bug::span_bug_fmt(sp,
format_args!("enum variant discr was too generic to eval"))span_bug!(sp, "enum variant discr was too generic to eval")
1073 }
1074 }
1075 }
1076 }
1077
1078 check_where_clauses(wfcx, item);
1079 Ok(())
1080 })
1081}
1082
1083{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_trait",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1083u32),
::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))]
1084pub(crate) fn check_trait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1085 if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1086 return Ok(());
1088 }
1089
1090 let trait_def = tcx.trait_def(def_id);
1091 if trait_def.is_marker
1092 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1093 {
1094 for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1095 struct_span_code_err!(
1096 tcx.dcx(),
1097 tcx.def_span(*associated_def_id),
1098 E0714,
1099 "marker traits cannot have associated items",
1100 )
1101 .emit();
1102 }
1103 }
1104
1105 let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1106 check_where_clauses(wfcx, def_id);
1107 Ok(())
1108 });
1109
1110 res
1111}
1112
1113fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, _span: Span) {
1118 let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1119
1120 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1120",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1120u32),
::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);
1121 let wf_obligations = bounds.iter_identity_copied().map(Unnormalized::skip_norm_wip).flat_map(
1122 |(bound, bound_span)| {
1123 traits::wf::clause_obligations(
1124 wfcx.infcx,
1125 wfcx.param_env,
1126 wfcx.body_def_id,
1127 bound,
1128 bound_span,
1129 )
1130 },
1131 );
1132
1133 wfcx.register_obligations(wf_obligations);
1134}
1135
1136fn check_item_fn(
1137 tcx: TyCtxt<'_>,
1138 def_id: LocalDefId,
1139 decl: &hir::FnDecl<'_>,
1140) -> Result<(), ErrorGuaranteed> {
1141 enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1142 check_eiis_fn(tcx, def_id);
1143
1144 let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1145 check_fn_or_method(wfcx, sig, decl, def_id);
1146 Ok(())
1147 })
1148}
1149
1150fn check_eiis_fn(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1151 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) {
1154 let (foreign_item, name) = match resolution {
1155 EiiImplResolution::Macro(def_id) => {
1156 if let Some(foreign_item) =
1159 {
{
'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)
1160 {
1161 (foreign_item, tcx.item_name(*def_id))
1162 } else {
1163 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1164 return;
1165 }
1166 }
1167 EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1168 EiiImplResolution::Error(_eg) => return,
1169 };
1170
1171 let _ = compare_eii_function_types(tcx, def_id, foreign_item, name, *span);
1172 }
1173}
1174
1175fn check_eiis_static<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, ty: Ty<'tcx>) {
1176 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) {
1179 let (foreign_item, name) = match resolution {
1180 EiiImplResolution::Macro(def_id) => {
1181 if let Some(foreign_item) =
1184 {
{
'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)
1185 {
1186 (foreign_item, tcx.item_name(*def_id))
1187 } else {
1188 tcx.dcx().span_delayed_bug(*span, "resolved to something that's not an EII");
1189 return;
1190 }
1191 }
1192 EiiImplResolution::Known(def_id) => (*def_id, tcx.item_name(*def_id)),
1193 EiiImplResolution::Error(_eg) => return,
1194 };
1195
1196 let _ = compare_eii_statics(tcx, def_id, ty, foreign_item, name, *span);
1197 }
1198}
1199
1200{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_static_item",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1200u32),
::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))]
1201pub(crate) fn check_static_item<'tcx>(
1202 tcx: TyCtxt<'tcx>,
1203 item_id: LocalDefId,
1204 ty: Ty<'tcx>,
1205 should_check_for_sync: bool,
1206) -> Result<(), ErrorGuaranteed> {
1207 enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1208 if should_check_for_sync {
1209 check_eiis_static(tcx, item_id, ty);
1210 }
1211
1212 let span = tcx.ty_span(item_id);
1213 let loc = Some(WellFormedLoc::Ty(item_id));
1214 let item_ty = wfcx.deeply_normalize(span, loc, Unnormalized::new_wip(ty));
1215
1216 let is_foreign_item = tcx.is_foreign_item(item_id);
1217 let is_structurally_foreign_item = || {
1218 let tail = tcx.struct_tail_raw(
1219 item_ty,
1220 &ObligationCause::dummy(),
1221 |ty| wfcx.deeply_normalize(span, loc, ty),
1222 || {},
1223 );
1224
1225 matches!(tail.kind(), ty::Foreign(_))
1226 };
1227 let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1228
1229 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1230 if forbid_unsized {
1231 let span = tcx.def_span(item_id);
1232 wfcx.register_bound(
1233 traits::ObligationCause::new(
1234 span,
1235 wfcx.body_def_id,
1236 ObligationCauseCode::SizedConstOrStatic,
1237 ),
1238 wfcx.param_env,
1239 item_ty,
1240 tcx.require_lang_item(LangItem::Sized, span),
1241 );
1242 }
1243
1244 let should_check_for_sync = should_check_for_sync
1246 && !is_foreign_item
1247 && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1248 && !tcx.is_thread_local_static(item_id.to_def_id());
1249
1250 if should_check_for_sync {
1251 wfcx.register_bound(
1252 traits::ObligationCause::new(
1253 span,
1254 wfcx.body_def_id,
1255 ObligationCauseCode::SharedStatic,
1256 ),
1257 wfcx.param_env,
1258 item_ty,
1259 tcx.require_lang_item(LangItem::Sync, span),
1260 );
1261 }
1262 Ok(())
1263 })
1264}
1265
1266{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_type_const",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1266u32),
::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()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("has_value")
}> =
::tracing::__macro_support::FieldName::new("has_value");
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)),
(::tracing::__macro_support::Option::Some(&has_value 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();
let span = tcx.def_span(def_id);
if !tcx.features().const_param_ty_unchecked() {
wfcx.register_bound(ObligationCause::new(span, def_id,
ObligationCauseCode::ConstParam(item_ty)), wfcx.param_env,
item_ty,
tcx.require_lang_item(LangItem::ConstParamTy, span));
}
if has_value {
let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
let norm_ct =
wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)),
raw_ct);
wfcx.register_wf_obligation(span,
Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
wfcx.register_obligation(Obligation::new(tcx,
ObligationCause::new(span, def_id,
ObligationCauseCode::WellFormed(None)), wfcx.param_env,
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct,
item_ty))));
}
Ok(())
}
}
}#[instrument(level = "debug", skip(wfcx))]
1267pub(super) fn check_type_const<'tcx>(
1268 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1269 def_id: LocalDefId,
1270 item_ty: Ty<'tcx>,
1271 has_value: bool,
1272) -> Result<(), ErrorGuaranteed> {
1273 let tcx = wfcx.tcx();
1274 let span = tcx.def_span(def_id);
1275
1276 if !tcx.features().const_param_ty_unchecked() {
1277 wfcx.register_bound(
1278 ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1279 wfcx.param_env,
1280 item_ty,
1281 tcx.require_lang_item(LangItem::ConstParamTy, span),
1282 );
1283 }
1284
1285 if has_value {
1286 let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1287 let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1288 wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1289
1290 wfcx.register_obligation(Obligation::new(
1291 tcx,
1292 ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1293 wfcx.param_env,
1294 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1295 ));
1296 }
1297 Ok(())
1298}
1299
1300{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_impl",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1300u32),
::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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:1369",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1369u32),
::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_))]
1301fn check_impl<'tcx>(
1302 tcx: TyCtxt<'tcx>,
1303 item: &'tcx hir::Item<'tcx>,
1304 impl_: &hir::Impl<'_>,
1305) -> Result<(), ErrorGuaranteed> {
1306 enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1307 match impl_.of_trait {
1308 Some(of_trait) => {
1309 let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1310 tcx.ensure_result().coherent_trait(trait_ref.skip_normalization().def_id)?;
1313 let trait_span = of_trait.trait_ref.path.span;
1314 let trait_ref = wfcx.deeply_normalize(
1315 trait_span,
1316 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1317 trait_ref,
1318 );
1319 let trait_pred =
1320 ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive };
1321 let mut obligations = traits::wf::trait_obligations(
1322 wfcx.infcx,
1323 wfcx.param_env,
1324 wfcx.body_def_id,
1325 trait_pred,
1326 trait_span,
1327 item,
1328 );
1329 for obligation in &mut obligations {
1330 if obligation.cause.span != trait_span {
1331 continue;
1333 }
1334 if let Some(pred) = obligation.predicate.as_trait_clause()
1335 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1336 {
1337 obligation.cause.span = impl_.self_ty.span;
1338 }
1339 if let Some(pred) = obligation.predicate.as_projection_clause()
1340 && pred.skip_binder().self_ty() == trait_ref.self_ty()
1341 {
1342 obligation.cause.span = impl_.self_ty.span;
1343 }
1344 }
1345
1346 if tcx.is_conditionally_const(item.owner_id.def_id) {
1348 for (bound, _) in
1349 tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1350 {
1351 let bound = wfcx.normalize(
1352 item.span,
1353 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1354 bound,
1355 );
1356 wfcx.register_obligation(Obligation::new(
1357 tcx,
1358 ObligationCause::new(
1359 impl_.self_ty.span,
1360 wfcx.body_def_id,
1361 ObligationCauseCode::WellFormed(None),
1362 ),
1363 wfcx.param_env,
1364 bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1365 ))
1366 }
1367 }
1368
1369 debug!(?obligations);
1370 wfcx.register_obligations(obligations);
1371 }
1372 None => {
1373 let self_ty = tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1374 let self_ty = wfcx.deeply_normalize(
1375 item.span,
1376 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1377 Unnormalized::new_wip(self_ty),
1378 );
1379 wfcx.register_wf_obligation(
1380 impl_.self_ty.span,
1381 Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1382 self_ty.into(),
1383 );
1384 }
1385 }
1386
1387 check_where_clauses(wfcx, item.owner_id.def_id);
1388 Ok(())
1389 })
1390}
1391
1392{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_where_clauses",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1393u32),
::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))]
1394pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1395 let infcx = wfcx.infcx;
1396 let tcx = wfcx.tcx();
1397
1398 let gen_clauses = tcx.clauses_of(def_id.to_def_id());
1399 let generics = tcx.generics_of(def_id);
1400
1401 for param in &generics.own_params {
1408 if let Some(default) = param
1409 .default_value(tcx)
1410 .map(ty::EarlyBinder::instantiate_identity)
1411 .map(Unnormalized::skip_norm_wip)
1412 {
1413 if !default.has_param() {
1420 wfcx.register_wf_obligation(
1421 tcx.def_span(param.def_id),
1422 matches!(param.kind, GenericParamDefKind::Type { .. })
1423 .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1424 default.as_term().unwrap(),
1425 );
1426 } else {
1427 let GenericArgKind::Const(ct) = default.kind() else {
1430 continue;
1431 };
1432
1433 let ct_ty = match ct.kind() {
1434 ty::ConstKind::Infer(_)
1435 | ty::ConstKind::Placeholder(_)
1436 | ty::ConstKind::Bound(_, _) => unreachable!(),
1437 ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1438 ty::ConstKind::Value(cv) => cv.ty,
1439 ty::ConstKind::Alias(_, alias_const) => {
1440 alias_const.type_of(infcx.tcx).skip_norm_wip()
1441 }
1442 ty::ConstKind::Param(param_ct) => {
1443 param_ct.find_const_ty_from_env(wfcx.param_env)
1444 }
1445 };
1446
1447 let param_ty = tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip();
1448 if !ct_ty.has_param() && !param_ty.has_param() {
1449 let cause = traits::ObligationCause::new(
1450 tcx.def_span(param.def_id),
1451 wfcx.body_def_id,
1452 ObligationCauseCode::WellFormed(None),
1453 );
1454 wfcx.register_obligation(Obligation::new(
1455 tcx,
1456 cause,
1457 wfcx.param_env,
1458 ty::ClauseKind::ConstArgHasType(ct, param_ty),
1459 ));
1460 }
1461 }
1462 }
1463 }
1464
1465 let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1474 if param.index >= generics.parent_count as u32
1475 && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity).map(Unnormalized::skip_norm_wip)
1477 && !default.has_param()
1479 {
1480 return default;
1482 }
1483 tcx.mk_param_from_def(param)
1484 });
1485
1486 let default_obligations = gen_clauses
1488 .clauses
1489 .iter()
1490 .flat_map(|&(clause, sp)| {
1491 #[derive(Default)]
1492 struct CountParams {
1493 params: FxHashSet<u32>,
1494 }
1495 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1496 type Result = ControlFlow<()>;
1497 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1498 if let ty::Param(param) = t.kind() {
1499 self.params.insert(param.index);
1500 }
1501 t.super_visit_with(self)
1502 }
1503
1504 fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1505 ControlFlow::Break(())
1506 }
1507
1508 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1509 if let ty::ConstKind::Param(param) = c.kind() {
1510 self.params.insert(param.index);
1511 }
1512 c.super_visit_with(self)
1513 }
1514 }
1515 let mut param_count = CountParams::default();
1516 let has_region = clause.visit_with(&mut param_count).is_break();
1517 let instantiated_clause = ty::EarlyBinder::bind(tcx, clause).instantiate(tcx, args);
1518 if instantiated_clause.skip_normalization().has_non_region_param()
1521 || param_count.params.len() > 1
1522 || has_region
1523 {
1524 None
1525 } else if gen_clauses
1526 .clauses
1527 .iter()
1528 .any(|&(p, _)| Unnormalized::new_wip(p) == instantiated_clause)
1529 {
1530 None
1532 } else {
1533 Some((instantiated_clause, sp))
1534 }
1535 })
1536 .map(|(clause, sp)| {
1537 let clause = wfcx.normalize(sp, None, clause);
1547 let cause = traits::ObligationCause::new(
1548 sp,
1549 wfcx.body_def_id,
1550 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1551 );
1552 Obligation::new(tcx, cause, wfcx.param_env, clause)
1553 });
1554
1555 let gen_clauses = gen_clauses.instantiate_identity(tcx);
1556
1557 let assoc_const_obligations: Vec<_> = gen_clauses
1558 .clauses
1559 .iter()
1560 .copied()
1561 .zip(gen_clauses.spans.iter().copied())
1562 .filter_map(|(clause, sp)| {
1563 let clause = clause.skip_norm_wip();
1564 let proj = clause.as_projection_clause()?;
1565 let pred_binder = proj
1566 .map_bound(|pred| {
1567 pred.term.as_const().map(|ct| {
1568 let assoc_const_ty =
1569 pred.projection_term.expect_ct().type_of(tcx).skip_norm_wip();
1570 ty::ClauseKind::ConstArgHasType(ct, assoc_const_ty)
1571 })
1572 })
1573 .transpose();
1574 pred_binder.map(|pred_binder| {
1575 let cause = traits::ObligationCause::new(
1576 sp,
1577 wfcx.body_def_id,
1578 ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1579 );
1580 Obligation::new(tcx, cause, wfcx.param_env, pred_binder)
1581 })
1582 })
1583 .collect();
1584
1585 assert_eq!(gen_clauses.clauses.len(), gen_clauses.spans.len());
1586 let wf_obligations = gen_clauses.into_iter().flat_map(|(p, sp)| {
1587 traits::wf::clause_obligations(
1588 infcx,
1589 wfcx.param_env,
1590 wfcx.body_def_id,
1591 p.skip_norm_wip(),
1592 sp,
1593 )
1594 });
1595 let obligations: Vec<_> =
1596 wf_obligations.chain(default_obligations).chain(assoc_const_obligations).collect();
1597 wfcx.register_obligations(obligations);
1598}
1599
1600{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_fn_or_method",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1600u32),
::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))]
1601fn check_fn_or_method<'tcx>(
1602 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1603 sig: ty::PolyFnSig<'tcx>,
1604 hir_decl: &hir::FnDecl<'_>,
1605 def_id: LocalDefId,
1606) {
1607 let tcx = wfcx.tcx();
1608 let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1609
1610 let arg_span =
1616 |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1617
1618 sig.inputs_and_output =
1619 tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1620 wfcx.deeply_normalize(
1621 arg_span(idx),
1622 Some(WellFormedLoc::Param {
1623 function: def_id,
1624 param_idx: idx,
1627 }),
1628 Unnormalized::new_wip(ty),
1629 )
1630 }));
1631
1632 for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1633 wfcx.register_wf_obligation(
1634 arg_span(idx),
1635 Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1636 ty.into(),
1637 );
1638 }
1639
1640 check_where_clauses(wfcx, def_id);
1641
1642 if sig.abi() == ExternAbi::RustCall {
1643 let span = tcx.def_span(def_id);
1644 let has_implicit_self = hir_decl.implicit_self().has_implicit_self();
1645 let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1646 if let Some(ty) = inputs.next() {
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::Tuple, span),
1653 );
1654 wfcx.register_bound(
1655 ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1656 wfcx.param_env,
1657 *ty,
1658 tcx.require_lang_item(LangItem::Sized, span),
1659 );
1660 } else {
1661 tcx.dcx().span_err(
1662 hir_decl.inputs.last().map_or(span, |input| input.span),
1663 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1664 );
1665 }
1666 if inputs.next().is_some() {
1668 tcx.dcx().span_err(
1669 hir_decl.inputs.last().map_or(span, |input| input.span),
1670 "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1671 );
1672 }
1673 }
1674
1675 if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1677 let span = match hir_decl.output {
1678 hir::FnRetTy::Return(ty) => ty.span,
1679 hir::FnRetTy::DefaultReturn(_) => body.value.span,
1680 };
1681
1682 wfcx.register_bound(
1683 ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1684 wfcx.param_env,
1685 sig.output(),
1686 tcx.require_lang_item(LangItem::Sized, span),
1687 );
1688 }
1689}
1690
1691#[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)]
1693enum ArbitrarySelfTypesLevel {
1694 Basic, WithPointers, }
1697
1698{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_method_receiver",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1698u32),
::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 compiler/rustc_hir_analysis/src/check/wfcheck.rs:1718",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1718u32),
::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))]
1699fn check_method_receiver<'tcx>(
1700 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1701 fn_sig: &hir::FnSig<'_>,
1702 method: ty::AssocItem,
1703 self_ty: Ty<'tcx>,
1704) -> Result<(), ErrorGuaranteed> {
1705 let tcx = wfcx.tcx();
1706
1707 if !method.is_method() {
1708 return Ok(());
1709 }
1710
1711 let span = fn_sig.decl.inputs[0].span;
1712 let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1713
1714 let sig = tcx.fn_sig(method.def_id).instantiate_identity().skip_norm_wip();
1715 let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1716 let sig = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(sig));
1717
1718 debug!("check_method_receiver: sig={:?}", sig);
1719
1720 let self_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(self_ty));
1721
1722 let receiver_ty = sig.inputs()[0];
1723 let receiver_ty = wfcx.normalize(DUMMY_SP, loc, Unnormalized::new_wip(receiver_ty));
1724
1725 receiver_ty.error_reported()?;
1728
1729 let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1730 Some(ArbitrarySelfTypesLevel::WithPointers)
1731 } else if tcx.features().arbitrary_self_types() {
1732 Some(ArbitrarySelfTypesLevel::Basic)
1733 } else {
1734 None
1735 };
1736 let generics = tcx.generics_of(method.def_id);
1737
1738 let receiver_validity =
1739 receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1740 if let Err(receiver_validity_err) = receiver_validity {
1741 return Err(match arbitrary_self_types_level {
1742 None if receiver_is_valid(
1746 wfcx,
1747 span,
1748 receiver_ty,
1749 self_ty,
1750 Some(ArbitrarySelfTypesLevel::Basic),
1751 generics,
1752 )
1753 .is_ok() =>
1754 {
1755 feature_err(
1757 &tcx.sess,
1758 sym::arbitrary_self_types,
1759 span,
1760 format!(
1761 "`{receiver_ty}` cannot be used as the type of `self` without \
1762 the `arbitrary_self_types` feature",
1763 ),
1764 )
1765 .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>`"))
1766 .emit()
1767 }
1768 None | Some(ArbitrarySelfTypesLevel::Basic)
1769 if receiver_is_valid(
1770 wfcx,
1771 span,
1772 receiver_ty,
1773 self_ty,
1774 Some(ArbitrarySelfTypesLevel::WithPointers),
1775 generics,
1776 )
1777 .is_ok() =>
1778 {
1779 feature_err(
1781 &tcx.sess,
1782 sym::arbitrary_self_types_pointers,
1783 span,
1784 format!(
1785 "`{receiver_ty}` cannot be used as the type of `self` without \
1786 the `arbitrary_self_types_pointers` feature",
1787 ),
1788 )
1789 .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>`"))
1790 .emit()
1791 }
1792 _ =>
1793 {
1795 match receiver_validity_err {
1796 ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1797 let adt_def =
1798 receiver_ty.builtin_deref(false).unwrap_or(receiver_ty).ty_adt_def();
1799
1800 let hint = match adt_def {
1801 Some(adt) => {
1802 if tcx.is_lang_item(adt.did(), LangItem::NonNull) {
1803 Some(InvalidReceiverTyHint::NonNull)
1804 } else {
1805 match tcx.get_diagnostic_name(adt.did()) {
1806 Some(sym::RcWeak | sym::ArcWeak) => {
1807 Some(InvalidReceiverTyHint::Weak)
1808 }
1809 _ => None,
1810 }
1811 }
1812 }
1813 _ => None,
1814 };
1815
1816 tcx.dcx().emit_err(diagnostics::InvalidReceiverTy {
1817 span,
1818 receiver_ty,
1819 hint,
1820 })
1821 }
1822 ReceiverValidityError::DoesNotDeref => {
1823 tcx.dcx().emit_err(diagnostics::InvalidReceiverTyNoArbitrarySelfTypes {
1824 span,
1825 receiver_ty,
1826 })
1827 }
1828 ReceiverValidityError::MethodGenericParamUsed => tcx
1829 .dcx()
1830 .emit_err(diagnostics::InvalidGenericReceiverTy { span, receiver_ty }),
1831 }
1832 }
1833 });
1834 }
1835 Ok(())
1836}
1837
1838enum ReceiverValidityError {
1842 DoesNotDeref,
1845 MethodGenericParamUsed,
1847}
1848
1849fn confirm_type_is_not_a_method_generic_param(
1852 ty: Ty<'_>,
1853 method_generics: &ty::Generics,
1854) -> Result<(), ReceiverValidityError> {
1855 if let ty::Param(param) = ty.kind() {
1856 if (param.index as usize) >= method_generics.parent_count {
1857 return Err(ReceiverValidityError::MethodGenericParamUsed);
1858 }
1859 }
1860 Ok(())
1861}
1862
1863fn receiver_is_valid<'tcx>(
1873 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1874 span: Span,
1875 receiver_ty: Ty<'tcx>,
1876 self_ty: Ty<'tcx>,
1877 arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1878 method_generics: &ty::Generics,
1879) -> Result<(), ReceiverValidityError> {
1880 let infcx = wfcx.infcx;
1881 let tcx = wfcx.tcx();
1882 let cause =
1883 ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1884
1885 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1887 let ocx = ObligationCtxt::new(wfcx.infcx);
1888 ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1889 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
1890 Ok(())
1891 } else {
1892 Err(NoSolution)
1893 }
1894 }) {
1895 return Ok(());
1896 }
1897
1898 confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1899
1900 let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1901
1902 if arbitrary_self_types_enabled.is_some() {
1906 autoderef = autoderef.use_receiver_trait();
1907 }
1908
1909 if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1911 autoderef = autoderef.include_raw_pointers();
1912 }
1913
1914 while let Some((potential_self_ty, _)) = autoderef.next() {
1916 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1916",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1916u32),
::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!(
1917 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1918 potential_self_ty, self_ty
1919 );
1920
1921 confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1922
1923 if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1926 let ocx = ObligationCtxt::new(wfcx.infcx);
1927 ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1928 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
1929 Ok(())
1930 } else {
1931 Err(NoSolution)
1932 }
1933 }) {
1934 wfcx.register_obligations(autoderef.into_obligations());
1935 return Ok(());
1936 }
1937
1938 if arbitrary_self_types_enabled.is_none() {
1941 let legacy_receiver_trait_def_id =
1942 tcx.require_lang_item(LangItem::LegacyReceiver, span);
1943 if !legacy_receiver_is_implemented(
1944 wfcx,
1945 legacy_receiver_trait_def_id,
1946 cause.clone(),
1947 potential_self_ty,
1948 ) {
1949 break;
1951 }
1952
1953 wfcx.register_bound(
1955 cause.clone(),
1956 wfcx.param_env,
1957 potential_self_ty,
1958 legacy_receiver_trait_def_id,
1959 );
1960 }
1961 }
1962
1963 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1963",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1963u32),
::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);
1964 Err(ReceiverValidityError::DoesNotDeref)
1965}
1966
1967fn legacy_receiver_is_implemented<'tcx>(
1968 wfcx: &WfCheckingCtxt<'_, 'tcx>,
1969 legacy_receiver_trait_def_id: DefId,
1970 cause: ObligationCause<'tcx>,
1971 receiver_ty: Ty<'tcx>,
1972) -> bool {
1973 let tcx = wfcx.tcx();
1974 let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1975
1976 let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1977
1978 if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1979 true
1980 } else {
1981 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/check/wfcheck.rs:1981",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(1981u32),
::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!(
1982 "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1983 receiver_ty
1984 );
1985 false
1986 }
1987}
1988
1989pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1990 match tcx.def_kind(def_id) {
1991 DefKind::Enum | DefKind::Struct | DefKind::Union => {
1992 }
1994 kind => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
format_args!("cannot compute the variances of {0:?}", kind))span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1995 }
1996
1997 let ty_clauses = tcx.clauses_of(def_id);
1998 {
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);
1999 let variances = tcx.variances_of(def_id);
2000
2001 let mut constrained_parameters: FxHashSet<_> = variances
2002 .iter()
2003 .enumerate()
2004 .filter(|&(_, &variance)| variance != ty::Bivariant)
2005 .map(|(index, _)| Parameter(index as u32))
2006 .collect();
2007
2008 identify_constrained_generic_params(tcx, ty_clauses, None, &mut constrained_parameters);
2009
2010 let explicitly_bounded_params = LazyCell::new(|| {
2012 let icx = crate::collect::ItemCtxt::new(tcx, def_id);
2013 tcx.hir_node_by_def_id(def_id)
2014 .generics()
2015 .unwrap()
2016 .predicates
2017 .iter()
2018 .filter_map(|predicate| match predicate.kind {
2019 hir::WherePredicateKind::BoundPredicate(predicate) => {
2020 match icx.lower_ty(predicate.bounded_ty).kind() {
2021 ty::Param(data) => Some(Parameter(data.index)),
2022 _ => None,
2023 }
2024 }
2025 _ => None,
2026 })
2027 .collect::<FxHashSet<_>>()
2028 });
2029
2030 for (index, _) in variances.iter().enumerate() {
2031 let parameter = Parameter(index as u32);
2032
2033 if constrained_parameters.contains(¶meter) {
2034 continue;
2035 }
2036
2037 let node = tcx.hir_node_by_def_id(def_id);
2038 let item = node.expect_item();
2039 let hir_generics = node.generics().unwrap();
2040 let hir_param = &hir_generics.params[index];
2041
2042 let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
2043
2044 if ty_param.def_id != hir_param.def_id.into() {
2045 tcx.dcx().span_delayed_bug(
2053 hir_param.span,
2054 "hir generics and ty generics in different order",
2055 );
2056 continue;
2057 }
2058
2059 if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
2061 .type_of(def_id)
2062 .instantiate_identity()
2063 .skip_norm_wip()
2064 .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
2065 {
2066 continue;
2067 }
2068
2069 match hir_param.name {
2070 hir::ParamName::Error(_) => {
2071 }
2074 _ => {
2075 let has_explicit_bounds = explicitly_bounded_params.contains(¶meter);
2076 report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2077 }
2078 }
2079 }
2080}
2081
2082struct HasErrorDeep<'tcx> {
2084 tcx: TyCtxt<'tcx>,
2085 seen: FxHashSet<DefId>,
2086}
2087impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2088 type Result = ControlFlow<ErrorGuaranteed>;
2089
2090 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2091 match *ty.kind() {
2092 ty::Adt(def, _) => {
2093 if self.seen.insert(def.did()) {
2094 for field in def.all_fields() {
2095 self.tcx
2096 .type_of(field.did)
2097 .instantiate_identity()
2098 .skip_norm_wip()
2099 .visit_with(self)?;
2100 }
2101 }
2102 }
2103 ty::Error(guar) => return ControlFlow::Break(guar),
2104 _ => {}
2105 }
2106 ty.super_visit_with(self)
2107 }
2108
2109 fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2110 if let Err(guar) = r.error_reported() {
2111 ControlFlow::Break(guar)
2112 } else {
2113 ControlFlow::Continue(())
2114 }
2115 }
2116
2117 fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2118 if let Err(guar) = c.error_reported() {
2119 ControlFlow::Break(guar)
2120 } else {
2121 ControlFlow::Continue(())
2122 }
2123 }
2124}
2125
2126fn report_bivariance<'tcx>(
2127 tcx: TyCtxt<'tcx>,
2128 param: &'tcx hir::GenericParam<'tcx>,
2129 has_explicit_bounds: bool,
2130 item: &'tcx hir::Item<'tcx>,
2131) -> ErrorGuaranteed {
2132 let param_name = param.name.ident();
2133
2134 let help = match item.kind {
2135 ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2136 if let Some(def_id) = tcx.lang_items().phantom_data() {
2137 diagnostics::UnusedGenericParameterHelp::Adt {
2138 param_name,
2139 phantom_data: tcx.def_path_str(def_id),
2140 }
2141 } else {
2142 diagnostics::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2143 }
2144 }
2145 item_kind => ::rustc_middle::util::bug::bug_fmt(format_args!("report_bivariance: unexpected item kind: {0:?}",
item_kind))bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2146 };
2147
2148 let mut usage_spans = ::alloc::vec::Vec::new()vec![];
2149 intravisit::walk_item(
2150 &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2151 item,
2152 );
2153
2154 if !usage_spans.is_empty() {
2155 let item_def_id = item.owner_id.to_def_id();
2159 let is_probably_cyclical =
2160 IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2161 .visit_def(item_def_id)
2162 .is_break();
2163 if is_probably_cyclical {
2172 return tcx.dcx().emit_err(diagnostics::RecursiveGenericParameter {
2173 spans: usage_spans,
2174 param_span: param.span,
2175 param_name,
2176 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2177 help,
2178 note: (),
2179 });
2180 }
2181 }
2182
2183 let const_param_help =
2184 #[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);
2185
2186 let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2187 span: param.span,
2188 param_name,
2189 param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2190 usage_spans,
2191 help,
2192 const_param_help,
2193 });
2194 diag.code(E0392);
2195 if item.kind.recovered() {
2196 diag.delay_as_bug()
2198 } else {
2199 diag.emit()
2200 }
2201}
2202
2203struct IsProbablyCyclical<'tcx> {
2209 tcx: TyCtxt<'tcx>,
2210 item_def_id: DefId,
2211 seen: FxHashSet<DefId>,
2212}
2213
2214impl<'tcx> IsProbablyCyclical<'tcx> {
2215 fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2216 match self.tcx.def_kind(def_id) {
2217 DefKind::Struct | DefKind::Enum | DefKind::Union => {
2218 self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2219 self.tcx
2220 .type_of(field.did)
2221 .instantiate_identity()
2222 .skip_norm_wip()
2223 .visit_with(self)
2224 })
2225 }
2226 _ => ControlFlow::Continue(()),
2227 }
2228 }
2229}
2230
2231impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2232 type Result = ControlFlow<(), ()>;
2233
2234 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2235 if let Some(adt_def) = ty.ty_adt_def() {
2236 if adt_def.did() == self.item_def_id {
2237 return ControlFlow::Break(());
2238 }
2239 if self.seen.insert(adt_def.did()) {
2240 self.visit_def(adt_def.did())?;
2241 }
2242 }
2243 ty.super_visit_with(self)
2244 }
2245}
2246
2247struct CollectUsageSpans<'a> {
2252 spans: &'a mut Vec<Span>,
2253 param_def_id: DefId,
2254}
2255
2256impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2257 type Result = ();
2258
2259 fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2260 }
2262
2263 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2264 if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2265 if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2266 && def_id == self.param_def_id
2267 {
2268 self.spans.push(t.span);
2269 return;
2270 } else if let Res::SelfTyAlias { .. } = qpath.res {
2271 self.spans.push(t.span);
2272 return;
2273 }
2274 }
2275 intravisit::walk_ty(self, t);
2276 }
2277}
2278
2279impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2280 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_false_global_bounds",
"rustc_hir_analysis::check::wfcheck",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2282u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::wfcheck"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_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))]
2283 fn check_false_global_bounds(&mut self) {
2284 let tcx = self.ocx.infcx.tcx;
2285 let mut span = tcx.def_span(self.body_def_id);
2286 let empty_env = ty::ParamEnv::empty();
2287
2288 let clauses_with_span = tcx.clauses_of(self.body_def_id).clauses.iter().copied();
2289 let implied_obligations = traits::elaborate(tcx, clauses_with_span);
2291
2292 for (clause, obligation_span) in implied_obligations {
2293 match clause.kind().skip_binder() {
2294 ty::ClauseKind::WellFormed(..)
2298 | ty::ClauseKind::UnstableFeature(..) => continue,
2300 _ => {}
2301 }
2302
2303 if clause.is_global() && !clause.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2305 let clause = self.normalize(span, None, Unnormalized::new_wip(clause));
2306
2307 let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2309 if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2310 span = predicates
2311 .iter()
2312 .find(|pred| pred.span.contains(obligation_span))
2314 .map(|pred| pred.span)
2315 .unwrap_or(obligation_span);
2316 }
2317
2318 let obligation = Obligation::new(
2319 tcx,
2320 traits::ObligationCause::new(
2321 span,
2322 self.body_def_id,
2323 ObligationCauseCode::TrivialBound,
2324 ),
2325 empty_env,
2326 clause,
2327 );
2328 self.ocx.register_obligation(obligation);
2329 }
2330 }
2331 }
2332
2333 {}
#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2333u32),
::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 constraints =
match validate(self.tcx(), &body.constraints) {
Ok(()) => body.constraints,
Err(_guar) =>
ty::region_constraint::RegionConstraint::And(Box::new([])),
};
self.infcx.register_solver_region_constraint(constraints);
for forall in body.foralls {
self.check_test_binder_forall(forall);
}
for exists in body.exists {
self.check_test_binder_exists(exists);
}
fn validate<'tcx>(tcx: TyCtxt<'tcx>,
constraint: &SolverRegionConstraint<'tcx>)
-> Result<(), ErrorGuaranteed> {
match constraint {
ty::region_constraint::RegionConstraint::Ambiguity(_) =>
Ok(()),
ty::region_constraint::RegionConstraint::RegionOutlives(..)
=> Ok(()),
ty::region_constraint::RegionConstraint::AliasTyOutlivesViaEnv(..)
=> Ok(()),
ty::region_constraint::RegionConstraint::PlaceholderTyOutlives(ty,
_, span) => {
if let ty::Placeholder(_) | ty::Param(_) = ty.kind() {
Ok(())
} 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))
}));
Err(err.emit())
}
}
ty::region_constraint::RegionConstraint::And(constraints) =>
{
let mut res = Ok(());
for constraint in constraints {
res = res.and(validate(tcx, constraint));
}
res
}
ty::region_constraint::RegionConstraint::Or(constraints) =>
{
let mut res = Ok(());
for constraint in constraints {
res = res.and(validate(tcx, constraint));
}
res
}
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2334 pub(super) fn check_test_binder_body(&self, body: TestBinderBody<'tcx>) {
2335 let constraints = match validate(self.tcx(), &body.constraints) {
2336 Ok(()) => body.constraints,
2337 Err(_guar) => ty::region_constraint::RegionConstraint::And(Box::new([])),
2338 };
2339
2340 self.infcx.register_solver_region_constraint(constraints);
2341
2342 for forall in body.foralls {
2343 self.check_test_binder_forall(forall);
2344 }
2345 for exists in body.exists {
2346 self.check_test_binder_exists(exists);
2347 }
2348
2349 fn validate<'tcx>(
2350 tcx: TyCtxt<'tcx>,
2351 constraint: &SolverRegionConstraint<'tcx>,
2352 ) -> Result<(), ErrorGuaranteed> {
2353 match constraint {
2354 ty::region_constraint::RegionConstraint::Ambiguity(_) => Ok(()),
2355 ty::region_constraint::RegionConstraint::RegionOutlives(..) => Ok(()),
2356 ty::region_constraint::RegionConstraint::AliasTyOutlivesViaEnv(..) => Ok(()),
2357 ty::region_constraint::RegionConstraint::PlaceholderTyOutlives(ty, _, span) => {
2358 if let ty::Placeholder(_) | ty::Param(_) = ty.kind() {
2361 Ok(())
2362 } else {
2363 let mut err = tcx.dcx().struct_span_err(
2364 *span,
2365 "the lhs of a ty outlives must be a placeholder",
2366 );
2367 err.note(format!("it is a {ty}"));
2368 err.note(format!("and here it is `Debug`ged :3 {ty:?}"));
2369 Err(err.emit())
2370 }
2371 }
2372 ty::region_constraint::RegionConstraint::And(constraints) => {
2373 let mut res = Ok(());
2374 for constraint in constraints {
2375 res = res.and(validate(tcx, constraint));
2376 }
2377 res
2378 }
2379 ty::region_constraint::RegionConstraint::Or(constraints) => {
2380 let mut res = Ok(());
2381 for constraint in constraints {
2382 res = res.and(validate(tcx, constraint));
2383 }
2384 res
2385 }
2386 }
2387 }
2388 }
2389
2390 {}
#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2390u32),
::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(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_span(forall.span);
if let Some(assert_on_exit) = forall.assert_on_exit {
self.check_test_binder_region_constraints(forall.span,
&assert_on_exit.clone().canonical_form(),
&constraint.clone().canonical_form());
}
self.infcx.overwrite_solver_region_constraint(constraint);
});
}
}
}#[instrument(level = "debug", skip(self))]
2391 fn check_test_binder_forall(&self, forall: TestBinderForall<'tcx>) {
2392 self.infcx.enter_forall(forall.binder, |body| {
2393 let u = self.infcx.universe();
2394 let mut builder = TransitiveRelationBuilder::default();
2395 for &(r1, r2) in &body.region_outlives {
2396 builder.add(r1, r2);
2397 }
2398 let assumptions =
2399 ty::region_constraint::Assumptions::new(body.type_outlives, builder.freeze());
2400 self.infcx.insert_placeholder_assumptions(u, Some(assumptions));
2401 self.check_test_binder_body(body.value);
2402 let solver_region_constraint = self.infcx.get_solver_region_constraint();
2403 let constraint = ty::region_constraint::eagerly_handle_placeholders_in_universe(
2404 self.infcx,
2405 solver_region_constraint.without_spans(),
2406 u,
2407 )
2408 .with_span(forall.span);
2409 if let Some(assert_on_exit) = forall.assert_on_exit {
2410 self.check_test_binder_region_constraints(
2411 forall.span,
2412 &assert_on_exit.clone().canonical_form(),
2413 &constraint.clone().canonical_form(),
2414 );
2415 }
2416 self.infcx.overwrite_solver_region_constraint(constraint);
2417 });
2418 }
2419
2420 {}
#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2420u32),
::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 span_of<'tcx>(constraint: &SolverRegionConstraint<'tcx>)
-> Option<Span> {
match constraint {
SolverRegionConstraint::Ambiguity(sp) |
SolverRegionConstraint::RegionOutlives(_, _, sp) |
SolverRegionConstraint::AliasTyOutlivesViaEnv(_, sp) |
ty::region_constraint::RegionConstraint::PlaceholderTyOutlives(_,
_, sp) => {
Some(*sp)
}
SolverRegionConstraint::And(constraints) |
SolverRegionConstraint::Or(constraints) =>
constraints.iter().map(span_of).flatten().fold(None,
|l, r| Some(l.map_or(r, |l| l.to(r)))),
}
}
fn err<'tcx>(tcx: TyCtxt<'tcx>, fallback_span: Span,
expected: &SolverRegionConstraint<'tcx>,
actual: &SolverRegionConstraint<'tcx>) {
let mut err =
tcx.dcx().struct_span_err(span_of(expected).unwrap_or(fallback_span),
"forall expect clause failed");
if let Some(actual_span) = span_of(actual) {
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();
}
match (expected, actual) {
(SolverRegionConstraint::And(expected_arr),
SolverRegionConstraint::And(actual_arr)) |
(SolverRegionConstraint::Or(expected_arr),
SolverRegionConstraint::Or(actual_arr)) => {
if expected_arr.len() != actual_arr.len() {
err(self.tcx(), fallback_span, expected, actual);
} else {
for (expected, actual) in
expected_arr.iter().zip(actual_arr) {
self.check_test_binder_region_constraints(fallback_span,
expected, actual);
}
}
}
_ if
expected.clone().without_spans() !=
actual.clone().without_spans() => {
err(self.tcx(), fallback_span, expected, actual);
}
_ => (),
}
}
}
}#[instrument(level = "debug", skip(self))]
2421 fn check_test_binder_region_constraints(
2422 &self,
2423 fallback_span: Span,
2424 expected: &SolverRegionConstraint<'tcx>,
2425 actual: &SolverRegionConstraint<'tcx>,
2426 ) {
2427 fn span_of<'tcx>(constraint: &SolverRegionConstraint<'tcx>) -> Option<Span> {
2428 match constraint {
2429 SolverRegionConstraint::Ambiguity(sp)
2430 | SolverRegionConstraint::RegionOutlives(_, _, sp)
2431 | SolverRegionConstraint::AliasTyOutlivesViaEnv(_, sp)
2432 | ty::region_constraint::RegionConstraint::PlaceholderTyOutlives(_, _, sp) => {
2433 Some(*sp)
2434 }
2435 SolverRegionConstraint::And(constraints)
2436 | SolverRegionConstraint::Or(constraints) => constraints
2437 .iter()
2438 .map(span_of)
2439 .flatten()
2440 .fold(None, |l, r| Some(l.map_or(r, |l| l.to(r)))),
2441 }
2442 }
2443 fn err<'tcx>(
2444 tcx: TyCtxt<'tcx>,
2445 fallback_span: Span,
2446 expected: &SolverRegionConstraint<'tcx>,
2447 actual: &SolverRegionConstraint<'tcx>,
2448 ) {
2449 let mut err = tcx.dcx().struct_span_err(
2450 span_of(expected).unwrap_or(fallback_span),
2451 "forall expect clause failed",
2452 );
2453 if let Some(actual_span) = span_of(actual) {
2454 err.span_note(actual_span, "constraint from here");
2455 }
2456 err.note(format!("expected: {expected:?}"));
2457 err.note(format!("actual: {actual:?}"));
2458 err.emit();
2459 }
2460 match (expected, actual) {
2461 (
2462 SolverRegionConstraint::And(expected_arr),
2463 SolverRegionConstraint::And(actual_arr),
2464 )
2465 | (SolverRegionConstraint::Or(expected_arr), SolverRegionConstraint::Or(actual_arr)) => {
2466 if expected_arr.len() != actual_arr.len() {
2467 err(self.tcx(), fallback_span, expected, actual);
2468 } else {
2469 for (expected, actual) in expected_arr.iter().zip(actual_arr) {
2470 self.check_test_binder_region_constraints(fallback_span, expected, actual);
2471 }
2472 }
2473 }
2474 _ if expected.clone().without_spans() != actual.clone().without_spans() => {
2475 err(self.tcx(), fallback_span, expected, actual);
2476 }
2477 _ => (),
2478 }
2479 }
2480
2481 {}
#[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("compiler/rustc_hir_analysis/src/check/wfcheck.rs"),
::tracing_core::__macro_support::Option::Some(2481u32),
::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))]
2482 fn check_test_binder_exists(&self, exists: TestBinderExists<'tcx>) {
2483 let body = self.infcx.instantiate_binder_with_fresh_vars(
2484 exists.span,
2485 BoundRegionConversionTime::HigherRankedType,
2486 exists.binder,
2487 );
2488 self.check_test_binder_body(body);
2489 }
2490}
2491
2492pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2493 let items = tcx.hir_crate_items(());
2494 let res =
2495 items
2496 .par_items(|item| tcx.ensure_result().check_well_formed(item.owner_id.def_id))
2497 .and(
2498 items.par_impl_items(|item| {
2499 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2500 }),
2501 )
2502 .and(items.par_trait_items(|item| {
2503 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2504 }))
2505 .and(items.par_foreign_items(|item| {
2506 tcx.ensure_result().check_well_formed(item.owner_id.def_id)
2507 }))
2508 .and(items.par_nested_bodies(|item| tcx.ensure_result().check_well_formed(item)))
2509 .and(items.par_opaques(|item| tcx.ensure_result().check_well_formed(item)));
2510
2511 super::entry::check_for_entry_fn(tcx)?;
2512
2513 res
2514}
2515
2516fn lint_redundant_lifetimes<'tcx>(
2517 tcx: TyCtxt<'tcx>,
2518 owner_id: LocalDefId,
2519 outlives_env: &OutlivesEnvironment<'tcx>,
2520) {
2521 let def_kind = tcx.def_kind(owner_id);
2522 match def_kind {
2523 DefKind::Struct
2524 | DefKind::Union
2525 | DefKind::Enum
2526 | DefKind::Trait
2527 | DefKind::TraitAlias
2528 | DefKind::Fn
2529 | DefKind::Const { .. }
2530 | DefKind::Impl { of_trait: _ }
2531 | DefKind::TestBinderConstraints => {
2532 }
2534 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
2535 if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2536 return;
2541 }
2542 }
2543 DefKind::Mod
2544 | DefKind::Variant
2545 | DefKind::TyAlias
2546 | DefKind::ForeignTy
2547 | DefKind::TyParam
2548 | DefKind::ConstParam
2549 | DefKind::Static { .. }
2550 | DefKind::Ctor(_, _)
2551 | DefKind::Macro(_)
2552 | DefKind::ExternCrate
2553 | DefKind::Use
2554 | DefKind::ForeignMod
2555 | DefKind::AnonConst
2556 | DefKind::OpaqueTy
2557 | DefKind::Field
2558 | DefKind::LifetimeParam
2559 | DefKind::GlobalAsm
2560 | DefKind::Closure
2561 | DefKind::SyntheticCoroutineBody => return,
2562 }
2563
2564 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];
2573 lifetimes.extend(
2574 ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2575 );
2576 if #[allow(non_exhaustive_omitted_patterns)] match def_kind {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2578 for (idx, var) in tcx
2579 .fn_sig(owner_id)
2580 .instantiate_identity()
2581 .skip_norm_wip()
2582 .bound_vars()
2583 .iter()
2584 .enumerate()
2585 {
2586 let ty::BoundVariableKind::Region(kind) = var else { continue };
2587 let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2588 lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2589 }
2590 }
2591 lifetimes.retain(|candidate| candidate.is_named(tcx));
2592
2593 let mut shadowed = FxHashSet::default();
2597
2598 for (idx, &candidate) in lifetimes.iter().enumerate() {
2599 if shadowed.contains(&candidate) {
2604 continue;
2605 }
2606
2607 for &victim in &lifetimes[(idx + 1)..] {
2608 let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2616 continue;
2617 };
2618
2619 if tcx.parent(def_id) != owner_id.to_def_id() {
2624 continue;
2625 }
2626
2627 if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2629 && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2630 {
2631 shadowed.insert(victim);
2632 tcx.emit_node_span_lint(
2633 REDUNDANT_LIFETIMES,
2634 tcx.local_def_id_to_hir_id(def_id.expect_local()),
2635 tcx.def_span(def_id),
2636 RedundantLifetimeArgsLint { candidate, victim },
2637 );
2638 }
2639 }
2640 }
2641}
2642
2643#[derive(const _: () =
{
impl<'_sess, 'tcx, G> rustc_errors::Diagnostic<'_sess, G> for
RedundantLifetimeArgsLint<'tcx> where
G: rustc_errors::EmissionGuarantee {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
RedundantLifetimeArgsLint {
victim: __binding_0, candidate: __binding_1 } => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unnecessary lifetime parameter `{$victim}`")));
diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")));
;
diag.arg("victim", __binding_0);
diag.arg("candidate", __binding_1);
diag
}
}
}
}
};Diagnostic)]
2644#[diag("unnecessary lifetime parameter `{$victim}`")]
2645#[note("you can use the `{$candidate}` lifetime directly, in place of `{$victim}`")]
2646struct RedundantLifetimeArgsLint<'tcx> {
2647 victim: ty::Region<'tcx>,
2649 candidate: ty::Region<'tcx>,
2651}
2652
2653#[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),
}
}
}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_field3_finish(f,
"TestBinderBody", "foralls", &self.foralls, "exists",
&self.exists, "constraints", &&self.constraints)
}
}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 } => {
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)?,
}
}
})
}
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 } => {
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),
}
}
}
}
}
};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 } => {
{
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)]
2654pub(crate) struct TestBinderBody<'tcx> {
2655 pub foralls: Vec<TestBinderForall<'tcx>>,
2656 pub exists: Vec<TestBinderExists<'tcx>>,
2657 pub constraints: SolverRegionConstraint<'tcx>,
2658}
2659
2660#[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)]
2661pub(crate) struct TestBinderForall<'tcx> {
2662 pub span: Span,
2663 pub binder: ty::Binder<'tcx, WithWhereClauses<'tcx, TestBinderBody<'tcx>>>,
2664 pub assert_on_exit: Option<SolverRegionConstraint<'tcx>>,
2665}
2666
2667#[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)]
2668pub(crate) struct TestBinderExists<'tcx> {
2669 pub span: Span,
2670 pub binder: ty::Binder<'tcx, TestBinderBody<'tcx>>,
2671}
2672
2673#[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)]
2674pub(crate) struct WithWhereClauses<'tcx, T> {
2675 pub value: T,
2676
2677 pub type_outlives: Vec<ty::Binder<'tcx, ty::OutlivesClause<'tcx, Ty<'tcx>>>>,
2680 pub region_outlives: Vec<(ty::Region<'tcx>, ty::Region<'tcx>)>,
2681}