1use std::borrow::Cow;
4use std::path::PathBuf;
5use std::{debug_assert_matches, iter};
6
7use itertools::{EitherOrBoth, Itertools};
8use rustc_abi::ExternAbi;
9use rustc_data_structures::fx::FxHashSet;
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_errors::codes::*;
12use rustc_errors::{
13 Applicability, Diag, EmissionGuarantee, MultiSpan, Style, SuggestionStyle, pluralize,
14 struct_span_code_err,
15};
16use rustc_hir::def::{CtorOf, DefKind, Res};
17use rustc_hir::def_id::DefId;
18use rustc_hir::intravisit::{Visitor, VisitorExt};
19use rustc_hir::lang_items::LangItem;
20use rustc_hir::{
21 self as hir, AmbigArg, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node,
22 expr_needs_parens,
23};
24use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
25use rustc_infer::traits::ImplSource;
26use rustc_middle::middle::privacy::Level;
27use rustc_middle::traits::IsConstable;
28use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind};
29use rustc_middle::ty::error::TypeError;
30use rustc_middle::ty::print::{
31 PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _,
32 PrintTraitRefExt as _, with_forced_trimmed_paths, with_no_trimmed_paths,
33 with_types_for_suggestion,
34};
35use rustc_middle::ty::{
36 self, AdtKind, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder,
37 TypeSuperFoldable, TypeSuperVisitable, TypeVisitableExt, TypeVisitor, TypeckResults,
38 Unnormalized, Upcast, suggest_arbitrary_trait_bound, suggest_constraining_type_param,
39};
40use rustc_middle::{bug, span_bug};
41use rustc_span::def_id::LocalDefId;
42use rustc_span::{
43 BytePos, DUMMY_SP, DesugaringKind, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym,
44};
45use tracing::{debug, instrument};
46
47use super::{
48 DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode,
49 PredicateObligation,
50};
51use crate::diagnostics;
52use crate::error_reporting::TypeErrCtxt;
53use crate::infer::InferCtxtExt as _;
54use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
55use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt, SelectionContext};
56
57#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CoroutineInteriorOrUpvar {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CoroutineInteriorOrUpvar::Interior(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Interior", __self_0, &__self_1),
CoroutineInteriorOrUpvar::Upvar(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Upvar",
&__self_0),
}
}
}Debug)]
58pub enum CoroutineInteriorOrUpvar {
59 Interior(Span, Option<(Span, Option<Span>)>),
61 Upvar(Span),
63}
64
65#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::fmt::Debug for CoroutineData<'a, 'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "CoroutineData",
&&self.0)
}
}Debug)]
68struct CoroutineData<'a, 'tcx>(&'a TypeckResults<'tcx>);
69
70impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
71 fn try_get_upvar_span<F>(
75 &self,
76 infer_context: &InferCtxt<'tcx>,
77 coroutine_did: DefId,
78 ty_matches: F,
79 ) -> Option<CoroutineInteriorOrUpvar>
80 where
81 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
82 {
83 infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| {
84 upvars.iter().find_map(|(upvar_id, upvar)| {
85 let upvar_ty = self.0.node_type(*upvar_id);
86 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
87 ty_matches(ty::Binder::dummy(upvar_ty))
88 .then(|| CoroutineInteriorOrUpvar::Upvar(upvar.span))
89 })
90 })
91 }
92
93 fn get_from_await_ty<F>(
97 &self,
98 visitor: AwaitsVisitor,
99 tcx: TyCtxt<'tcx>,
100 ty_matches: F,
101 ) -> Option<Span>
102 where
103 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
104 {
105 visitor
106 .awaits
107 .into_iter()
108 .map(|id| tcx.hir_expect_expr(id))
109 .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
110 .map(|expr| expr.span)
111 }
112}
113
114fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
115 (
116 generics.tail_span_for_predicate_suggestion(),
117 {
let _guard =
::rustc_middle::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSuggestion);
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
generics.add_where_or_trailing_comma(), pred))
})
}with_types_for_suggestion!(format!("{} {}", generics.add_where_or_trailing_comma(), pred)),
118 )
119}
120
121pub fn suggest_restriction<'tcx, G: EmissionGuarantee>(
125 tcx: TyCtxt<'tcx>,
126 item_id: LocalDefId,
127 hir_generics: &hir::Generics<'tcx>,
128 msg: &str,
129 err: &mut Diag<'_, G>,
130 fn_sig: Option<&hir::FnSig<'_>>,
131 projection: Option<ty::AliasTy<'_>>,
132 trait_pred: ty::PolyTraitPredicate<'tcx>,
133 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
139) {
140 if hir_generics.where_clause_span.from_expansion()
141 || hir_generics.where_clause_span.desugaring_kind().is_some()
142 || projection.is_some_and(|projection| {
143 (tcx.is_impl_trait_in_trait(projection.kind.def_id())
144 && !tcx.features().return_type_notation())
145 || tcx
146 .lookup_stability(projection.kind.def_id())
147 .is_some_and(|stab| stab.is_unstable())
148 })
149 {
150 return;
151 }
152 let generics = tcx.generics_of(item_id);
153 if let Some((param, bound_str, fn_sig)) =
155 fn_sig.zip(projection).and_then(|(sig, p)| match *p.self_ty().kind() {
156 ty::Param(param) => {
158 let param_def = generics.type_param(param, tcx);
159 if param_def.kind.is_synthetic() {
160 let bound_str =
161 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
162 return Some((param_def, bound_str, sig));
163 }
164 None
165 }
166 _ => None,
167 })
168 {
169 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
170 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
171 tcx,
172 param,
173 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
174 .to_ty(tcx),
175 });
176 if !trait_pred.is_suggestable(tcx, false) {
177 return;
178 }
179 let mut ty_spans = ::alloc::vec::Vec::new()vec![];
187 for input in fn_sig.decl.inputs {
188 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
189 .visit_ty_unambig(input);
190 }
191 let type_param = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", type_param_name,
bound_str))
})format!("{type_param_name}: {bound_str}");
193
194 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[if let Some(span) = hir_generics.span_for_param_suggestion() {
(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", type_param))
}))
} else {
(hir_generics.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", type_param))
}))
},
predicate_constraint(hir_generics, trait_pred.upcast(tcx))]))vec![
195 if let Some(span) = hir_generics.span_for_param_suggestion() {
196 (span, format!(", {type_param}"))
197 } else {
198 (hir_generics.span, format!("<{type_param}>"))
199 },
200 predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
203 ];
204 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
205
206 err.multipart_suggestion(
209 "introduce a type parameter with a trait bound instead of using `impl Trait`",
210 sugg,
211 Applicability::MaybeIncorrect,
212 );
213 } else {
214 if !trait_pred.is_suggestable(tcx, false) {
215 return;
216 }
217 let (sp, suggestion) = match (
219 hir_generics
220 .params
221 .iter()
222 .find(|p| !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
hir::GenericParamKind::Type { synthetic: true, .. } => true,
_ => false,
}matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
223 super_traits,
224 ) {
225 (_, None) => predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
226 (None, Some((ident, []))) => (
227 ident.span.shrink_to_hi(),
228 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}",
trait_pred.print_modifiers_and_trait_path()))
})format!(": {}", trait_pred.print_modifiers_and_trait_path()),
229 ),
230 (_, Some((_, [.., bounds]))) => (
231 bounds.span().shrink_to_hi(),
232 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}",
trait_pred.print_modifiers_and_trait_path()))
})format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
233 ),
234 (Some(_), Some((_, []))) => (
235 hir_generics.span.shrink_to_hi(),
236 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}",
trait_pred.print_modifiers_and_trait_path()))
})format!(": {}", trait_pred.print_modifiers_and_trait_path()),
237 ),
238 };
239
240 err.span_suggestion_verbose(
241 sp,
242 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider further restricting {0}",
msg))
})format!("consider further restricting {msg}"),
243 suggestion,
244 Applicability::MachineApplicable,
245 );
246 }
247}
248
249struct PeeledRef<'tcx> {
252 span: Span,
254 peeled_ty: Ty<'tcx>,
256}
257
258impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
259 pub fn note_field_shadowed_by_private_candidate_in_cause(
260 &self,
261 err: &mut Diag<'_>,
262 cause: &ObligationCause<'tcx>,
263 param_env: ty::ParamEnv<'tcx>,
264 ) {
265 let mut hir_ids = FxHashSet::default();
266 let mut next_code = Some(cause.code());
269 while let Some(cause_code) = next_code {
270 match cause_code {
271 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
272 hir_ids.insert(*lhs_hir_id);
273 hir_ids.insert(*rhs_hir_id);
274 }
275 ObligationCauseCode::FunctionArg { arg_hir_id, .. }
276 | ObligationCauseCode::ReturnValue(arg_hir_id)
277 | ObligationCauseCode::AwaitableExpr(arg_hir_id)
278 | ObligationCauseCode::BlockTailExpression(arg_hir_id, _)
279 | ObligationCauseCode::UnOp { hir_id: arg_hir_id } => {
280 hir_ids.insert(*arg_hir_id);
281 }
282 ObligationCauseCode::OpaqueReturnType(Some((_, hir_id))) => {
283 hir_ids.insert(*hir_id);
284 }
285 _ => {}
286 }
287 next_code = cause_code.parent();
288 }
289
290 if !cause.span.is_dummy()
291 && let Some(body) = self.tcx.hir_maybe_body_owned_by(cause.body_id)
292 {
293 let mut expr_finder = FindExprBySpan::new(cause.span, self.tcx);
294 expr_finder.visit_body(body);
295 if let Some(expr) = expr_finder.result {
296 hir_ids.insert(expr.hir_id);
297 }
298 }
299
300 #[allow(rustc::potential_query_instability)]
302 let mut hir_ids: Vec<_> = hir_ids.into_iter().collect();
303 let source_map = self.tcx.sess.source_map();
304 hir_ids.sort_by_cached_key(|hir_id| {
305 let span = self.tcx.hir_span(*hir_id);
306 let lo = source_map.lookup_byte_offset(span.lo());
307 let hi = source_map.lookup_byte_offset(span.hi());
308 (lo.sf.name.prefer_remapped_unconditionally().to_string(), lo.pos.0, hi.pos.0)
309 });
310
311 for hir_id in hir_ids {
312 self.note_field_shadowed_by_private_candidate(err, hir_id, param_env);
313 }
314 }
315
316 pub fn note_field_shadowed_by_private_candidate(
317 &self,
318 err: &mut Diag<'_>,
319 hir_id: hir::HirId,
320 param_env: ty::ParamEnv<'tcx>,
321 ) {
322 let Some(typeck_results) = &self.typeck_results else {
323 return;
324 };
325 let Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
326 return;
327 };
328 let hir::ExprKind::Field(base_expr, field_ident) = expr.kind else {
329 return;
330 };
331
332 let Some(base_ty) = typeck_results.expr_ty_opt(base_expr) else {
333 return;
334 };
335 let base_ty = self.resolve_vars_if_possible(base_ty);
336 if base_ty.references_error() {
337 return;
338 }
339
340 let fn_body_hir_id = self.tcx.local_def_id_to_hir_id(typeck_results.hir_owner.def_id);
341 let mut private_candidate: Option<(Ty<'tcx>, Ty<'tcx>, Span)> = None;
342
343 for (deref_base_ty, _) in (self.autoderef_steps)(base_ty) {
344 let ty::Adt(base_def, args) = deref_base_ty.kind() else {
345 continue;
346 };
347
348 if base_def.is_enum() {
349 continue;
350 }
351
352 let (adjusted_ident, def_scope) =
353 self.tcx.adjust_ident_and_get_scope(field_ident, base_def.did(), fn_body_hir_id);
354
355 let Some((_, field_def)) =
356 base_def.non_enum_variant().fields.iter_enumerated().find(|(_, field)| {
357 field.ident(self.tcx).normalize_to_macros_2_0() == adjusted_ident
358 })
359 else {
360 continue;
361 };
362 let field_span = self
363 .tcx
364 .def_ident_span(field_def.did)
365 .unwrap_or_else(|| self.tcx.def_span(field_def.did));
366
367 if field_def.vis.is_accessible_from(def_scope, self.tcx) {
368 let accessible_field_ty = field_def.ty(self.tcx, args).skip_norm_wip();
369 if let Some((private_base_ty, private_field_ty, private_field_span)) =
370 private_candidate
371 && !self.can_eq(param_env, private_field_ty, accessible_field_ty)
372 {
373 let private_struct_span = match private_base_ty.kind() {
374 ty::Adt(private_base_def, _) => self
375 .tcx
376 .def_ident_span(private_base_def.did())
377 .unwrap_or_else(|| self.tcx.def_span(private_base_def.did())),
378 _ => DUMMY_SP,
379 };
380 let accessible_struct_span = self
381 .tcx
382 .def_ident_span(base_def.did())
383 .unwrap_or_else(|| self.tcx.def_span(base_def.did()));
384 let deref_impl_span = (typeck_results
385 .expr_adjustments(base_expr)
386 .iter()
387 .filter(|adj| {
388 #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
Adjust::Deref(DerefAdjustKind::Overloaded(_)) => true,
_ => false,
}matches!(adj.kind, Adjust::Deref(DerefAdjustKind::Overloaded(_)))
389 })
390 .count()
391 == 1)
392 .then(|| {
393 self.probe(|_| {
394 let deref_trait_did =
395 self.tcx.require_lang_item(LangItem::Deref, DUMMY_SP);
396 let trait_ref =
397 ty::TraitRef::new(self.tcx, deref_trait_did, [private_base_ty]);
398 let obligation: Obligation<'tcx, ty::Predicate<'tcx>> =
399 Obligation::new(
400 self.tcx,
401 ObligationCause::dummy(),
402 param_env,
403 trait_ref,
404 );
405 let Ok(Some(ImplSource::UserDefined(impl_data))) =
406 SelectionContext::new(self)
407 .select(&obligation.with(self.tcx, trait_ref))
408 else {
409 return None;
410 };
411 Some(self.tcx.def_span(impl_data.impl_def_id))
412 })
413 })
414 .flatten();
415
416 let mut note_spans: MultiSpan = private_struct_span.into();
417 if private_struct_span != DUMMY_SP {
418 note_spans.push_span_label(private_struct_span, "in this struct");
419 }
420 if private_field_span != DUMMY_SP {
421 note_spans.push_span_label(
422 private_field_span,
423 "if this field wasn't private, it would be accessible",
424 );
425 }
426 if accessible_struct_span != DUMMY_SP {
427 note_spans.push_span_label(
428 accessible_struct_span,
429 "this struct is accessible through auto-deref",
430 );
431 }
432 if field_span != DUMMY_SP {
433 note_spans
434 .push_span_label(field_span, "this is the field that was accessed");
435 }
436 if let Some(deref_impl_span) = deref_impl_span
437 && deref_impl_span != DUMMY_SP
438 {
439 note_spans.push_span_label(
440 deref_impl_span,
441 "the field was accessed through this `Deref`",
442 );
443 }
444
445 err.span_note(
446 note_spans,
447 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there is a field `{0}` on `{1}` with type `{2}` but it is private; `{0}` from `{3}` was accessed through auto-deref instead",
field_ident, private_base_ty, private_field_ty,
deref_base_ty))
})format!(
448 "there is a field `{field_ident}` on `{private_base_ty}` with type `{private_field_ty}` but it is private; `{field_ident}` from `{deref_base_ty}` was accessed through auto-deref instead"
449 ),
450 );
451 }
452
453 return;
456 }
457
458 private_candidate.get_or_insert((
459 deref_base_ty,
460 field_def.ty(self.tcx, args).skip_norm_wip(),
461 field_span,
462 ));
463 }
464 }
465
466 pub fn suggest_restricting_param_bound(
467 &self,
468 err: &mut Diag<'_>,
469 trait_pred: ty::PolyTraitPredicate<'tcx>,
470 associated_ty: Option<(&'static str, Ty<'tcx>)>,
471 mut body_id: LocalDefId,
472 ) {
473 if trait_pred.skip_binder().polarity != ty::PredicatePolarity::Positive {
474 return;
475 }
476
477 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
478
479 let self_ty = trait_pred.skip_binder().self_ty();
480 let (param_ty, projection) = match *self_ty.kind() {
481 ty::Param(_) => (true, None),
482 ty::Alias(projection @ ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
483 (false, Some(projection))
484 }
485 _ => (false, None),
486 };
487
488 let mut finder = ParamFinder { .. };
489 finder.visit_binder(&trait_pred);
490
491 loop {
494 let node = self.tcx.hir_node_by_def_id(body_id);
495 match node {
496 hir::Node::Item(hir::Item {
497 kind: hir::ItemKind::Trait { ident, generics, bounds, .. },
498 ..
499 }) if self_ty == self.tcx.types.self_param => {
500 if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
501 suggest_restriction(
503 self.tcx,
504 body_id,
505 generics,
506 "`Self`",
507 err,
508 None,
509 projection,
510 trait_pred,
511 Some((&ident, bounds)),
512 );
513 return;
514 }
515
516 hir::Node::TraitItem(hir::TraitItem {
517 generics,
518 kind: hir::TraitItemKind::Fn(..),
519 ..
520 }) if self_ty == self.tcx.types.self_param => {
521 if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
522 suggest_restriction(
524 self.tcx, body_id, generics, "`Self`", err, None, projection, trait_pred,
525 None,
526 );
527 return;
528 }
529
530 hir::Node::TraitItem(hir::TraitItem {
531 generics,
532 kind: hir::TraitItemKind::Fn(fn_sig, ..),
533 ..
534 })
535 | hir::Node::ImplItem(hir::ImplItem {
536 generics,
537 kind: hir::ImplItemKind::Fn(fn_sig, ..),
538 ..
539 })
540 | hir::Node::Item(hir::Item {
541 kind: hir::ItemKind::Fn { sig: fn_sig, generics, .. },
542 ..
543 }) if projection.is_some() => {
544 suggest_restriction(
546 self.tcx,
547 body_id,
548 generics,
549 "the associated type",
550 err,
551 Some(fn_sig),
552 projection,
553 trait_pred,
554 None,
555 );
556 return;
557 }
558 hir::Node::Item(hir::Item {
559 kind:
560 hir::ItemKind::Trait { generics, .. }
561 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
562 ..
563 }) if projection.is_some() => {
564 suggest_restriction(
566 self.tcx,
567 body_id,
568 generics,
569 "the associated type",
570 err,
571 None,
572 projection,
573 trait_pred,
574 None,
575 );
576 return;
577 }
578
579 hir::Node::Item(hir::Item {
580 kind:
581 hir::ItemKind::Struct(_, generics, _)
582 | hir::ItemKind::Enum(_, generics, _)
583 | hir::ItemKind::Union(_, generics, _)
584 | hir::ItemKind::Trait { generics, .. }
585 | hir::ItemKind::Impl(hir::Impl { generics, .. })
586 | hir::ItemKind::Fn { generics, .. }
587 | hir::ItemKind::TyAlias(_, generics, _)
588 | hir::ItemKind::Const(_, generics, _, _)
589 | hir::ItemKind::TraitAlias(_, _, generics, _),
590 ..
591 })
592 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
593 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
594 if param_ty =>
595 {
596 if !trait_pred.skip_binder().trait_ref.args[1..]
605 .iter()
606 .all(|g| g.is_suggestable(self.tcx, false))
607 {
608 return;
609 }
610 let param_name = self_ty.to_string();
612 let mut constraint = {
let _guard = NoTrimmedGuard::new();
trait_pred.print_modifiers_and_trait_path().to_string()
}with_no_trimmed_paths!(
613 trait_pred.print_modifiers_and_trait_path().to_string()
614 );
615
616 if let Some((name, term)) = associated_ty {
617 if let Some(stripped) = constraint.strip_suffix('>') {
620 constraint = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, {1} = {2}>", stripped, name,
term))
})format!("{stripped}, {name} = {term}>");
621 } else {
622 constraint.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} = {1}>", name, term))
})format!("<{name} = {term}>"));
623 }
624 }
625
626 if suggest_constraining_type_param(
627 self.tcx,
628 generics,
629 err,
630 ¶m_name,
631 &constraint,
632 Some(trait_pred.def_id()),
633 None,
634 ) {
635 return;
636 }
637 }
638
639 hir::Node::TraitItem(hir::TraitItem {
640 generics,
641 kind: hir::TraitItemKind::Fn(..),
642 ..
643 })
644 | hir::Node::ImplItem(hir::ImplItem {
645 generics,
646 impl_kind: hir::ImplItemImplKind::Inherent { .. },
647 kind: hir::ImplItemKind::Fn(..),
648 ..
649 }) if finder.can_suggest_bound(generics) => {
650 suggest_arbitrary_trait_bound(
652 self.tcx,
653 generics,
654 err,
655 trait_pred,
656 associated_ty,
657 );
658 }
659 hir::Node::Item(hir::Item {
660 kind:
661 hir::ItemKind::Struct(_, generics, _)
662 | hir::ItemKind::Enum(_, generics, _)
663 | hir::ItemKind::Union(_, generics, _)
664 | hir::ItemKind::Trait { generics, .. }
665 | hir::ItemKind::Impl(hir::Impl { generics, .. })
666 | hir::ItemKind::Fn { generics, .. }
667 | hir::ItemKind::TyAlias(_, generics, _)
668 | hir::ItemKind::Const(_, generics, _, _)
669 | hir::ItemKind::TraitAlias(_, _, generics, _),
670 ..
671 }) if finder.can_suggest_bound(generics) => {
672 if suggest_arbitrary_trait_bound(
674 self.tcx,
675 generics,
676 err,
677 trait_pred,
678 associated_ty,
679 ) {
680 return;
681 }
682 }
683 hir::Node::Crate(..) => return,
684
685 _ => {}
686 }
687 body_id = self.tcx.local_parent(body_id);
688 }
689 }
690
691 pub(super) fn suggest_dereferences(
694 &self,
695 obligation: &PredicateObligation<'tcx>,
696 err: &mut Diag<'_>,
697 trait_pred: ty::PolyTraitPredicate<'tcx>,
698 ) -> bool {
699 let mut code = obligation.cause.code();
700 if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
701 && let Some(typeck_results) = &self.typeck_results
702 && let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
703 && let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
704 {
705 let mut real_trait_pred = trait_pred;
709 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
710 code = parent_code;
711 if let Some(parent_trait_pred) = parent_trait_pred {
712 real_trait_pred = parent_trait_pred;
713 }
714 }
715
716 let real_ty = self.tcx.instantiate_bound_regions_with_erased(real_trait_pred.self_ty());
719 if !self.can_eq(obligation.param_env, real_ty, arg_ty) {
720 return false;
721 }
722
723 let (is_under_ref, base_ty, span) = match expr.kind {
730 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, subexpr)
731 if let &ty::Ref(region, base_ty, hir::Mutability::Not) = real_ty.kind() =>
732 {
733 (Some(region), base_ty, subexpr.span)
734 }
735 hir::ExprKind::AddrOf(..) => return false,
737 _ => (None, real_ty, obligation.cause.span),
738 };
739
740 let autoderef = (self.autoderef_steps)(base_ty);
741 let mut is_boxed = base_ty.is_box();
742 if let Some(steps) = autoderef.into_iter().position(|(mut ty, obligations)| {
743 let can_deref = is_under_ref.is_some()
746 || self.type_is_copy_modulo_regions(obligation.param_env, ty)
747 || ty.is_numeric() || is_boxed && self.type_is_sized_modulo_regions(obligation.param_env, ty);
749 is_boxed &= ty.is_box();
750
751 if let Some(region) = is_under_ref {
753 ty = Ty::new_ref(self.tcx, region, ty, hir::Mutability::Not);
754 }
755
756 let real_trait_pred_and_ty =
758 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
759 let obligation = self.mk_trait_obligation_with_new_self_ty(
760 obligation.param_env,
761 real_trait_pred_and_ty,
762 );
763
764 can_deref
765 && obligations
766 .iter()
767 .chain([&obligation])
768 .all(|obligation| self.predicate_may_hold(obligation))
769 }) && steps > 0
770 {
771 if span.in_external_macro(self.tcx.sess.source_map()) {
772 return false;
773 }
774 let derefs = "*".repeat(steps);
775 let msg = "consider dereferencing here";
776
777 let call_node = self.tcx.hir_node(*call_hir_id);
778 let is_receiver = #[allow(non_exhaustive_omitted_patterns)] match call_node {
Node::Expr(hir::Expr {
kind: hir::ExprKind::MethodCall(_, receiver_expr, ..), .. }) if
receiver_expr.hir_id == *arg_hir_id => true,
_ => false,
}matches!(
779 call_node,
780 Node::Expr(hir::Expr {
781 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
782 ..
783 })
784 if receiver_expr.hir_id == *arg_hir_id
785 );
786 if is_receiver {
787 err.multipart_suggestion(
788 msg,
789 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}", derefs))
})), (span.shrink_to_hi(), ")".to_string())]))vec![
790 (span.shrink_to_lo(), format!("({derefs}")),
791 (span.shrink_to_hi(), ")".to_string()),
792 ],
793 Applicability::MachineApplicable,
794 )
795 } else {
796 err.span_suggestion_verbose(
797 span.shrink_to_lo(),
798 msg,
799 derefs,
800 Applicability::MachineApplicable,
801 )
802 };
803 return true;
804 }
805 } else if let (
806 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. },
807 predicate,
808 ) = code.peel_derives_with_predicate()
809 && let Some(typeck_results) = &self.typeck_results
810 && let hir::Node::Expr(lhs) = self.tcx.hir_node(*lhs_hir_id)
811 && let hir::Node::Expr(rhs) = self.tcx.hir_node(*rhs_hir_id)
812 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs)
813 && let trait_pred = predicate.unwrap_or(trait_pred)
814 && hir::lang_items::BINARY_OPERATORS
816 .iter()
817 .filter_map(|&op| self.tcx.lang_items().get(op))
818 .any(|op| {
819 op == trait_pred.skip_binder().trait_ref.def_id
820 })
821 {
822 let trait_pred = predicate.unwrap_or(trait_pred);
824 let lhs_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
825 let lhs_autoderef = (self.autoderef_steps)(lhs_ty);
826 let rhs_autoderef = (self.autoderef_steps)(rhs_ty);
827 let first_lhs = lhs_autoderef.first().unwrap().clone();
828 let first_rhs = rhs_autoderef.first().unwrap().clone();
829 let mut autoderefs = lhs_autoderef
830 .into_iter()
831 .enumerate()
832 .rev()
833 .zip_longest(rhs_autoderef.into_iter().enumerate().rev())
834 .map(|t| match t {
835 EitherOrBoth::Both(a, b) => (a, b),
836 EitherOrBoth::Left(a) => (a, (0, first_rhs.clone())),
837 EitherOrBoth::Right(b) => ((0, first_lhs.clone()), b),
838 })
839 .rev();
840 if let Some((lsteps, rsteps)) =
841 autoderefs.find_map(|((lsteps, (l_ty, _)), (rsteps, (r_ty, _)))| {
842 let trait_pred_and_ty = trait_pred.map_bound(|inner| {
846 (
847 ty::TraitPredicate {
848 trait_ref: ty::TraitRef::new_from_args(
849 self.tcx,
850 inner.trait_ref.def_id,
851 self.tcx.mk_args(
852 &[&[l_ty.into(), r_ty.into()], &inner.trait_ref.args[2..]]
853 .concat(),
854 ),
855 ),
856 ..inner
857 },
858 l_ty,
859 )
860 });
861 let obligation = self.mk_trait_obligation_with_new_self_ty(
862 obligation.param_env,
863 trait_pred_and_ty,
864 );
865 self.predicate_may_hold(&obligation).then_some(match (lsteps, rsteps) {
866 (_, 0) => (Some(lsteps), None),
867 (0, _) => (None, Some(rsteps)),
868 _ => (Some(lsteps), Some(rsteps)),
869 })
870 })
871 {
872 let make_sugg = |mut expr: &Expr<'_>, mut steps| {
873 if expr.span.in_external_macro(self.tcx.sess.source_map()) {
874 return None;
875 }
876 let mut prefix_span = expr.span.shrink_to_lo();
877 let mut msg = "consider dereferencing here";
878 if let hir::ExprKind::AddrOf(_, _, inner) = expr.kind {
879 msg = "consider removing the borrow and dereferencing instead";
880 if let hir::ExprKind::AddrOf(..) = inner.kind {
881 msg = "consider removing the borrows and dereferencing instead";
882 }
883 }
884 while let hir::ExprKind::AddrOf(_, _, inner) = expr.kind
885 && steps > 0
886 {
887 prefix_span = prefix_span.with_hi(inner.span.lo());
888 expr = inner;
889 steps -= 1;
890 }
891 if steps == 0 {
893 return Some((
894 msg.trim_end_matches(" and dereferencing instead"),
895 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(prefix_span, String::new())]))vec![(prefix_span, String::new())],
896 ));
897 }
898 let derefs = "*".repeat(steps);
899 let needs_parens = steps > 0 && expr_needs_parens(expr);
900 let mut suggestion = if needs_parens {
901 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}(", derefs))
})), (expr.span.shrink_to_hi(), ")".to_string())]))vec![
902 (
903 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
904 format!("{derefs}("),
905 ),
906 (expr.span.shrink_to_hi(), ")".to_string()),
907 ]
908 } else {
909 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", derefs))
}))]))vec![(
910 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
911 format!("{derefs}"),
912 )]
913 };
914 if !prefix_span.is_empty() {
916 suggestion.push((prefix_span, String::new()));
917 }
918 Some((msg, suggestion))
919 };
920
921 if let Some(lsteps) = lsteps
922 && let Some(rsteps) = rsteps
923 && lsteps > 0
924 && rsteps > 0
925 {
926 let Some((_, mut suggestion)) = make_sugg(lhs, lsteps) else {
927 return false;
928 };
929 let Some((_, mut rhs_suggestion)) = make_sugg(rhs, rsteps) else {
930 return false;
931 };
932 suggestion.append(&mut rhs_suggestion);
933 err.multipart_suggestion(
934 "consider dereferencing both sides of the expression",
935 suggestion,
936 Applicability::MachineApplicable,
937 );
938 return true;
939 } else if let Some(lsteps) = lsteps
940 && lsteps > 0
941 {
942 let Some((msg, suggestion)) = make_sugg(lhs, lsteps) else {
943 return false;
944 };
945 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
946 return true;
947 } else if let Some(rsteps) = rsteps
948 && rsteps > 0
949 {
950 let Some((msg, suggestion)) = make_sugg(rhs, rsteps) else {
951 return false;
952 };
953 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
954 return true;
955 }
956 }
957 }
958 false
959 }
960
961 fn get_closure_name(
965 &self,
966 def_id: DefId,
967 err: &mut Diag<'_>,
968 msg: Cow<'static, str>,
969 ) -> Option<Symbol> {
970 let get_name = |err: &mut Diag<'_>, kind: &hir::PatKind<'_>| -> Option<Symbol> {
971 match &kind {
974 hir::PatKind::Binding(hir::BindingMode::NONE, _, ident, None) => Some(ident.name),
975 _ => {
976 err.note(msg);
977 None
978 }
979 }
980 };
981
982 let hir_id = self.tcx.local_def_id_to_hir_id(def_id.as_local()?);
983 match self.tcx.parent_hir_node(hir_id) {
984 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(local), .. }) => {
985 get_name(err, &local.pat.kind)
986 }
987 hir::Node::LetStmt(local) => get_name(err, &local.pat.kind),
990 _ => None,
991 }
992 }
993
994 pub(super) fn suggest_fn_call(
998 &self,
999 obligation: &PredicateObligation<'tcx>,
1000 err: &mut Diag<'_>,
1001 trait_pred: ty::PolyTraitPredicate<'tcx>,
1002 ) -> bool {
1003 if self.typeck_results.is_none() {
1006 return false;
1007 }
1008
1009 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
1010 obligation.predicate.kind().skip_binder()
1011 && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1012 {
1013 return false;
1015 }
1016
1017 let self_ty = self.instantiate_binder_with_fresh_vars(
1018 DUMMY_SP,
1019 BoundRegionConversionTime::FnCall,
1020 trait_pred.self_ty(),
1021 );
1022
1023 let Some((def_id_or_name, output, inputs)) =
1024 self.extract_callable_info(obligation.cause.body_id, obligation.param_env, self_ty)
1025 else {
1026 return false;
1027 };
1028
1029 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
1031
1032 let new_obligation =
1033 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1034 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
1035 return false;
1036 }
1037
1038 if let ty::CoroutineClosure(def_id, args) = *self_ty.kind()
1042 && let sig = args.as_coroutine_closure().coroutine_closure_sig().skip_binder()
1043 && let ty::Tuple(inputs) = *sig.tupled_inputs_ty.kind()
1044 && inputs.is_empty()
1045 && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Future)
1046 && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1047 && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) =
1048 self.tcx.hir_node(*arg_hir_id)
1049 && let Some(hir::Node::Expr(hir::Expr {
1050 kind: hir::ExprKind::Closure(closure), ..
1051 })) = self.tcx.hir_get_if_local(def_id)
1052 && let hir::ClosureKind::CoroutineClosure(CoroutineDesugaring::Async) = closure.kind
1053 && let Some(arg_span) = closure.fn_arg_span
1054 && obligation.cause.span.contains(arg_span)
1055 {
1056 let mut body = self.tcx.hir_body(closure.body).value;
1057 let peeled = body.peel_blocks().peel_drop_temps();
1058 if let hir::ExprKind::Closure(inner) = peeled.kind {
1059 body = self.tcx.hir_body(inner.body).value;
1060 }
1061 if !#[allow(non_exhaustive_omitted_patterns)] match body.peel_blocks().peel_drop_temps().kind
{
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(body.peel_blocks().peel_drop_temps().kind, hir::ExprKind::Block(..)) {
1062 return false;
1063 }
1064
1065 let sm = self.tcx.sess.source_map();
1066 let removal_span = if let Ok(snippet) =
1067 sm.span_to_snippet(arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1)))
1068 && snippet.ends_with(' ')
1069 {
1070 arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1))
1072 } else {
1073 arg_span
1074 };
1075 err.span_suggestion_verbose(
1076 removal_span,
1077 "use `async {}` instead of `async || {}` to introduce an async block",
1078 "",
1079 Applicability::MachineApplicable,
1080 );
1081 return true;
1082 }
1083
1084 let msg = match def_id_or_name {
1086 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
1087 DefKind::Ctor(CtorOf::Struct, _) => {
1088 Cow::from("use parentheses to construct this tuple struct")
1089 }
1090 DefKind::Ctor(CtorOf::Variant, _) => {
1091 Cow::from("use parentheses to construct this tuple variant")
1092 }
1093 kind => Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use parentheses to call this {0}",
self.tcx.def_kind_descr(kind, def_id)))
})format!(
1094 "use parentheses to call this {}",
1095 self.tcx.def_kind_descr(kind, def_id)
1096 )),
1097 },
1098 DefIdOrName::Name(name) => Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use parentheses to call this {0}",
name))
})format!("use parentheses to call this {name}")),
1099 };
1100
1101 let args = inputs
1102 .into_iter()
1103 .map(|ty| {
1104 if ty.is_suggestable(self.tcx, false) {
1105 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", ty))
})format!("/* {ty} */")
1106 } else {
1107 "/* value */".to_string()
1108 }
1109 })
1110 .collect::<Vec<_>>()
1111 .join(", ");
1112
1113 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1114 && obligation.cause.span.can_be_used_for_suggestions()
1115 {
1116 let span = obligation.cause.span;
1117
1118 let arg_expr = match self.tcx.hir_node(*arg_hir_id) {
1119 hir::Node::Expr(expr) => Some(expr),
1120 _ => None,
1121 };
1122
1123 let is_closure_expr =
1124 arg_expr.is_some_and(|expr| #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Closure(..) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Closure(..)));
1125
1126 if args.is_empty()
1129 && let Some(expr) = arg_expr
1130 && let hir::ExprKind::Closure(closure) = expr.kind
1131 {
1132 let mut body = self.tcx.hir_body(closure.body).value;
1133
1134 if let hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) =
1136 closure.kind
1137 {
1138 let peeled = body.peel_blocks().peel_drop_temps();
1139 if let hir::ExprKind::Closure(inner) = peeled.kind {
1140 body = self.tcx.hir_body(inner.body).value;
1141 }
1142 }
1143
1144 let peeled_body = body.peel_blocks().peel_drop_temps();
1145 if let hir::ExprKind::Call(callee, call_args) = peeled_body.kind
1146 && call_args.is_empty()
1147 && let hir::ExprKind::Block(..) = callee.peel_blocks().peel_drop_temps().kind
1148 {
1149 return false;
1150 }
1151 }
1152
1153 if is_closure_expr {
1154 err.multipart_suggestions(
1155 msg,
1156 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "(".to_string()),
(span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(")({0})", args))
}))]))]))vec![vec![
1157 (span.shrink_to_lo(), "(".to_string()),
1158 (span.shrink_to_hi(), format!(")({args})")),
1159 ]],
1160 Applicability::HasPlaceholders,
1161 );
1162 } else {
1163 err.span_suggestion_verbose(
1164 span.shrink_to_hi(),
1165 msg,
1166 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", args))
})format!("({args})"),
1167 Applicability::HasPlaceholders,
1168 );
1169 }
1170 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1171 let name = match self.tcx.hir_get_if_local(def_id) {
1172 Some(hir::Node::Expr(hir::Expr {
1173 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1174 ..
1175 })) => {
1176 err.span_label(*fn_decl_span, "consider calling this closure");
1177 let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
1178 return false;
1179 };
1180 name.to_string()
1181 }
1182 Some(hir::Node::Item(hir::Item {
1183 kind: hir::ItemKind::Fn { ident, .. }, ..
1184 })) => {
1185 err.span_label(ident.span, "consider calling this function");
1186 ident.to_string()
1187 }
1188 Some(hir::Node::Ctor(..)) => {
1189 let name = self.tcx.def_path_str(def_id);
1190 err.span_label(
1191 self.tcx.def_span(def_id),
1192 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling the constructor for `{0}`",
name))
})format!("consider calling the constructor for `{name}`"),
1193 );
1194 name
1195 }
1196 _ => return false,
1197 };
1198 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}({2})`", msg, name, args))
})format!("{msg}: `{name}({args})`"));
1199 }
1200 true
1201 }
1202
1203 pub(super) fn suggest_cast_to_fn_pointer(
1204 &self,
1205 obligation: &PredicateObligation<'tcx>,
1206 err: &mut Diag<'_>,
1207 leaf_trait_predicate: ty::PolyTraitPredicate<'tcx>,
1208 main_trait_predicate: ty::PolyTraitPredicate<'tcx>,
1209 span: Span,
1210 ) -> bool {
1211 let &[candidate] = &self.find_similar_impl_candidates(leaf_trait_predicate)[..] else {
1212 return false;
1213 };
1214 let candidate = candidate.trait_ref;
1215
1216 if !#[allow(non_exhaustive_omitted_patterns)] match (candidate.self_ty().kind(),
main_trait_predicate.self_ty().skip_binder().kind()) {
(ty::FnPtr(..), ty::FnDef(..)) => true,
_ => false,
}matches!(
1217 (candidate.self_ty().kind(), main_trait_predicate.self_ty().skip_binder().kind(),),
1218 (ty::FnPtr(..), ty::FnDef(..))
1219 ) {
1220 return false;
1221 }
1222
1223 let parenthesized_cast = |span: Span| {
1224 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "(".to_string()),
(span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0})",
candidate.self_ty()))
}))]))vec![
1225 (span.shrink_to_lo(), "(".to_string()),
1226 (span.shrink_to_hi(), format!(" as {})", candidate.self_ty())),
1227 ]
1228 };
1229 let suggestion = if self.tcx.sess.source_map().span_followed_by(span, ".").is_some() {
1231 parenthesized_cast(span)
1232 } else if let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) {
1233 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1234 expr_finder.visit_expr(body.value);
1235 if let Some(expr) = expr_finder.result
1236 && let hir::ExprKind::AddrOf(_, _, expr) = expr.kind
1237 {
1238 parenthesized_cast(expr.span)
1239 } else {
1240 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}",
candidate.self_ty()))
}))]))vec![(span.shrink_to_hi(), format!(" as {}", candidate.self_ty()))]
1241 }
1242 } else {
1243 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" as {0}",
candidate.self_ty()))
}))]))vec![(span.shrink_to_hi(), format!(" as {}", candidate.self_ty()))]
1244 };
1245
1246 let trait_ = self.tcx.short_string(candidate.print_trait_sugared(), err.long_ty_path());
1247 let self_ty = self.tcx.short_string(candidate.self_ty(), err.long_ty_path());
1248 err.multipart_suggestion(
1249 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `{0}` is implemented for fn pointer `{1}`, try casting using `as`",
trait_, self_ty))
})format!(
1250 "the trait `{trait_}` is implemented for fn pointer \
1251 `{self_ty}`, try casting using `as`",
1252 ),
1253 suggestion,
1254 Applicability::MaybeIncorrect,
1255 );
1256 true
1257 }
1258
1259 pub(super) fn check_for_binding_assigned_block_without_tail_expression(
1260 &self,
1261 obligation: &PredicateObligation<'tcx>,
1262 err: &mut Diag<'_>,
1263 trait_pred: ty::PolyTraitPredicate<'tcx>,
1264 ) {
1265 let mut span = obligation.cause.span;
1266 while span.from_expansion() {
1267 span.remove_mark();
1269 }
1270 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1271 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
1272 return;
1273 };
1274 expr_finder.visit_expr(body.value);
1275 let Some(expr) = expr_finder.result else {
1276 return;
1277 };
1278 let Some(typeck) = &self.typeck_results else {
1279 return;
1280 };
1281 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
1282 return;
1283 };
1284 if !ty.is_unit() {
1285 return;
1286 };
1287 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
1288 return;
1289 };
1290 let Res::Local(hir_id) = path.res else {
1291 return;
1292 };
1293 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
1294 return;
1295 };
1296 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
1297 self.tcx.parent_hir_node(pat.hir_id)
1298 else {
1299 return;
1300 };
1301 let hir::ExprKind::Block(block, None) = init.kind else {
1302 return;
1303 };
1304 if block.expr.is_some() {
1305 return;
1306 }
1307 let [.., stmt] = block.stmts else {
1308 err.span_label(block.span, "this empty block is missing a tail expression");
1309 return;
1310 };
1311 if stmt.span.from_expansion() {
1314 return;
1315 }
1316 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
1317 return;
1318 };
1319 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1320 err.span_label(block.span, "this block is missing a tail expression");
1321 return;
1322 };
1323 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1324 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1325
1326 let new_obligation =
1327 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1328 if !#[allow(non_exhaustive_omitted_patterns)] match tail_expr.kind {
hir::ExprKind::Err(_) => true,
_ => false,
}matches!(tail_expr.kind, hir::ExprKind::Err(_))
1329 && self.predicate_must_hold_modulo_regions(&new_obligation)
1330 {
1331 err.span_suggestion_short(
1332 stmt.span.with_lo(tail_expr.span.hi()),
1333 "remove this semicolon",
1334 "",
1335 Applicability::MachineApplicable,
1336 );
1337 } else {
1338 err.span_label(block.span, "this block is missing a tail expression");
1339 }
1340 }
1341
1342 pub(super) fn suggest_add_clone_to_arg(
1343 &self,
1344 obligation: &PredicateObligation<'tcx>,
1345 err: &mut Diag<'_>,
1346 trait_pred: ty::PolyTraitPredicate<'tcx>,
1347 ) -> bool {
1348 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
1349 self.enter_forall(self_ty, |ty: Ty<'_>| {
1350 let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_id) else {
1351 return false;
1352 };
1353 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1354 let ty::Param(param) = inner_ty.kind() else { return false };
1355 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1356 else {
1357 return false;
1358 };
1359
1360 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, obligation.cause.span);
1361 let has_clone = |ty| {
1362 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1363 .must_apply_modulo_regions()
1364 };
1365
1366 let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
1367 Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
1369 Node::Expr(Expr {
1372 kind:
1373 hir::ExprKind::MethodCall(
1374 hir::PathSegment { ident, .. },
1375 _receiver,
1376 [],
1377 call_span,
1378 ),
1379 hir_id,
1380 ..
1381 }) if ident.name == sym::clone
1382 && !call_span.from_expansion()
1383 && !has_clone(*inner_ty) =>
1384 {
1385 let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
1387 let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
1388 else {
1389 return false;
1390 };
1391 if self.tcx.trait_of_assoc(did) != Some(clone_trait) {
1392 return false;
1393 }
1394 Some(ident.span)
1395 }
1396 _ => return false,
1397 };
1398
1399 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1400 obligation.param_env,
1401 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1402 );
1403
1404 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1405 if !has_clone(param.to_ty(self.tcx)) {
1406 suggest_constraining_type_param(
1407 self.tcx,
1408 generics,
1409 err,
1410 param.name.as_str(),
1411 "Clone",
1412 Some(clone_trait),
1413 None,
1414 );
1415 }
1416 if let Some(existing_clone_call) = existing_clone_call {
1417 err.span_note(
1418 existing_clone_call,
1419 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this `clone()` copies the reference, which does not do anything, because `{0}` does not implement `Clone`",
inner_ty))
})format!(
1420 "this `clone()` copies the reference, \
1421 which does not do anything, \
1422 because `{inner_ty}` does not implement `Clone`"
1423 ),
1424 );
1425 } else {
1426 err.span_suggestion_verbose(
1427 obligation.cause.span.shrink_to_hi(),
1428 "consider using clone here",
1429 ".clone()".to_string(),
1430 Applicability::MaybeIncorrect,
1431 );
1432 }
1433 return true;
1434 }
1435 false
1436 })
1437 }
1438
1439 pub fn extract_callable_info(
1443 &self,
1444 body_id: LocalDefId,
1445 param_env: ty::ParamEnv<'tcx>,
1446 found: Ty<'tcx>,
1447 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1448 let Some((def_id_or_name, output, inputs)) =
1450 (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1451 ty::FnPtr(sig_tys, _) => Some((
1452 DefIdOrName::Name("function pointer"),
1453 sig_tys.output(),
1454 sig_tys.inputs(),
1455 )),
1456 ty::FnDef(def_id, _) => {
1457 let fn_sig = found.fn_sig(self.tcx);
1458 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1459 }
1460 ty::Closure(def_id, args) => {
1461 let fn_sig = args.as_closure().sig();
1462 Some((
1463 DefIdOrName::DefId(def_id),
1464 fn_sig.output(),
1465 fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1466 ))
1467 }
1468 ty::CoroutineClosure(def_id, args) => {
1469 let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1470 Some((
1471 DefIdOrName::DefId(def_id),
1472 sig_parts.map_bound(|sig| {
1473 sig.to_coroutine(
1474 self.tcx,
1475 args.as_coroutine_closure().parent_args(),
1476 self.next_ty_var(DUMMY_SP),
1479 self.tcx.coroutine_for_closure(def_id),
1480 self.next_ty_var(DUMMY_SP),
1481 )
1482 }),
1483 sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1484 ))
1485 }
1486 ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
1487 self.tcx
1488 .item_self_bounds(def_id)
1489 .instantiate(self.tcx, args)
1490 .skip_norm_wip()
1491 .iter()
1492 .find_map(|pred| {
1493 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1494 && self
1495 .tcx
1496 .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1497 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1499 {
1500 Some((
1501 DefIdOrName::DefId(def_id),
1502 pred.kind().rebind(proj.term.expect_type()),
1503 pred.kind().rebind(args.as_slice()),
1504 ))
1505 } else {
1506 None
1507 }
1508 })
1509 }
1510 ty::Dynamic(data, _) => data.iter().find_map(|pred| {
1511 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1512 && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1513 && let ty::Tuple(args) = proj.args.type_at(0).kind()
1515 {
1516 Some((
1517 DefIdOrName::Name("trait object"),
1518 pred.rebind(proj.term.expect_type()),
1519 pred.rebind(args.as_slice()),
1520 ))
1521 } else {
1522 None
1523 }
1524 }),
1525 ty::Param(param) => {
1526 let generics = self.tcx.generics_of(body_id);
1527 let name = if generics.count() > param.index as usize
1528 && let def = generics.param_at(param.index as usize, self.tcx)
1529 && #[allow(non_exhaustive_omitted_patterns)] match def.kind {
ty::GenericParamDefKind::Type { .. } => true,
_ => false,
}matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1530 && def.name == param.name
1531 {
1532 DefIdOrName::DefId(def.def_id)
1533 } else {
1534 DefIdOrName::Name("type parameter")
1535 };
1536 param_env.caller_bounds().iter().find_map(|pred| {
1537 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1538 && self
1539 .tcx
1540 .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1541 && proj.projection_term.self_ty() == found
1542 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1544 {
1545 Some((
1546 name,
1547 pred.kind().rebind(proj.term.expect_type()),
1548 pred.kind().rebind(args.as_slice()),
1549 ))
1550 } else {
1551 None
1552 }
1553 })
1554 }
1555 _ => None,
1556 })
1557 else {
1558 return None;
1559 };
1560
1561 let output = self.instantiate_binder_with_fresh_vars(
1562 DUMMY_SP,
1563 BoundRegionConversionTime::FnCall,
1564 output,
1565 );
1566 let inputs = inputs
1567 .skip_binder()
1568 .iter()
1569 .map(|ty| {
1570 self.instantiate_binder_with_fresh_vars(
1571 DUMMY_SP,
1572 BoundRegionConversionTime::FnCall,
1573 inputs.rebind(*ty),
1574 )
1575 })
1576 .collect();
1577
1578 let InferOk { value: output, obligations: _ } =
1582 self.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(output));
1583
1584 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1585 }
1586
1587 pub(super) fn where_clause_expr_matches_failed_self_ty(
1588 &self,
1589 obligation: &PredicateObligation<'tcx>,
1590 old_self_ty: Ty<'tcx>,
1591 ) -> bool {
1592 let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code() else {
1593 return true;
1594 };
1595 let (Some(typeck_results), Some(body)) = (
1596 self.typeck_results.as_ref(),
1597 self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id),
1598 ) else {
1599 return true;
1600 };
1601
1602 let mut expr_finder = FindExprBySpan::new(obligation.cause.span, self.tcx);
1603 expr_finder.visit_expr(body.value);
1604 let Some(expr) = expr_finder.result else {
1605 return true;
1606 };
1607
1608 let inner_old_self_ty = match old_self_ty.kind() {
1609 ty::Ref(_, inner_ty, _) => Some(*inner_ty),
1610 _ => None,
1611 };
1612
1613 [typeck_results.expr_ty_adjusted_opt(expr)].into_iter().flatten().any(|expr_ty| {
1614 self.can_eq(obligation.param_env, expr_ty, old_self_ty)
1615 || inner_old_self_ty
1616 .is_some_and(|inner_ty| self.can_eq(obligation.param_env, expr_ty, inner_ty))
1617 })
1618 }
1619
1620 pub(super) fn suggest_add_reference_to_arg(
1621 &self,
1622 obligation: &PredicateObligation<'tcx>,
1623 err: &mut Diag<'_>,
1624 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1625 has_custom_message: bool,
1626 ) -> bool {
1627 let span = obligation.cause.span;
1628 let param_env = obligation.param_env;
1629
1630 let mk_result = |trait_pred_and_new_ty| {
1631 let obligation =
1632 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1633 self.predicate_must_hold_modulo_regions(&obligation)
1634 };
1635
1636 let code = match obligation.cause.code() {
1637 ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1638 c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
1641 if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
1642 {
1643 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id)
1647 && let hir::ExprKind::Call(base, _) = expr.kind
1648 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) = base.kind
1649 && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id)
1650 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind
1651 && ty.span == span
1652 {
1653 let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| {
1659 (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1660 });
1661 let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| {
1662 (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1663 });
1664
1665 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1666 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1667 let sugg_msg = |pre: &str| {
1668 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you likely meant to call the associated function `{0}` for type `&{2}{1}`, but the code as written calls associated function `{0}` on type `{1}`",
segment.ident, poly_trait_pred.self_ty(), pre))
})format!(
1669 "you likely meant to call the associated function `{FN}` for type \
1670 `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \
1671 type `{TY}`",
1672 FN = segment.ident,
1673 TY = poly_trait_pred.self_ty(),
1674 )
1675 };
1676 match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl) {
1677 (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => {
1678 err.multipart_suggestion(
1679 sugg_msg(mtbl.prefix_str()),
1680 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(outer.span.shrink_to_lo(), "<".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
1681 (outer.span.shrink_to_lo(), "<".to_string()),
1682 (span.shrink_to_hi(), ">".to_string()),
1683 ],
1684 Applicability::MachineApplicable,
1685 );
1686 }
1687 (true, _, hir::Mutability::Mut) => {
1688 err.multipart_suggestion(
1690 sugg_msg("mut "),
1691 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(outer.span.shrink_to_lo().until(span), "<&".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
1692 (outer.span.shrink_to_lo().until(span), "<&".to_string()),
1693 (span.shrink_to_hi(), ">".to_string()),
1694 ],
1695 Applicability::MachineApplicable,
1696 );
1697 }
1698 (_, true, hir::Mutability::Not) => {
1699 err.multipart_suggestion(
1700 sugg_msg(""),
1701 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(outer.span.shrink_to_lo().until(span), "<&mut ".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
1702 (outer.span.shrink_to_lo().until(span), "<&mut ".to_string()),
1703 (span.shrink_to_hi(), ">".to_string()),
1704 ],
1705 Applicability::MachineApplicable,
1706 );
1707 }
1708 _ => {}
1709 }
1710 return false;
1712 }
1713 c
1714 }
1715 c if #[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1716 span.ctxt().outer_expn_data().kind,
1717 ExpnKind::Desugaring(DesugaringKind::ForLoop)
1718 ) =>
1719 {
1720 c
1721 }
1722 _ => return false,
1723 };
1724
1725 let mut never_suggest_borrow: Vec<_> =
1729 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1730 .iter()
1731 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1732 .collect();
1733
1734 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1735 never_suggest_borrow.push(def_id);
1736 }
1737
1738 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1740 blacklist: &[DefId]|
1741 -> bool {
1742 if blacklist.contains(&old_pred.def_id()) {
1743 return false;
1744 }
1745 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1747 (
1748 trait_pred,
1749 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1750 )
1751 });
1752 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1753 (
1754 trait_pred,
1755 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1756 )
1757 });
1758
1759 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1760 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1761
1762 let (ref_inner_ty_satisfies_pred, ref_inner_ty_is_mut) =
1763 if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1764 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1765 {
1766 (
1767 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1768 mutability.is_mut(),
1769 )
1770 } else {
1771 (false, false)
1772 };
1773
1774 let is_immut = imm_ref_self_ty_satisfies_pred
1775 || (ref_inner_ty_satisfies_pred && !ref_inner_ty_is_mut);
1776 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_is_mut;
1777 if !is_immut && !is_mut {
1778 return false;
1779 }
1780 let Ok(_snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1781 return false;
1782 };
1783 if !#[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1791 span.ctxt().outer_expn_data().kind,
1792 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1793 ) {
1794 return false;
1795 }
1796 let mut label = || {
1803 let is_sized = match obligation.predicate.kind().skip_binder() {
1806 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
1807 self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1808 }
1809 _ => false,
1810 };
1811
1812 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait bound `{0}` is not satisfied",
self.tcx.short_string(old_pred, err.long_ty_path())))
})format!(
1813 "the trait bound `{}` is not satisfied",
1814 self.tcx.short_string(old_pred, err.long_ty_path()),
1815 );
1816 let self_ty_str = self.tcx.short_string(old_pred.self_ty(), err.long_ty_path());
1817 let trait_path = self
1818 .tcx
1819 .short_string(old_pred.print_modifiers_and_trait_path(), err.long_ty_path());
1820
1821 if has_custom_message {
1822 let msg = if is_sized {
1823 "the trait bound `Sized` is not satisfied".into()
1824 } else {
1825 msg
1826 };
1827 err.note(msg);
1828 } else {
1829 err.messages = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(rustc_errors::DiagMessage::from(msg), Style::NoStyle)]))vec![(rustc_errors::DiagMessage::from(msg), Style::NoStyle)];
1830 }
1831 if is_sized {
1832 err.span_label(
1833 span,
1834 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `Sized` is not implemented for `{0}`",
self_ty_str))
})format!("the trait `Sized` is not implemented for `{self_ty_str}`"),
1835 );
1836 } else {
1837 err.span_label(
1838 span,
1839 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `{0}` is not implemented for `{1}`",
trait_path, self_ty_str))
})format!("the trait `{trait_path}` is not implemented for `{self_ty_str}`"),
1840 );
1841 }
1842 };
1843
1844 let mut sugg_prefixes = ::alloc::vec::Vec::new()vec![];
1845 if is_immut {
1846 sugg_prefixes.push("&");
1847 }
1848 if is_mut {
1849 sugg_prefixes.push("&mut ");
1850 }
1851 let sugg_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider{0} borrowing here",
if is_mut && !is_immut { " mutably" } else { "" }))
})format!(
1852 "consider{} borrowing here",
1853 if is_mut && !is_immut { " mutably" } else { "" },
1854 );
1855
1856 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
1860 return false;
1861 };
1862 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1863 expr_finder.visit_expr(body.value);
1864
1865 if let Some(ty) = expr_finder.ty_result {
1866 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(ty.hir_id)
1867 && let hir::ExprKind::Path(hir::QPath::TypeRelative(_, _)) = expr.kind
1868 && ty.span == span
1869 {
1870 label();
1873 err.multipart_suggestions(
1874 sugg_msg,
1875 sugg_prefixes.into_iter().map(|sugg_prefix| {
1876 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}", sugg_prefix))
})), (span.shrink_to_hi(), ">".to_string())]))vec![
1877 (span.shrink_to_lo(), format!("<{sugg_prefix}")),
1878 (span.shrink_to_hi(), ">".to_string()),
1879 ]
1880 }),
1881 Applicability::MaybeIncorrect,
1882 );
1883 return true;
1884 }
1885 return false;
1886 }
1887 let Some(expr) = expr_finder.result else {
1888 return false;
1889 };
1890 if let hir::ExprKind::AddrOf(_, _, _) = expr.kind {
1891 return false;
1892 }
1893 let old_self_ty = old_pred.skip_binder().self_ty();
1894 if !old_self_ty.has_escaping_bound_vars()
1895 && !self.where_clause_expr_matches_failed_self_ty(
1896 obligation,
1897 self.tcx.instantiate_bound_regions_with_erased(old_pred.self_ty()),
1898 )
1899 {
1900 return false;
1901 }
1902 let needs_parens_post = expr_needs_parens(expr);
1903 let needs_parens_pre = match self.tcx.parent_hir_node(expr.hir_id) {
1904 Node::Expr(e)
1905 if let hir::ExprKind::MethodCall(_, base, _, _) = e.kind
1906 && base.hir_id == expr.hir_id =>
1907 {
1908 true
1909 }
1910 _ => false,
1911 };
1912
1913 label();
1914 let suggestions = sugg_prefixes.into_iter().map(|sugg_prefix| {
1915 match (needs_parens_pre, needs_parens_post) {
1916 (false, false) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), sugg_prefix.to_string())]))vec![(span.shrink_to_lo(), sugg_prefix.to_string())],
1917 (false, true) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}(", sugg_prefix))
})), (span.shrink_to_hi(), ")".to_string())]))vec![
1920 (span.shrink_to_lo(), format!("{sugg_prefix}(")),
1921 (span.shrink_to_hi(), ")".to_string()),
1922 ],
1923 (true, false) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}", sugg_prefix))
})), (span.shrink_to_hi(), ")".to_string())]))vec![
1926 (span.shrink_to_lo(), format!("({sugg_prefix}")),
1927 (span.shrink_to_hi(), ")".to_string()),
1928 ],
1929 (true, true) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(", sugg_prefix))
})), (span.shrink_to_hi(), "))".to_string())]))vec![
1930 (span.shrink_to_lo(), format!("({sugg_prefix}(")),
1931 (span.shrink_to_hi(), "))".to_string()),
1932 ],
1933 }
1934 });
1935 err.multipart_suggestions(sugg_msg, suggestions, Applicability::MaybeIncorrect);
1936 return true;
1937 };
1938
1939 if let ObligationCauseCode::ImplDerived(cause) = &*code {
1940 try_borrowing(cause.derived.parent_trait_pred, &[])
1941 } else if let ObligationCauseCode::WhereClause(..)
1942 | ObligationCauseCode::WhereClauseInExpr(..) = code
1943 {
1944 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1945 } else {
1946 false
1947 }
1948 }
1949
1950 pub(super) fn suggest_borrowing_for_object_cast(
1952 &self,
1953 err: &mut Diag<'_>,
1954 obligation: &PredicateObligation<'tcx>,
1955 self_ty: Ty<'tcx>,
1956 target_ty: Ty<'tcx>,
1957 ) {
1958 let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
1959 return;
1960 };
1961 let ty::Dynamic(predicates, _) = object_ty.kind() else {
1962 return;
1963 };
1964 let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
1965
1966 for predicate in predicates.iter() {
1967 if !self.predicate_must_hold_modulo_regions(
1968 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1969 ) {
1970 return;
1971 }
1972 }
1973
1974 err.span_suggestion_verbose(
1975 obligation.cause.span.shrink_to_lo(),
1976 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider borrowing the value, since `&{0}` can be coerced into `{1}`",
self_ty, target_ty))
})format!(
1977 "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
1978 ),
1979 "&",
1980 Applicability::MaybeIncorrect,
1981 );
1982 }
1983
1984 fn peel_expr_refs(
1989 &self,
1990 mut expr: &'tcx hir::Expr<'tcx>,
1991 mut ty: Ty<'tcx>,
1992 ) -> (Vec<PeeledRef<'tcx>>, Option<&'tcx hir::Param<'tcx>>) {
1993 let mut refs = Vec::new();
1994 'outer: loop {
1995 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1996 let span =
1997 if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
1998 expr.span.until(borrowed_span)
1999 } else {
2000 break 'outer;
2001 };
2002
2003 let span = match self.tcx.sess.source_map().span_to_snippet(span) {
2009 Ok(ref snippet) if snippet.starts_with("&") => span,
2010 Ok(ref snippet) if let Some(amp) = snippet.find('&') => {
2011 span.with_lo(span.lo() + BytePos(amp as u32))
2012 }
2013 _ => break 'outer,
2014 };
2015
2016 let ty::Ref(_, inner_ty, _) = ty.kind() else {
2017 break 'outer;
2018 };
2019 ty = *inner_ty;
2020 refs.push(PeeledRef { span, peeled_ty: ty });
2021 expr = borrowed;
2022 }
2023 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
2024 && let Res::Local(hir_id) = path.res
2025 && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
2026 {
2027 match self.tcx.parent_hir_node(binding.hir_id) {
2028 hir::Node::LetStmt(local)
2030 if local.ty.is_none()
2031 && let Some(init) = local.init =>
2032 {
2033 expr = init;
2034 continue;
2035 }
2036 hir::Node::LetStmt(local)
2039 if #[allow(non_exhaustive_omitted_patterns)] match local.source {
hir::LocalSource::AsyncFn => true,
_ => false,
}matches!(local.source, hir::LocalSource::AsyncFn)
2040 && let Some(init) = local.init
2041 && let hir::ExprKind::Path(hir::QPath::Resolved(None, arg_path)) =
2042 init.kind
2043 && let Res::Local(arg_hir_id) = arg_path.res
2044 && let hir::Node::Pat(arg_binding) = self.tcx.hir_node(arg_hir_id)
2045 && let hir::Node::Param(param) =
2046 self.tcx.parent_hir_node(arg_binding.hir_id) =>
2047 {
2048 return (refs, Some(param));
2049 }
2050 hir::Node::Param(param) => {
2052 return (refs, Some(param));
2053 }
2054 _ => break 'outer,
2055 }
2056 } else {
2057 break 'outer;
2058 }
2059 }
2060 (refs, None)
2061 }
2062
2063 pub(super) fn suggest_remove_reference(
2066 &self,
2067 obligation: &PredicateObligation<'tcx>,
2068 err: &mut Diag<'_>,
2069 trait_pred: ty::PolyTraitPredicate<'tcx>,
2070 ) -> bool {
2071 let mut span = obligation.cause.span;
2072 let mut trait_pred = trait_pred;
2073 let mut code = obligation.cause.code();
2074 while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
2075 code = c;
2078 trait_pred = parent_trait_pred;
2079 }
2080 while span.desugaring_kind().is_some() {
2081 span.remove_mark();
2083 }
2084 let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
2085 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
2086 return false;
2087 };
2088 expr_finder.visit_expr(body.value);
2089 let mut maybe_suggest = |suggested_ty, count, suggestions| {
2090 let trait_pred_and_suggested_ty =
2092 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2093
2094 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2095 obligation.param_env,
2096 trait_pred_and_suggested_ty,
2097 );
2098
2099 if self.predicate_may_hold(&new_obligation) {
2100 let msg = if count == 1 {
2101 "consider removing the leading `&`-reference".to_string()
2102 } else {
2103 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
2104 };
2105
2106 err.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
2107 true
2108 } else {
2109 false
2110 }
2111 };
2112
2113 let mut count = 0;
2116 let mut suggestions = ::alloc::vec::Vec::new()vec![];
2117 let mut suggested_ty = trait_pred.self_ty().skip_binder();
2119 if let Some(mut hir_ty) = expr_finder.ty_result {
2120 while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
2121 count += 1;
2122 let span = hir_ty.span.until(mut_ty.ty.span);
2123 suggestions.push((span, String::new()));
2124
2125 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
2126 break;
2127 };
2128 suggested_ty = *inner_ty;
2129
2130 hir_ty = mut_ty.ty;
2131
2132 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
2133 return true;
2134 }
2135 }
2136 }
2137
2138 let Some(expr) = expr_finder.result else {
2140 return false;
2141 };
2142 let suggested_ty = trait_pred.self_ty().skip_binder();
2144 let (peeled_refs, _) = self.peel_expr_refs(expr, suggested_ty);
2145 for (i, peeled) in peeled_refs.iter().enumerate() {
2146 let suggestions: Vec<_> =
2147 peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2148 if maybe_suggest(peeled.peeled_ty, i + 1, suggestions) {
2149 return true;
2150 }
2151 }
2152 false
2153 }
2154
2155 fn suggest_remove_ref_from_param(&self, param: &hir::Param<'_>, err: &mut Diag<'_>) -> bool {
2157 if let Some(decl) = self.tcx.parent_hir_node(param.hir_id).fn_decl()
2158 && let Some(input_ty) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
2159 && let hir::TyKind::Ref(_, mut_ty) = input_ty.kind
2160 {
2161 let ref_span = input_ty.span.until(mut_ty.ty.span);
2162 match self.tcx.sess.source_map().span_to_snippet(ref_span) {
2163 Ok(snippet) if snippet.starts_with("&") => {
2164 err.span_suggestion_verbose(
2165 ref_span,
2166 "consider removing the `&` from the parameter type",
2167 "",
2168 Applicability::MaybeIncorrect,
2169 );
2170 return true;
2171 }
2172 _ => {}
2173 }
2174 }
2175 false
2176 }
2177
2178 pub(super) fn suggest_remove_await(
2179 &self,
2180 obligation: &PredicateObligation<'tcx>,
2181 err: &mut Diag<'_>,
2182 ) {
2183 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
2184 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2185 {
2186 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2194 obligation.predicate.kind().skip_binder()
2195 {
2196 let self_ty = pred.self_ty();
2197 let future_trait =
2198 self.tcx.require_lang_item(LangItem::Future, obligation.cause.span);
2199
2200 let has_future = {
2202 let mut ty = self_ty;
2203 loop {
2204 match *ty.kind() {
2205 ty::Ref(_, inner_ty, _)
2206 if !#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind() {
ty::Dynamic(..) => true,
_ => false,
}matches!(inner_ty.kind(), ty::Dynamic(..)) =>
2207 {
2208 if self
2209 .type_implements_trait(
2210 future_trait,
2211 [inner_ty],
2212 obligation.param_env,
2213 )
2214 .must_apply_modulo_regions()
2215 {
2216 break true;
2217 }
2218 ty = inner_ty;
2219 }
2220 _ => break false,
2221 }
2222 }
2223 };
2224
2225 if has_future {
2226 let (peeled_refs, terminal_param) = self.peel_expr_refs(expr, self_ty);
2227
2228 for (i, peeled) in peeled_refs.iter().enumerate() {
2230 if self
2231 .type_implements_trait(
2232 future_trait,
2233 [peeled.peeled_ty],
2234 obligation.param_env,
2235 )
2236 .must_apply_modulo_regions()
2237 {
2238 let count = i + 1;
2239 let msg = if count == 1 {
2240 "consider removing the leading `&`-reference".to_string()
2241 } else {
2242 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
2243 };
2244 let suggestions: Vec<_> =
2245 peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2246 err.multipart_suggestion(
2247 msg,
2248 suggestions,
2249 Applicability::MachineApplicable,
2250 );
2251 return;
2252 }
2253 }
2254
2255 if peeled_refs.is_empty()
2259 && let Some(param) = terminal_param
2260 && self.suggest_remove_ref_from_param(param, err)
2261 {
2262 return;
2263 }
2264
2265 err.help(
2267 "a reference to a future is not a future; \
2268 consider removing the leading `&`-reference",
2269 );
2270 return;
2271 }
2272 }
2273
2274 if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
2276 && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
2277 {
2278 let removal_span = self
2279 .tcx
2280 .sess
2281 .source_map()
2282 .span_extend_while_whitespace(expr_span)
2283 .shrink_to_hi()
2284 .to(await_expr.span.shrink_to_hi());
2285 err.span_suggestion_verbose(
2286 removal_span,
2287 "remove the `.await`",
2288 "",
2289 Applicability::MachineApplicable,
2290 );
2291 } else {
2292 err.span_label(obligation.cause.span, "remove the `.await`");
2293 }
2294 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
2296 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2297 obligation.predicate.kind().skip_binder()
2298 {
2299 err.span_label(*span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this call returns `{0}`",
pred.self_ty()))
})format!("this call returns `{}`", pred.self_ty()));
2300 }
2301 if let Some(typeck_results) = &self.typeck_results
2302 && let ty = typeck_results.expr_ty_adjusted(base)
2303 && let ty::FnDef(def_id, _args) = ty.kind()
2304 && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
2305 {
2306 let (ident, _, _, _) = item.expect_fn();
2307 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alternatively, consider making `fn {0}` asynchronous",
ident))
})format!("alternatively, consider making `fn {ident}` asynchronous");
2308 if item.vis_span.is_empty() {
2309 err.span_suggestion_verbose(
2310 item.span.shrink_to_lo(),
2311 msg,
2312 "async ",
2313 Applicability::MaybeIncorrect,
2314 );
2315 } else {
2316 err.span_suggestion_verbose(
2317 item.vis_span.shrink_to_hi(),
2318 msg,
2319 " async",
2320 Applicability::MaybeIncorrect,
2321 );
2322 }
2323 }
2324 }
2325 }
2326 }
2327
2328 pub(super) fn suggest_change_mut(
2331 &self,
2332 obligation: &PredicateObligation<'tcx>,
2333 err: &mut Diag<'_>,
2334 trait_pred: ty::PolyTraitPredicate<'tcx>,
2335 ) {
2336 let points_at_arg =
2337 #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
ObligationCauseCode::FunctionArg { .. } => true,
_ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
2338
2339 let span = obligation.cause.span;
2340 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2341 let refs_number =
2342 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
2343 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
2344 return;
2346 }
2347 let trait_pred = self.resolve_vars_if_possible(trait_pred);
2348 if trait_pred.has_non_region_infer() {
2349 return;
2352 }
2353
2354 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
2356 {
2357 let suggested_ty = match mutability {
2358 hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
2359 hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
2360 };
2361
2362 let trait_pred_and_suggested_ty =
2364 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2365
2366 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2367 obligation.param_env,
2368 trait_pred_and_suggested_ty,
2369 );
2370 let suggested_ty_would_satisfy_obligation = self
2371 .evaluate_obligation_no_overflow(&new_obligation)
2372 .must_apply_modulo_regions();
2373 if suggested_ty_would_satisfy_obligation {
2374 let sp = self
2375 .tcx
2376 .sess
2377 .source_map()
2378 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
2379 if points_at_arg && mutability.is_not() && refs_number > 0 {
2380 if snippet
2382 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
2383 .starts_with("mut")
2384 {
2385 return;
2386 }
2387 err.span_suggestion_verbose(
2388 sp,
2389 "consider changing this borrow's mutability",
2390 "&mut ",
2391 Applicability::MachineApplicable,
2392 );
2393 } else {
2394 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is implemented for `{1}`, but not for `{2}`",
trait_pred.print_modifiers_and_trait_path(), suggested_ty,
trait_pred.skip_binder().self_ty()))
})format!(
2395 "`{}` is implemented for `{}`, but not for `{}`",
2396 trait_pred.print_modifiers_and_trait_path(),
2397 suggested_ty,
2398 trait_pred.skip_binder().self_ty(),
2399 ));
2400 }
2401 }
2402 }
2403 }
2404 }
2405
2406 pub(super) fn suggest_semicolon_removal(
2407 &self,
2408 obligation: &PredicateObligation<'tcx>,
2409 err: &mut Diag<'_>,
2410 span: Span,
2411 trait_pred: ty::PolyTraitPredicate<'tcx>,
2412 ) -> bool {
2413 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
2414 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn {sig, body: body_id, .. }, .. }) = node
2415 && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
2416 && sig.decl.output.span().overlaps(span)
2417 && blk.expr.is_none()
2418 && trait_pred.self_ty().skip_binder().is_unit()
2419 && let Some(stmt) = blk.stmts.last()
2420 && let hir::StmtKind::Semi(expr) = stmt.kind
2421 && let Some(typeck_results) = &self.typeck_results
2423 && let Some(ty) = typeck_results.expr_ty_opt(expr)
2424 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
2425 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
2426 ))
2427 {
2428 err.span_label(
2429 expr.span,
2430 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this expression has type `{0}`, which implements `{1}`",
ty, trait_pred.print_modifiers_and_trait_path()))
})format!(
2431 "this expression has type `{}`, which implements `{}`",
2432 ty,
2433 trait_pred.print_modifiers_and_trait_path()
2434 ),
2435 );
2436 err.span_suggestion(
2437 self.tcx.sess.source_map().end_point(stmt.span),
2438 "remove this semicolon",
2439 "",
2440 Applicability::MachineApplicable,
2441 );
2442 return true;
2443 }
2444 false
2445 }
2446
2447 pub(super) fn suggest_borrow_for_unsized_closure_return<G: EmissionGuarantee>(
2448 &self,
2449 body_id: LocalDefId,
2450 err: &mut Diag<'_, G>,
2451 predicate: ty::Predicate<'tcx>,
2452 ) {
2453 let Some(pred) = predicate.as_trait_clause() else {
2454 return;
2455 };
2456 if !self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) {
2457 return;
2458 }
2459
2460 let Some(span) = err.span.primary_span() else {
2461 return;
2462 };
2463 let Some(node_body_id) = self.tcx.hir_node_by_def_id(body_id).body_id() else {
2464 return;
2465 };
2466 let body = self.tcx.hir_body(node_body_id);
2467 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2468 expr_finder.visit_expr(body.value);
2469 let Some(expr) = expr_finder.result else {
2470 return;
2471 };
2472
2473 let closure = match expr.kind {
2474 hir::ExprKind::Call(_, args) => args.iter().find_map(|arg| match arg.kind {
2475 hir::ExprKind::Closure(closure) => Some(closure),
2476 _ => None,
2477 }),
2478 hir::ExprKind::MethodCall(_, _, args, _) => {
2479 args.iter().find_map(|arg| match arg.kind {
2480 hir::ExprKind::Closure(closure) => Some(closure),
2481 _ => None,
2482 })
2483 }
2484 _ => None,
2485 };
2486 let Some(closure) = closure else {
2487 return;
2488 };
2489 if !#[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
hir::FnRetTy::DefaultReturn(_) => true,
_ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_)) {
2490 return;
2491 }
2492
2493 err.span_suggestion_verbose(
2494 self.tcx.hir_body(closure.body).value.span.shrink_to_lo(),
2495 "consider borrowing the value",
2496 "&",
2497 Applicability::MaybeIncorrect,
2498 );
2499 }
2500
2501 pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
2502 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
2503 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
2504 else {
2505 return None;
2506 };
2507
2508 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
2509 }
2510
2511 pub(super) fn suggest_impl_trait(
2515 &self,
2516 err: &mut Diag<'_>,
2517 obligation: &PredicateObligation<'tcx>,
2518 trait_pred: ty::PolyTraitPredicate<'tcx>,
2519 ) -> bool {
2520 let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
2521 return false;
2522 };
2523 let ty::Dynamic(_, _) = trait_pred.self_ty().skip_binder().kind() else {
2524 return false;
2525 };
2526 if let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2527 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2528 | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, _), .. }) =
2529 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
2530 && let hir::FnRetTy::Return(ty) = fn_sig.decl.output
2531 && let hir::TyKind::Path(qpath) = ty.kind
2532 && let hir::QPath::Resolved(None, path) = qpath
2533 && let Res::Def(DefKind::TyAlias, def_id) = path.res
2534 {
2535 err.span_note(self.tcx.def_span(def_id), "this type alias is unsized");
2539 err.multipart_suggestion(
2540 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider boxing the return type, and wrapping all of the returned values in `Box::new`"))
})format!(
2541 "consider boxing the return type, and wrapping all of the returned values in \
2542 `Box::new`",
2543 ),
2544 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ty.span.shrink_to_lo(), "Box<".to_string()),
(ty.span.shrink_to_hi(), ">".to_string())]))vec![
2545 (ty.span.shrink_to_lo(), "Box<".to_string()),
2546 (ty.span.shrink_to_hi(), ">".to_string()),
2547 ],
2548 Applicability::MaybeIncorrect,
2549 );
2550 return false;
2551 }
2552
2553 err.code(E0746);
2554 err.primary_message("return type cannot be a trait object without pointer indirection");
2555 err.children.clear();
2556
2557 let mut span = obligation.cause.span;
2558 if let DefKind::Closure = self.tcx.def_kind(obligation.cause.body_id)
2559 && let parent = self.tcx.local_parent(obligation.cause.body_id)
2560 && let DefKind::Fn | DefKind::AssocFn = self.tcx.def_kind(parent)
2561 && self.tcx.asyncness(parent).is_async()
2562 && let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2563 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2564 | Node::TraitItem(hir::TraitItem {
2565 kind: hir::TraitItemKind::Fn(fn_sig, _), ..
2566 }) = self.tcx.hir_node_by_def_id(parent)
2567 {
2568 span = fn_sig.decl.output.span();
2573 err.span(span);
2574 }
2575 let body = self.tcx.hir_body_owned_by(obligation.cause.body_id);
2576
2577 let mut visitor = ReturnsVisitor::default();
2578 visitor.visit_body(&body);
2579
2580 let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
2581 && snip.starts_with("dyn ")
2582 {
2583 ("", span.with_hi(span.lo() + BytePos(4)))
2584 } else {
2585 ("dyn ", span.shrink_to_lo())
2586 };
2587
2588 err.span_suggestion_verbose(
2589 impl_span,
2590 "consider returning an `impl Trait` instead of a `dyn Trait`",
2591 "impl ",
2592 Applicability::MaybeIncorrect,
2593 );
2594
2595 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Box<{0}", pre))
})), (span.shrink_to_hi(), ">".to_string())]))vec![
2596 (span.shrink_to_lo(), format!("Box<{pre}")),
2597 (span.shrink_to_hi(), ">".to_string()),
2598 ];
2599 sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
2600 let span =
2601 expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
2602 if !span.can_be_used_for_suggestions() {
2603 ::alloc::vec::Vec::new()vec![]
2604 } else if let hir::ExprKind::Call(path, ..) = expr.kind
2605 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
2606 && method.ident.name == sym::new
2607 && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
2608 && box_path
2609 .res
2610 .opt_def_id()
2611 .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
2612 {
2613 ::alloc::vec::Vec::new()vec![]
2615 } else {
2616 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "Box::new(".to_string()),
(span.shrink_to_hi(), ")".to_string())]))vec![
2617 (span.shrink_to_lo(), "Box::new(".to_string()),
2618 (span.shrink_to_hi(), ")".to_string()),
2619 ]
2620 }
2621 }));
2622
2623 err.multipart_suggestion(
2624 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alternatively, box the return type, and wrap all of the returned values in `Box::new`"))
})format!(
2625 "alternatively, box the return type, and wrap all of the returned values in \
2626 `Box::new`",
2627 ),
2628 sugg,
2629 Applicability::MaybeIncorrect,
2630 );
2631
2632 true
2633 }
2634
2635 pub(super) fn report_closure_arg_mismatch(
2636 &self,
2637 span: Span,
2638 found_span: Option<Span>,
2639 found: ty::TraitRef<'tcx>,
2640 expected: ty::TraitRef<'tcx>,
2641 cause: &ObligationCauseCode<'tcx>,
2642 found_node: Option<Node<'_>>,
2643 param_env: ty::ParamEnv<'tcx>,
2644 ) -> Diag<'a> {
2645 pub(crate) fn build_fn_sig_ty<'tcx>(
2646 infcx: &InferCtxt<'tcx>,
2647 trait_ref: ty::TraitRef<'tcx>,
2648 ) -> Ty<'tcx> {
2649 let inputs = trait_ref.args.type_at(1);
2650 let sig = match inputs.kind() {
2651 ty::Tuple(inputs) if infcx.tcx.is_callable_trait(trait_ref.def_id) => {
2652 infcx.tcx.mk_fn_sig_safe_rust_abi(*inputs, infcx.next_ty_var(DUMMY_SP))
2653 }
2654 _ => infcx.tcx.mk_fn_sig_safe_rust_abi([inputs], infcx.next_ty_var(DUMMY_SP)),
2655 };
2656
2657 Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
2658 }
2659
2660 let argument_kind = match expected.self_ty().kind() {
2661 ty::Closure(..) => "closure",
2662 ty::Coroutine(..) => "coroutine",
2663 _ => "function",
2664 };
2665 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type mismatch in {0} arguments",
argument_kind))
})).with_code(E0631)
}struct_span_code_err!(
2666 self.dcx(),
2667 span,
2668 E0631,
2669 "type mismatch in {argument_kind} arguments",
2670 );
2671
2672 err.span_label(span, "expected due to this");
2673
2674 let found_span = found_span.unwrap_or(span);
2675 err.span_label(found_span, "found signature defined here");
2676
2677 let expected = build_fn_sig_ty(self, expected);
2678 let found = build_fn_sig_ty(self, found);
2679
2680 let (expected_str, found_str) = self.cmp(expected, found);
2681
2682 let signature_kind = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} signature", argument_kind))
})format!("{argument_kind} signature");
2683 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2684
2685 self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
2686 self.note_conflicting_closure_bounds(cause, &mut err);
2687
2688 if let Some(found_node) = found_node {
2689 hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
2690 }
2691
2692 err
2693 }
2694
2695 fn note_conflicting_fn_args(
2696 &self,
2697 err: &mut Diag<'_>,
2698 cause: &ObligationCauseCode<'tcx>,
2699 expected: Ty<'tcx>,
2700 found: Ty<'tcx>,
2701 param_env: ty::ParamEnv<'tcx>,
2702 ) {
2703 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
2704 return;
2705 };
2706 let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
2707 return;
2708 };
2709 let expected = sig_tys.with(*hdr);
2710 let ty::FnPtr(sig_tys, hdr) = found.kind() else {
2711 return;
2712 };
2713 let found = sig_tys.with(*hdr);
2714 let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
2715 return;
2716 };
2717 let hir::ExprKind::Path(path) = arg.kind else {
2718 return;
2719 };
2720 let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
2721 let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
2722 let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
2723
2724 let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
2725 let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
2726 let (found_ty, found_refs) = get_deref_type_and_refs(found);
2727
2728 if infcx.can_eq(param_env, found_ty, expected_ty) {
2729 if found_refs.len() == expected_refs.len()
2730 && found_refs.iter().eq(expected_refs.iter())
2731 {
2732 name
2733 } else if found_refs.len() > expected_refs.len() {
2734 let refs = &found_refs[..found_refs.len() - expected_refs.len()];
2735 if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
2736 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
refs.iter().map(|mutbl|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}",
mutbl.prefix_str()))
})).collect::<Vec<_>>().join(""), name))
})format!(
2737 "{}{name}",
2738 refs.iter()
2739 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2740 .collect::<Vec<_>>()
2741 .join(""),
2742 )
2743 } else {
2744 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}*{1}",
refs.iter().map(|mutbl|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}",
mutbl.prefix_str()))
})).collect::<Vec<_>>().join(""), name))
})format!(
2746 "{}*{name}",
2747 refs.iter()
2748 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2749 .collect::<Vec<_>>()
2750 .join(""),
2751 )
2752 }
2753 } else if expected_refs.len() > found_refs.len() {
2754 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
(0..(expected_refs.len() -
found_refs.len())).map(|_|
"*").collect::<Vec<_>>().join(""), name))
})format!(
2755 "{}{name}",
2756 (0..(expected_refs.len() - found_refs.len()))
2757 .map(|_| "*")
2758 .collect::<Vec<_>>()
2759 .join(""),
2760 )
2761 } else {
2762 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
found_refs.iter().map(|mutbl|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}",
mutbl.prefix_str()))
})).chain(found_refs.iter().map(|_|
"*".to_string())).collect::<Vec<_>>().join(""), name))
})format!(
2763 "{}{name}",
2764 found_refs
2765 .iter()
2766 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2767 .chain(found_refs.iter().map(|_| "*".to_string()))
2768 .collect::<Vec<_>>()
2769 .join(""),
2770 )
2771 }
2772 } else {
2773 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", found))
})format!("/* {found} */")
2774 }
2775 };
2776 let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
2777 let (expected_ty, _) = get_deref_type_and_refs(expected);
2778 let (found_ty, _) = get_deref_type_and_refs(found);
2779 self.can_eq(param_env, found_ty, expected_ty)
2780 });
2781 let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
2782 && !expected_inputs.is_empty()
2783 && expected_inputs.len() == found_inputs.len()
2784 && let Some(typeck) = &self.typeck_results
2785 && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
2786 && res_kind.is_fn_like()
2787 {
2788 let closure: Vec<_> = self
2789 .tcx
2790 .fn_arg_idents(fn_def_id)
2791 .iter()
2792 .enumerate()
2793 .map(|(i, ident)| {
2794 if let Some(ident) = ident
2795 && !#[allow(non_exhaustive_omitted_patterns)] match ident {
Ident { name: kw::Underscore | kw::SelfLower, .. } => true,
_ => false,
}matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
2796 {
2797 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}")
2798 } else {
2799 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}")
2800 }
2801 })
2802 .collect();
2803 let args = closure
2804 .iter()
2805 .zip(both_tys)
2806 .map(|(name, (expected, found))| {
2807 arg_expr(self.infcx, name.to_owned(), expected, found)
2808 })
2809 .collect();
2810 (closure, args)
2811 } else {
2812 let closure_args = expected_inputs
2813 .iter()
2814 .enumerate()
2815 .map(|(i, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"))
2816 .collect::<Vec<_>>();
2817 let call_args = both_tys
2818 .enumerate()
2819 .map(|(i, (expected, found))| {
2820 arg_expr(self.infcx, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"), expected, found)
2821 })
2822 .collect::<Vec<_>>();
2823 (closure_args, call_args)
2824 };
2825 let closure_names: Vec<_> = closure_names
2826 .into_iter()
2827 .zip(expected_inputs.iter())
2828 .map(|(name, ty)| {
2829 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}",
if ty.has_infer_types() {
String::new()
} else if ty.references_error() {
": /* type */".to_string()
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", ty))
})
}, name))
})format!(
2830 "{name}{}",
2831 if ty.has_infer_types() {
2832 String::new()
2833 } else if ty.references_error() {
2834 ": /* type */".to_string()
2835 } else {
2836 format!(": {ty}")
2837 }
2838 )
2839 })
2840 .collect();
2841 err.multipart_suggestion(
2842 "consider wrapping the function in a closure",
2843 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(arg.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}| ",
closure_names.join(", ")))
})),
(arg.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})",
call_names.join(", ")))
}))]))vec![
2844 (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
2845 (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
2846 ],
2847 Applicability::MaybeIncorrect,
2848 );
2849 }
2850
2851 fn note_conflicting_closure_bounds(
2854 &self,
2855 cause: &ObligationCauseCode<'tcx>,
2856 err: &mut Diag<'_>,
2857 ) {
2858 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *cause
2862 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2863 && let Some(pred) = predicates.predicates.get(idx).map(|p| p.as_ref().skip_norm_wip())
2864 && let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
2865 && self.tcx.is_fn_trait(trait_pred.def_id())
2866 {
2867 let expected_self =
2868 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2869 let expected_args =
2870 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.args));
2871
2872 let other_pred = predicates.into_iter().enumerate().find(|&(other_idx, (pred, _))| {
2875 let pred = pred.skip_norm_wip();
2876 match pred.kind().skip_binder() {
2877 ty::ClauseKind::Trait(trait_pred)
2878 if self.tcx.is_fn_trait(trait_pred.def_id())
2879 && other_idx != idx
2880 && expected_self
2883 == self.tcx.anonymize_bound_vars(
2884 pred.kind().rebind(trait_pred.self_ty()),
2885 )
2886 && expected_args
2888 != self.tcx.anonymize_bound_vars(
2889 pred.kind().rebind(trait_pred.trait_ref.args),
2890 ) =>
2891 {
2892 true
2893 }
2894 _ => false,
2895 }
2896 });
2897 if let Some((_, (_, other_pred_span))) = other_pred {
2899 err.span_note(
2900 other_pred_span,
2901 "closure inferred to have a different signature due to this bound",
2902 );
2903 }
2904 }
2905 }
2906
2907 pub(super) fn suggest_fully_qualified_path(
2908 &self,
2909 err: &mut Diag<'_>,
2910 item_def_id: DefId,
2911 span: Span,
2912 trait_ref: DefId,
2913 ) {
2914 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
2915 && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
2916 {
2917 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}s cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl`",
self.tcx.def_kind_descr(assoc_item.as_def_kind(),
item_def_id)))
})format!(
2918 "{}s cannot be accessed directly on a `trait`, they can only be \
2919 accessed through a specific `impl`",
2920 self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
2921 ));
2922
2923 if !assoc_item.is_impl_trait_in_trait() {
2924 err.span_suggestion_verbose(
2925 span,
2926 "use the fully qualified path to an implementation",
2927 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
self.tcx.def_path_str(trait_ref), assoc_item.name()))
})format!(
2928 "<Type as {}>::{}",
2929 self.tcx.def_path_str(trait_ref),
2930 assoc_item.name()
2931 ),
2932 Applicability::HasPlaceholders,
2933 );
2934 }
2935 }
2936 }
2937
2938 #[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("maybe_note_obligation_cause_for_async_await",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2980u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["obligation.predicate",
"obligation.cause.span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&obligation.predicate)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&obligation.cause.span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
let (mut trait_ref, mut target_ty) =
match obligation.predicate.kind().skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) =>
(Some(p), Some(p.self_ty())),
_ => (None, None),
};
let mut coroutine = None;
let mut outer_coroutine = None;
let mut next_code = Some(obligation.cause.code());
let mut seen_upvar_tys_infer_tuple = false;
while let Some(code) = next_code {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3019",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3019u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["code"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&code) as
&dyn Value))])
});
} else { ; }
};
match code {
ObligationCauseCode::FunctionArg { parent_code, .. } => {
next_code = Some(parent_code);
}
ObligationCauseCode::ImplDerived(cause) => {
let ty =
cause.derived.parent_trait_pred.skip_binder().self_ty();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3026",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3026u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
"parent_trait_ref", "self_ty.kind"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ImplDerived")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&cause.derived.parent_trait_pred)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty.kind())
as &dyn Value))])
});
} else { ; }
};
match *ty.kind() {
ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
coroutine = coroutine.or(Some(did));
outer_coroutine = Some(did);
}
ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
seen_upvar_tys_infer_tuple = true;
}
_ if coroutine.is_none() => {
trait_ref =
Some(cause.derived.parent_trait_pred.skip_binder());
target_ty = Some(ty);
}
_ => {}
}
next_code = Some(&cause.derived.parent_code);
}
ObligationCauseCode::WellFormedDerived(derived_obligation) |
ObligationCauseCode::BuiltinDerived(derived_obligation) => {
let ty =
derived_obligation.parent_trait_pred.skip_binder().self_ty();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3056",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3056u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["parent_trait_ref",
"self_ty.kind"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&derived_obligation.parent_trait_pred)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty.kind())
as &dyn Value))])
});
} else { ; }
};
match *ty.kind() {
ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
coroutine = coroutine.or(Some(did));
outer_coroutine = Some(did);
}
ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
seen_upvar_tys_infer_tuple = true;
}
_ if coroutine.is_none() => {
trait_ref =
Some(derived_obligation.parent_trait_pred.skip_binder());
target_ty = Some(ty);
}
_ => {}
}
next_code = Some(&derived_obligation.parent_code);
}
_ => break,
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3087",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3087u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["coroutine",
"trait_ref", "target_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_ref)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&target_ty)
as &dyn Value))])
});
} else { ; }
};
let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
(coroutine, trait_ref, target_ty) else { return false; };
let span = self.tcx.def_span(coroutine_did);
let coroutine_did_root =
self.tcx.typeck_root_def_id(coroutine_did);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3097",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3097u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["coroutine_did",
"coroutine_did_root", "typeck_results.hir_owner", "span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine_did)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine_did_root)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.typeck_results.as_ref().map(|t|
t.hir_owner)) as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&span) as
&dyn Value))])
});
} else { ; }
};
let coroutine_body =
coroutine_did.as_local().and_then(|def_id|
self.tcx.hir_maybe_body_owned_by(def_id));
let mut visitor = AwaitsVisitor::default();
if let Some(body) = coroutine_body { visitor.visit_body(&body); }
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3110",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3110u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["awaits"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&visitor.awaits)
as &dyn Value))])
});
} else { ; }
};
let target_ty_erased =
self.tcx.erase_and_anonymize_regions(target_ty);
let ty_matches =
|ty| -> bool
{
let ty_erased =
self.tcx.instantiate_bound_regions_with_erased(ty);
let ty_erased =
self.tcx.erase_and_anonymize_regions(ty_erased);
let eq = ty_erased == target_ty_erased;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3131",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3131u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["ty_erased",
"target_ty_erased", "eq"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty_erased)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&target_ty_erased)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&eq) as
&dyn Value))])
});
} else { ; }
};
eq
};
let coroutine_data =
match &self.typeck_results {
Some(t) if t.hir_owner.to_def_id() == coroutine_did_root =>
CoroutineData(t),
_ if coroutine_did.is_local() => {
CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
}
_ => return false,
};
let coroutine_within_in_progress_typeck =
match &self.typeck_results {
Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
_ => false,
};
let mut interior_or_upvar_span = None;
let from_awaited_ty =
coroutine_data.get_from_await_ty(visitor, self.tcx,
ty_matches);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3155",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3155u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["from_awaited_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&from_awaited_ty)
as &dyn Value))])
});
} else { ; }
};
if coroutine_did.is_local() &&
!coroutine_within_in_progress_typeck &&
let Some(coroutine_info) =
self.tcx.mir_coroutine_witnesses(coroutine_did) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3163",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3163u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["coroutine_info"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine_info)
as &dyn Value))])
});
} else { ; }
};
'find_source:
for (variant, source_info) in
coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3167",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3167u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["variant"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&variant) as
&dyn Value))])
});
} else { ; }
};
for &local in variant {
let decl = &coroutine_info.field_tys[local];
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3170",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3170u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["decl"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&decl) as
&dyn Value))])
});
} else { ; }
};
if ty_matches(ty::Binder::dummy(decl.ty)) &&
!decl.ignore_for_traits {
interior_or_upvar_span =
Some(CoroutineInteriorOrUpvar::Interior(decl.source_info.span,
Some((source_info.span, from_awaited_ty))));
break 'find_source;
}
}
}
}
if interior_or_upvar_span.is_none() {
interior_or_upvar_span =
coroutine_data.try_get_upvar_span(self, coroutine_did,
ty_matches);
}
if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
interior_or_upvar_span =
Some(CoroutineInteriorOrUpvar::Interior(span, None));
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3191",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3191u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["interior_or_upvar_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&interior_or_upvar_span)
as &dyn Value))])
});
} else { ; }
};
if let Some(interior_or_upvar_span) = interior_or_upvar_span {
let is_async = self.tcx.coroutine_is_async(coroutine_did);
self.note_obligation_cause_for_async_await(err,
interior_or_upvar_span, is_async, outer_coroutine,
trait_ref, target_ty, obligation, next_code);
true
} else { false }
}
}
}#[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2981 pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2982 &self,
2983 err: &mut Diag<'_, G>,
2984 obligation: &PredicateObligation<'tcx>,
2985 ) -> bool {
2986 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
3009 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
3010 _ => (None, None),
3011 };
3012 let mut coroutine = None;
3013 let mut outer_coroutine = None;
3014 let mut next_code = Some(obligation.cause.code());
3015
3016 let mut seen_upvar_tys_infer_tuple = false;
3017
3018 while let Some(code) = next_code {
3019 debug!(?code);
3020 match code {
3021 ObligationCauseCode::FunctionArg { parent_code, .. } => {
3022 next_code = Some(parent_code);
3023 }
3024 ObligationCauseCode::ImplDerived(cause) => {
3025 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
3026 debug!(
3027 parent_trait_ref = ?cause.derived.parent_trait_pred,
3028 self_ty.kind = ?ty.kind(),
3029 "ImplDerived",
3030 );
3031
3032 match *ty.kind() {
3033 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
3034 coroutine = coroutine.or(Some(did));
3035 outer_coroutine = Some(did);
3036 }
3037 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3038 seen_upvar_tys_infer_tuple = true;
3043 }
3044 _ if coroutine.is_none() => {
3045 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
3046 target_ty = Some(ty);
3047 }
3048 _ => {}
3049 }
3050
3051 next_code = Some(&cause.derived.parent_code);
3052 }
3053 ObligationCauseCode::WellFormedDerived(derived_obligation)
3054 | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
3055 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
3056 debug!(
3057 parent_trait_ref = ?derived_obligation.parent_trait_pred,
3058 self_ty.kind = ?ty.kind(),
3059 );
3060
3061 match *ty.kind() {
3062 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
3063 coroutine = coroutine.or(Some(did));
3064 outer_coroutine = Some(did);
3065 }
3066 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3067 seen_upvar_tys_infer_tuple = true;
3072 }
3073 _ if coroutine.is_none() => {
3074 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
3075 target_ty = Some(ty);
3076 }
3077 _ => {}
3078 }
3079
3080 next_code = Some(&derived_obligation.parent_code);
3081 }
3082 _ => break,
3083 }
3084 }
3085
3086 debug!(?coroutine, ?trait_ref, ?target_ty);
3088 let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
3089 (coroutine, trait_ref, target_ty)
3090 else {
3091 return false;
3092 };
3093
3094 let span = self.tcx.def_span(coroutine_did);
3095
3096 let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
3097 debug!(
3098 ?coroutine_did,
3099 ?coroutine_did_root,
3100 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
3101 ?span,
3102 );
3103
3104 let coroutine_body =
3105 coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
3106 let mut visitor = AwaitsVisitor::default();
3107 if let Some(body) = coroutine_body {
3108 visitor.visit_body(&body);
3109 }
3110 debug!(awaits = ?visitor.awaits);
3111
3112 let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
3115 let ty_matches = |ty| -> bool {
3116 let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
3129 let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
3130 let eq = ty_erased == target_ty_erased;
3131 debug!(?ty_erased, ?target_ty_erased, ?eq);
3132 eq
3133 };
3134
3135 let coroutine_data = match &self.typeck_results {
3140 Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
3141 _ if coroutine_did.is_local() => {
3142 CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
3143 }
3144 _ => return false,
3145 };
3146
3147 let coroutine_within_in_progress_typeck = match &self.typeck_results {
3148 Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
3149 _ => false,
3150 };
3151
3152 let mut interior_or_upvar_span = None;
3153
3154 let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
3155 debug!(?from_awaited_ty);
3156
3157 if coroutine_did.is_local()
3159 && !coroutine_within_in_progress_typeck
3161 && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
3162 {
3163 debug!(?coroutine_info);
3164 'find_source: for (variant, source_info) in
3165 coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
3166 {
3167 debug!(?variant);
3168 for &local in variant {
3169 let decl = &coroutine_info.field_tys[local];
3170 debug!(?decl);
3171 if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
3172 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
3173 decl.source_info.span,
3174 Some((source_info.span, from_awaited_ty)),
3175 ));
3176 break 'find_source;
3177 }
3178 }
3179 }
3180 }
3181
3182 if interior_or_upvar_span.is_none() {
3183 interior_or_upvar_span =
3184 coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
3185 }
3186
3187 if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
3188 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
3189 }
3190
3191 debug!(?interior_or_upvar_span);
3192 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
3193 let is_async = self.tcx.coroutine_is_async(coroutine_did);
3194 self.note_obligation_cause_for_async_await(
3195 err,
3196 interior_or_upvar_span,
3197 is_async,
3198 outer_coroutine,
3199 trait_ref,
3200 target_ty,
3201 obligation,
3202 next_code,
3203 );
3204 true
3205 } else {
3206 false
3207 }
3208 }
3209
3210 #[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("note_obligation_cause_for_async_await",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3212u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let source_map = self.tcx.sess.source_map();
let (await_or_yield, an_await_or_yield) =
if is_async {
("await", "an await")
} else { ("yield", "a yield") };
let future_or_coroutine =
if is_async { "future" } else { "coroutine" };
let trait_explanation =
if let Some(name @ (sym::Send | sym::Sync)) =
self.tcx.get_diagnostic_name(trait_pred.def_id()) {
let (trait_name, trait_verb) =
if name == sym::Send {
("`Send`", "sent")
} else { ("`Sync`", "shared") };
err.code = None;
err.primary_message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} cannot be {1} between threads safely",
future_or_coroutine, trait_verb))
}));
let original_span = err.span.primary_span().unwrap();
let mut span = MultiSpan::from_span(original_span);
let message =
outer_coroutine.and_then(|coroutine_did|
{
Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
CoroutineKind::Coroutine(_) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("coroutine is not {0}",
trait_name))
}),
CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Fn) =>
self.tcx.parent(coroutine_did).as_local().map(|parent_did|
self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
self.tcx.hir_opt_name(parent_hir_id)).map(|name|
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future returned by `{0}` is not {1}",
name, trait_name))
})
})?,
CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Block) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future created by async block is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Closure) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future created by async closure is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
CoroutineSource::Fn) =>
self.tcx.parent(coroutine_did).as_local().map(|parent_did|
self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
self.tcx.hir_opt_name(parent_hir_id)).map(|name|
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("async iterator returned by `{0}` is not {1}",
name, trait_name))
})
})?,
CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
CoroutineSource::Block) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("async iterator created by async gen block is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
CoroutineSource::Closure) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("async iterator created by async gen closure is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::Gen,
CoroutineSource::Fn) => {
self.tcx.parent(coroutine_did).as_local().map(|parent_did|
self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
self.tcx.hir_opt_name(parent_hir_id)).map(|name|
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("iterator returned by `{0}` is not {1}",
name, trait_name))
})
})?
}
CoroutineKind::Desugared(CoroutineDesugaring::Gen,
CoroutineSource::Block) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("iterator created by gen block is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::Gen,
CoroutineSource::Closure) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("iterator created by gen closure is not {0}",
trait_name))
})
}
})
}).unwrap_or_else(||
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not {1}",
future_or_coroutine, trait_name))
}));
span.push_span_label(original_span, message);
err.span(span);
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("is not {0}", trait_name))
})
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("does not implement `{0}`",
trait_pred.print_modifiers_and_trait_path()))
})
};
let mut explain_yield =
|interior_span: Span, yield_span: Span|
{
let mut span = MultiSpan::from_span(yield_span);
let snippet =
match source_map.span_to_snippet(interior_span) {
Ok(snippet) if !snippet.contains('\n') =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", snippet))
}),
_ => "the value".to_string(),
};
span.push_span_label(yield_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} occurs here, with {1} maybe used later",
await_or_yield, snippet))
}));
span.push_span_label(interior_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}` which {1}",
target_ty, trait_explanation))
}));
err.span_note(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1} as this value is used across {2}",
future_or_coroutine, trait_explanation, an_await_or_yield))
}));
};
match interior_or_upvar_span {
CoroutineInteriorOrUpvar::Interior(interior_span,
interior_extra_info) => {
if let Some((yield_span, from_awaited_ty)) =
interior_extra_info {
if let Some(await_span) = from_awaited_ty {
let mut span = MultiSpan::from_span(await_span);
span.push_span_label(await_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("await occurs here on type `{0}`, which {1}",
target_ty, trait_explanation))
}));
err.span_note(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future {0} as it awaits another future which {0}",
trait_explanation))
}));
} else { explain_yield(interior_span, yield_span); }
}
}
CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
let non_send =
match target_ty.kind() {
ty::Ref(_, ref_ty, mutability) =>
match self.evaluate_obligation(obligation) {
Ok(eval) if !eval.may_apply() =>
Some((ref_ty, mutability.is_mut())),
_ => None,
},
_ => None,
};
let (span_label, span_note) =
match non_send {
Some((ref_ty, is_mut)) => {
let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
let ref_kind = if is_mut { "&mut" } else { "&" };
(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}` which {1}, because `{2}` is not `{3}`",
target_ty, trait_explanation, ref_ty, ref_ty_trait))
}),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("captured value {0} because `{1}` references cannot be sent unless their referent is `{2}`",
trait_explanation, ref_kind, ref_ty_trait))
}))
}
None =>
(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}` which {1}",
target_ty, trait_explanation))
}),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("captured value {0}",
trait_explanation))
})),
};
let mut span = MultiSpan::from_span(upvar_span);
span.push_span_label(upvar_span, span_label);
err.span_note(span, span_note);
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3435",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3435u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["next_code"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&next_code)
as &dyn Value))])
});
} else { ; }
};
self.note_obligation_cause_code(obligation.cause.body_id, err,
obligation.predicate, obligation.param_env,
next_code.unwrap(), &mut Vec::new(), &mut Default::default());
}
}
}#[instrument(level = "debug", skip_all)]
3213 fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
3214 &self,
3215 err: &mut Diag<'_, G>,
3216 interior_or_upvar_span: CoroutineInteriorOrUpvar,
3217 is_async: bool,
3218 outer_coroutine: Option<DefId>,
3219 trait_pred: ty::TraitPredicate<'tcx>,
3220 target_ty: Ty<'tcx>,
3221 obligation: &PredicateObligation<'tcx>,
3222 next_code: Option<&ObligationCauseCode<'tcx>>,
3223 ) {
3224 let source_map = self.tcx.sess.source_map();
3225
3226 let (await_or_yield, an_await_or_yield) =
3227 if is_async { ("await", "an await") } else { ("yield", "a yield") };
3228 let future_or_coroutine = if is_async { "future" } else { "coroutine" };
3229
3230 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
3233 self.tcx.get_diagnostic_name(trait_pred.def_id())
3234 {
3235 let (trait_name, trait_verb) =
3236 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
3237
3238 err.code = None;
3239 err.primary_message(format!(
3240 "{future_or_coroutine} cannot be {trait_verb} between threads safely"
3241 ));
3242
3243 let original_span = err.span.primary_span().unwrap();
3244 let mut span = MultiSpan::from_span(original_span);
3245
3246 let message = outer_coroutine
3247 .and_then(|coroutine_did| {
3248 Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
3249 CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
3250 CoroutineKind::Desugared(
3251 CoroutineDesugaring::Async,
3252 CoroutineSource::Fn,
3253 ) => self
3254 .tcx
3255 .parent(coroutine_did)
3256 .as_local()
3257 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3258 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3259 .map(|name| {
3260 format!("future returned by `{name}` is not {trait_name}")
3261 })?,
3262 CoroutineKind::Desugared(
3263 CoroutineDesugaring::Async,
3264 CoroutineSource::Block,
3265 ) => {
3266 format!("future created by async block is not {trait_name}")
3267 }
3268 CoroutineKind::Desugared(
3269 CoroutineDesugaring::Async,
3270 CoroutineSource::Closure,
3271 ) => {
3272 format!("future created by async closure is not {trait_name}")
3273 }
3274 CoroutineKind::Desugared(
3275 CoroutineDesugaring::AsyncGen,
3276 CoroutineSource::Fn,
3277 ) => self
3278 .tcx
3279 .parent(coroutine_did)
3280 .as_local()
3281 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3282 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3283 .map(|name| {
3284 format!("async iterator returned by `{name}` is not {trait_name}")
3285 })?,
3286 CoroutineKind::Desugared(
3287 CoroutineDesugaring::AsyncGen,
3288 CoroutineSource::Block,
3289 ) => {
3290 format!("async iterator created by async gen block is not {trait_name}")
3291 }
3292 CoroutineKind::Desugared(
3293 CoroutineDesugaring::AsyncGen,
3294 CoroutineSource::Closure,
3295 ) => {
3296 format!(
3297 "async iterator created by async gen closure is not {trait_name}"
3298 )
3299 }
3300 CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
3301 self.tcx
3302 .parent(coroutine_did)
3303 .as_local()
3304 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3305 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3306 .map(|name| {
3307 format!("iterator returned by `{name}` is not {trait_name}")
3308 })?
3309 }
3310 CoroutineKind::Desugared(
3311 CoroutineDesugaring::Gen,
3312 CoroutineSource::Block,
3313 ) => {
3314 format!("iterator created by gen block is not {trait_name}")
3315 }
3316 CoroutineKind::Desugared(
3317 CoroutineDesugaring::Gen,
3318 CoroutineSource::Closure,
3319 ) => {
3320 format!("iterator created by gen closure is not {trait_name}")
3321 }
3322 })
3323 })
3324 .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
3325
3326 span.push_span_label(original_span, message);
3327 err.span(span);
3328
3329 format!("is not {trait_name}")
3330 } else {
3331 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
3332 };
3333
3334 let mut explain_yield = |interior_span: Span, yield_span: Span| {
3335 let mut span = MultiSpan::from_span(yield_span);
3336 let snippet = match source_map.span_to_snippet(interior_span) {
3337 Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
3340 _ => "the value".to_string(),
3341 };
3342 span.push_span_label(
3359 yield_span,
3360 format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
3361 );
3362 span.push_span_label(
3363 interior_span,
3364 format!("has type `{target_ty}` which {trait_explanation}"),
3365 );
3366 err.span_note(
3367 span,
3368 format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
3369 );
3370 };
3371 match interior_or_upvar_span {
3372 CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
3373 if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
3374 if let Some(await_span) = from_awaited_ty {
3375 let mut span = MultiSpan::from_span(await_span);
3377 span.push_span_label(
3378 await_span,
3379 format!(
3380 "await occurs here on type `{target_ty}`, which {trait_explanation}"
3381 ),
3382 );
3383 err.span_note(
3384 span,
3385 format!(
3386 "future {trait_explanation} as it awaits another future which {trait_explanation}"
3387 ),
3388 );
3389 } else {
3390 explain_yield(interior_span, yield_span);
3392 }
3393 }
3394 }
3395 CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
3396 let non_send = match target_ty.kind() {
3398 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
3399 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
3400 _ => None,
3401 },
3402 _ => None,
3403 };
3404
3405 let (span_label, span_note) = match non_send {
3406 Some((ref_ty, is_mut)) => {
3410 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
3411 let ref_kind = if is_mut { "&mut" } else { "&" };
3412 (
3413 format!(
3414 "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
3415 ),
3416 format!(
3417 "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
3418 ),
3419 )
3420 }
3421 None => (
3422 format!("has type `{target_ty}` which {trait_explanation}"),
3423 format!("captured value {trait_explanation}"),
3424 ),
3425 };
3426
3427 let mut span = MultiSpan::from_span(upvar_span);
3428 span.push_span_label(upvar_span, span_label);
3429 err.span_note(span, span_note);
3430 }
3431 }
3432
3433 debug!(?next_code);
3436 self.note_obligation_cause_code(
3437 obligation.cause.body_id,
3438 err,
3439 obligation.predicate,
3440 obligation.param_env,
3441 next_code.unwrap(),
3442 &mut Vec::new(),
3443 &mut Default::default(),
3444 );
3445 }
3446
3447 pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
3448 &self,
3449 body_id: LocalDefId,
3450 err: &mut Diag<'_, G>,
3451 predicate: T,
3452 param_env: ty::ParamEnv<'tcx>,
3453 cause_code: &ObligationCauseCode<'tcx>,
3454 obligated_types: &mut Vec<Ty<'tcx>>,
3455 seen_requirements: &mut FxHashSet<DefId>,
3456 ) where
3457 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3458 {
3459 let tcx = self.tcx;
3460 let predicate = predicate.upcast(tcx);
3461 let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
3462 if let Some(pred) = predicate.as_trait_clause()
3463 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3464 && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
3465 {
3466 err.span_suggestion_verbose(
3467 expr.span.until(inner.span),
3468 "references are always `Sized`, even if they point to unsized data; consider \
3469 not dereferencing the expression",
3470 String::new(),
3471 Applicability::MaybeIncorrect,
3472 );
3473 }
3474 };
3475 match *cause_code {
3476 ObligationCauseCode::ExprAssignable
3477 | ObligationCauseCode::MatchExpressionArm { .. }
3478 | ObligationCauseCode::Pattern { .. }
3479 | ObligationCauseCode::IfExpression { .. }
3480 | ObligationCauseCode::IfExpressionWithNoElse
3481 | ObligationCauseCode::MainFunctionType
3482 | ObligationCauseCode::LangFunctionType(_)
3483 | ObligationCauseCode::IntrinsicType
3484 | ObligationCauseCode::MethodReceiver
3485 | ObligationCauseCode::ReturnNoExpression
3486 | ObligationCauseCode::Misc
3487 | ObligationCauseCode::WellFormed(..)
3488 | ObligationCauseCode::MatchImpl(..)
3489 | ObligationCauseCode::ReturnValue(_)
3490 | ObligationCauseCode::BlockTailExpression(..)
3491 | ObligationCauseCode::AwaitableExpr(_)
3492 | ObligationCauseCode::ForLoopIterator
3493 | ObligationCauseCode::QuestionMark
3494 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
3495 | ObligationCauseCode::LetElse
3496 | ObligationCauseCode::UnOp { .. }
3497 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
3498 | ObligationCauseCode::AlwaysApplicableImpl
3499 | ObligationCauseCode::ConstParam(_)
3500 | ObligationCauseCode::ReferenceOutlivesReferent(..)
3501 | ObligationCauseCode::ObjectTypeBound(..) => {}
3502 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
3503 if let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
3504 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
3505 && tcx.sess.source_map().lookup_char_pos(lhs.span.lo()).line
3506 != tcx.sess.source_map().lookup_char_pos(rhs.span.hi()).line
3507 {
3508 err.span_label(lhs.span, "");
3509 err.span_label(rhs.span, "");
3510 }
3511 }
3512 ObligationCauseCode::RustCall => {
3513 if let Some(pred) = predicate.as_trait_clause()
3514 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3515 {
3516 err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
3517 }
3518 }
3519 ObligationCauseCode::SliceOrArrayElem => {
3520 err.note("slice and array elements must have `Sized` type");
3521 }
3522 ObligationCauseCode::ArrayLen(array_ty) => {
3523 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the length of array `{0}` must be type `usize`",
array_ty))
})format!("the length of array `{array_ty}` must be type `usize`"));
3524 }
3525 ObligationCauseCode::TupleElem => {
3526 err.note("only the last element of a tuple may have a dynamically sized type");
3527 }
3528 ObligationCauseCode::DynCompatible(span) => {
3529 err.multipart_suggestion(
3530 "you might have meant to use `Self` to refer to the implementing type",
3531 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, "Self".into())]))vec![(span, "Self".into())],
3532 Applicability::MachineApplicable,
3533 );
3534 }
3535 ObligationCauseCode::WhereClause(item_def_id, span)
3536 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
3537 | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
3538 if !span.is_dummy() =>
3539 {
3540 if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
3541 if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
3542 && let hir::ExprKind::Call(_, args) = expr.kind
3543 && let Some(expr) = args.get(*pos)
3544 {
3545 suggest_remove_deref(err, &expr);
3546 } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
3547 && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
3548 && let Some(expr) = args.get(*pos)
3549 {
3550 suggest_remove_deref(err, &expr);
3551 }
3552 }
3553 let item_name = tcx.def_path_str(item_def_id);
3554 let short_item_name = { let _guard = ForceTrimmedGuard::new(); tcx.def_path_str(item_def_id) }with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
3555 let mut multispan = MultiSpan::from(span);
3556 let sm = tcx.sess.source_map();
3557 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
3558 let same_line =
3559 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
3560 (Ok(l), Ok(r)) => l.line == r.line,
3561 _ => true,
3562 };
3563 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
3564 multispan.push_span_label(
3565 ident.span,
3566 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by a bound in this {0}",
tcx.def_kind(item_def_id).descr(item_def_id)))
})format!(
3567 "required by a bound in this {}",
3568 tcx.def_kind(item_def_id).descr(item_def_id)
3569 ),
3570 );
3571 }
3572 }
3573 let mut a = "a";
3574 let mut this = "this bound".to_owned();
3575 let mut note = None;
3576 let mut help = None;
3577 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
3578 match clause {
3579 ty::ClauseKind::Trait(trait_pred) => {
3580 let def_id = trait_pred.def_id();
3581 let visible_item = if let Some(local) = def_id.as_local() {
3582 let ty = trait_pred.self_ty();
3583 if let ty::Adt(adt, _) = ty.kind() {
3587 let visibilities = &tcx.resolutions(()).effective_visibilities;
3588 visibilities.effective_vis(local).is_none_or(|v| {
3589 v.at_level(Level::Reexported)
3590 .is_accessible_from(adt.did(), tcx)
3591 })
3592 } else {
3593 true
3595 }
3596 } else {
3597 tcx.visible_parent_map(()).get(&def_id).is_some()
3599 };
3600 if tcx.is_lang_item(def_id, LangItem::Sized) {
3601 if let Some(DesugaringKind::DefaultBound { def }) =
3602 span.desugaring_kind()
3603 {
3604 a = "an implicit `Sized`";
3605 this = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the implicit `Sized` requirement on this {0}",
tcx.def_kind(def).descr(def)))
})format!(
3606 "the implicit `Sized` requirement on this {}",
3607 tcx.def_kind(def).descr(def)
3608 );
3609 }
3610 if let Some(hir::Node::TraitItem(hir::TraitItem {
3611 generics,
3612 kind: hir::TraitItemKind::Type(bounds, None),
3613 ..
3614 })) = tcx.hir_get_if_local(item_def_id)
3615 && !bounds.iter()
3617 .filter_map(|bound| bound.trait_ref())
3618 .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
3619 {
3620 let (span, separator) = if let [.., last] = bounds {
3621 (last.span().shrink_to_hi(), " +")
3622 } else {
3623 (generics.span.shrink_to_hi(), ":")
3624 };
3625 err.span_suggestion_verbose(
3626 span,
3627 "consider relaxing the implicit `Sized` restriction",
3628 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ?Sized", separator))
})format!("{separator} ?Sized"),
3629 Applicability::MachineApplicable,
3630 );
3631 }
3632 }
3633 if let DefKind::Trait = tcx.def_kind(item_def_id)
3634 && !visible_item
3635 {
3636 note = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` is a \"sealed trait\", because to implement it you also need to implement `{0}`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it",
{
let _guard = NoTrimmedGuard::new();
tcx.def_path_str(def_id)
}, short_item_name))
})format!(
3637 "`{short_item_name}` is a \"sealed trait\", because to implement it \
3638 you also need to implement `{}`, which is not accessible; this is \
3639 usually done to force you to use one of the provided types that \
3640 already implement it",
3641 with_no_trimmed_paths!(tcx.def_path_str(def_id)),
3642 ));
3643 let mut types = tcx
3644 .all_impls(def_id)
3645 .map(|t| {
3646 {
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}",
tcx.type_of(t).instantiate_identity().skip_norm_wip()))
})
}with_no_trimmed_paths!(format!(
3647 " {}",
3648 tcx.type_of(t).instantiate_identity().skip_norm_wip(),
3649 ))
3650 })
3651 .collect::<Vec<_>>();
3652 if !types.is_empty() {
3653 let len = types.len();
3654 let post = if len > 9 {
3655 types.truncate(8);
3656 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
})format!("\nand {} others", len - 8)
3657 } else {
3658 String::new()
3659 };
3660 help = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following type{0} implement{1} the trait:\n{2}{3}",
if len == 1 { "" } else { "s" },
if len == 1 { "s" } else { "" }, types.join("\n"), post))
})format!(
3661 "the following type{} implement{} the trait:\n{}{post}",
3662 pluralize!(len),
3663 if len == 1 { "s" } else { "" },
3664 types.join("\n"),
3665 ));
3666 }
3667 }
3668 }
3669 ty::ClauseKind::ConstArgHasType(..) => {
3670 let descr =
3671 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by a const generic parameter in `{0}`",
item_name))
})format!("required by a const generic parameter in `{item_name}`");
3672 if span.is_visible(sm) {
3673 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
short_item_name))
})format!(
3674 "required by this const generic parameter in `{short_item_name}`"
3675 );
3676 multispan.push_span_label(span, msg);
3677 err.span_note(multispan, descr);
3678 } else {
3679 err.span_note(tcx.def_span(item_def_id), descr);
3680 }
3681 return;
3682 }
3683 _ => (),
3684 }
3685 }
3686
3687 let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
3690 #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
3691 } else {
3692 false
3693 };
3694 if !is_in_fmt_lit {
3695 let descr = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by {0} bound in `{1}`", a,
item_name))
})format!("required by {a} bound in `{item_name}`");
3696 if span.is_visible(sm) {
3697 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by {0} in `{1}`", this,
short_item_name))
})format!("required by {this} in `{short_item_name}`");
3698 multispan.push_span_label(span, msg);
3699 err.span_note(multispan, descr);
3700 } else {
3701 err.span_note(tcx.def_span(item_def_id), descr);
3702 }
3703 }
3704 if let Some(note) = note {
3705 err.note(note);
3706 }
3707 if let Some(help) = help {
3708 err.help(help);
3709 }
3710 }
3711 ObligationCauseCode::WhereClause(..)
3712 | ObligationCauseCode::WhereClauseInExpr(..)
3713 | ObligationCauseCode::HostEffectInExpr(..) => {
3714 }
3717 ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
3718 err.span_note(span, "required by a bound in an opaque type");
3719 if let Some(definition_def_id) = definition_def_id
3720 && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
3724 {
3725 err.span_note(
3728 tcx.def_span(definition_def_id),
3729 "this definition site has more where clauses than the opaque type",
3730 );
3731 }
3732 }
3733 ObligationCauseCode::Coercion { source, target } => {
3734 let source =
3735 tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
3736 let target =
3737 tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
3738 err.note({
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for the cast from `{0}` to `{1}`",
source, target))
})
}with_forced_trimmed_paths!(format!(
3739 "required for the cast from `{source}` to `{target}`",
3740 )));
3741 }
3742 ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
3743 err.note(
3744 "the `Copy` trait is required because this value will be copied for each element of the array",
3745 );
3746 let sm = tcx.sess.source_map();
3747 if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
IsConstable::Fn | IsConstable::Ctor => true,
_ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
3748 && let Ok(_) = sm.span_to_snippet(elt_span)
3749 {
3750 err.multipart_suggestion(
3751 "create an inline `const` block",
3752 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(elt_span.shrink_to_lo(), "const { ".to_string()),
(elt_span.shrink_to_hi(), " }".to_string())]))vec![
3753 (elt_span.shrink_to_lo(), "const { ".to_string()),
3754 (elt_span.shrink_to_hi(), " }".to_string()),
3755 ],
3756 Applicability::MachineApplicable,
3757 );
3758 } else {
3759 err.help("consider using `core::array::from_fn` to initialize the array");
3761 err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
3762 }
3763 }
3764 ObligationCauseCode::VariableType(hir_id) => {
3765 if let Some(typeck_results) = &self.typeck_results
3766 && let Some(ty) = typeck_results.node_type_opt(hir_id)
3767 && let ty::Error(_) = ty.kind()
3768 {
3769 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` isn\'t satisfied, but the type of this pattern is `{{type error}}`",
predicate))
})format!(
3770 "`{predicate}` isn't satisfied, but the type of this pattern is \
3771 `{{type error}}`",
3772 ));
3773 err.downgrade_to_delayed_bug();
3774 }
3775 let mut local = true;
3776 match tcx.parent_hir_node(hir_id) {
3777 Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
3778 err.span_suggestion_verbose(
3779 ty.span.shrink_to_lo(),
3780 "consider borrowing here",
3781 "&",
3782 Applicability::MachineApplicable,
3783 );
3784 }
3785 Node::LetStmt(hir::LetStmt {
3786 init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
3787 ..
3788 }) => {
3789 err.span_suggestion_verbose(
3793 span.shrink_to_lo(),
3794 "consider borrowing here",
3795 "&",
3796 Applicability::MachineApplicable,
3797 );
3798 }
3799 Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
3800 suggest_remove_deref(err, &expr);
3803 }
3804 Node::Param(param) => {
3805 err.span_suggestion_verbose(
3806 param.ty_span.shrink_to_lo(),
3807 "function arguments must have a statically known size, borrowed types \
3808 always have a known size",
3809 "&",
3810 Applicability::MachineApplicable,
3811 );
3812 local = false;
3813 }
3814 _ => {}
3815 }
3816 if local {
3817 err.note("all local variables must have a statically known size");
3818 }
3819 }
3820 ObligationCauseCode::SizedArgumentType(hir_id) => {
3821 let mut ty = None;
3822 let borrowed_msg = "function arguments must have a statically known size, borrowed \
3823 types always have a known size";
3824 if let Some(hir_id) = hir_id
3825 && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
3826 && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
3827 && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
3828 {
3829 ty = Some(t);
3837 } else if let Some(hir_id) = hir_id
3838 && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
3839 {
3840 ty = Some(t);
3841 }
3842 if let Some(ty) = ty {
3843 match ty.kind {
3844 hir::TyKind::TraitObject(traits, _) => {
3845 let (span, kw) = match traits {
3846 [first, ..] if first.span.lo() == ty.span.lo() => {
3847 (ty.span.shrink_to_lo(), "dyn ")
3849 }
3850 [first, ..] => (ty.span.until(first.span), ""),
3851 [] => ::rustc_middle::util::bug::span_bug_fmt(ty.span,
format_args!("trait object with no traits: {0:?}", ty))span_bug!(ty.span, "trait object with no traits: {ty:?}"),
3852 };
3853 let needs_parens = traits.len() != 1;
3854 if let Some(hir_id) = hir_id
3856 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(hir_id)
{
hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. }) => true,
_ => false,
}matches!(
3857 self.tcx.parent_hir_node(hir_id),
3858 hir::Node::Item(hir::Item {
3859 kind: hir::ItemKind::Fn { .. },
3860 ..
3861 })
3862 )
3863 {
3864 err.span_suggestion_verbose(
3865 span,
3866 "you can use `impl Trait` as the argument type",
3867 "impl ",
3868 Applicability::MaybeIncorrect,
3869 );
3870 }
3871 let sugg = if !needs_parens {
3872 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", kw))
}))]))vec![(span.shrink_to_lo(), format!("&{kw}"))]
3873 } else {
3874 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&({0}", kw))
})), (ty.span.shrink_to_hi(), ")".to_string())]))vec![
3875 (span.shrink_to_lo(), format!("&({kw}")),
3876 (ty.span.shrink_to_hi(), ")".to_string()),
3877 ]
3878 };
3879 err.multipart_suggestion(
3880 borrowed_msg,
3881 sugg,
3882 Applicability::MachineApplicable,
3883 );
3884 }
3885 hir::TyKind::Slice(_ty) => {
3886 err.span_suggestion_verbose(
3887 ty.span.shrink_to_lo(),
3888 "function arguments must have a statically known size, borrowed \
3889 slices always have a known size",
3890 "&",
3891 Applicability::MachineApplicable,
3892 );
3893 }
3894 hir::TyKind::Path(_) => {
3895 err.span_suggestion_verbose(
3896 ty.span.shrink_to_lo(),
3897 borrowed_msg,
3898 "&",
3899 Applicability::MachineApplicable,
3900 );
3901 }
3902 _ => {}
3903 }
3904 } else {
3905 err.note("all function arguments must have a statically known size");
3906 }
3907 if tcx.sess.opts.unstable_features.is_nightly_build()
3908 && !tcx.features().unsized_fn_params()
3909 {
3910 err.help("unsized fn params are gated as an unstable feature");
3911 }
3912 }
3913 ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
3914 err.note("the return type of a function must have a statically known size");
3915 }
3916 ObligationCauseCode::SizedYieldType => {
3917 err.note("the yield type of a coroutine must have a statically known size");
3918 }
3919 ObligationCauseCode::AssignmentLhsSized => {
3920 err.note("the left-hand-side of an assignment must have a statically known size");
3921 }
3922 ObligationCauseCode::TupleInitializerSized => {
3923 err.note("tuples must have a statically known size to be initialized");
3924 }
3925 ObligationCauseCode::StructInitializerSized => {
3926 err.note("structs must have a statically known size to be initialized");
3927 }
3928 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
3929 match *item {
3930 AdtKind::Struct => {
3931 if last {
3932 err.note(
3933 "the last field of a packed struct may only have a \
3934 dynamically sized type if it does not need drop to be run",
3935 );
3936 } else {
3937 err.note(
3938 "only the last field of a struct may have a dynamically sized type",
3939 );
3940 }
3941 }
3942 AdtKind::Union => {
3943 err.note("no field of a union may have a dynamically sized type");
3944 }
3945 AdtKind::Enum => {
3946 err.note("no field of an enum variant may have a dynamically sized type");
3947 }
3948 }
3949 err.help("change the field's type to have a statically known size");
3950 err.span_suggestion_verbose(
3951 span.shrink_to_lo(),
3952 "borrowed types always have a statically known size",
3953 "&",
3954 Applicability::MachineApplicable,
3955 );
3956 err.multipart_suggestion(
3957 "the `Box` type always has a statically known size and allocates its contents \
3958 in the heap",
3959 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "Box<".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
3960 (span.shrink_to_lo(), "Box<".to_string()),
3961 (span.shrink_to_hi(), ">".to_string()),
3962 ],
3963 Applicability::MachineApplicable,
3964 );
3965 }
3966 ObligationCauseCode::SizedConstOrStatic => {
3967 err.note("statics and constants must have a statically known size");
3968 }
3969 ObligationCauseCode::InlineAsmSized => {
3970 err.note("all inline asm arguments must have a statically known size");
3971 }
3972 ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
3973 err.note(
3974 "all values captured by value by a closure must have a statically known size",
3975 );
3976 let hir::ExprKind::Closure(closure) =
3977 tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
3978 else {
3979 ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure in SizedClosureCapture obligation"));bug!("expected closure in SizedClosureCapture obligation");
3980 };
3981 if let hir::CaptureBy::Value { .. } = closure.capture_clause
3982 && let Some(span) = closure.fn_arg_span
3983 {
3984 err.span_label(span, "this closure captures all values by move");
3985 }
3986 }
3987 ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
3988 let what = match tcx.coroutine_kind(coroutine_def_id) {
3989 None
3990 | Some(hir::CoroutineKind::Coroutine(_))
3991 | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
3992 "yield"
3993 }
3994 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3995 "await"
3996 }
3997 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
3998 "yield`/`await"
3999 }
4000 };
4001 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
what))
})format!(
4002 "all values live across `{what}` must have a statically known size"
4003 ));
4004 }
4005 ObligationCauseCode::SharedStatic => {
4006 err.note("shared static variables must have a type that implements `Sync`");
4007 }
4008 ObligationCauseCode::BuiltinDerived(ref data) => {
4009 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4010 let ty = parent_trait_ref.skip_binder().self_ty();
4011 if parent_trait_ref.references_error() {
4012 err.downgrade_to_delayed_bug();
4015 return;
4016 }
4017
4018 let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
4021 false
4022 } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
4023 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4024 let nested_ty = parent_trait_ref.skip_binder().self_ty();
4025 #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Coroutine(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
4026 || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Closure(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
4027 } else {
4028 false
4029 };
4030
4031 let is_builtin_async_fn_trait =
4032 tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
4033
4034 if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
4035 let mut msg = || {
4036 let ty_str = tcx.short_string(ty, err.long_ty_path());
4037 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required because it appears within the type `{0}`",
ty_str))
})format!("required because it appears within the type `{ty_str}`")
4038 };
4039 match *ty.kind() {
4040 ty::Adt(def, _) => {
4041 let msg = msg();
4042 match tcx.opt_item_ident(def.did()) {
4043 Some(ident) => {
4044 err.span_note(ident.span, msg);
4045 }
4046 None => {
4047 err.note(msg);
4048 }
4049 }
4050 }
4051 ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
4052 let is_future = tcx.ty_is_opaque_future(ty);
4055 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4055",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4055u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
"obligated_types", "is_future"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("note_obligation_cause_code: check for async fn")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&obligated_types)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&is_future)
as &dyn Value))])
});
} else { ; }
};debug!(
4056 ?obligated_types,
4057 ?is_future,
4058 "note_obligation_cause_code: check for async fn"
4059 );
4060 if is_future
4061 && obligated_types.last().is_some_and(|ty| match ty.kind() {
4062 ty::Coroutine(last_def_id, ..) => {
4063 tcx.coroutine_is_async(*last_def_id)
4064 }
4065 _ => false,
4066 })
4067 {
4068 } else {
4070 let msg = msg();
4071 err.span_note(tcx.def_span(def_id), msg);
4072 }
4073 }
4074 ty::Coroutine(def_id, _) => {
4075 let sp = tcx.def_span(def_id);
4076
4077 let kind = tcx.coroutine_kind(def_id).unwrap();
4079 err.span_note(
4080 sp,
4081 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required because it\'s used within this {0:#}",
kind))
})
}with_forced_trimmed_paths!(format!(
4082 "required because it's used within this {kind:#}",
4083 )),
4084 );
4085 }
4086 ty::CoroutineWitness(..) => {
4087 }
4090 ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
4091 err.span_note(
4092 tcx.def_span(def_id),
4093 "required because it's used within this closure",
4094 );
4095 }
4096 ty::Str => {
4097 err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
4098 }
4099 _ => {
4100 let msg = msg();
4101 err.note(msg);
4102 }
4103 };
4104 }
4105
4106 obligated_types.push(ty);
4107
4108 let parent_predicate = parent_trait_ref;
4109 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
4110 ensure_sufficient_stack(|| {
4112 self.note_obligation_cause_code(
4113 body_id,
4114 err,
4115 parent_predicate,
4116 param_env,
4117 &data.parent_code,
4118 obligated_types,
4119 seen_requirements,
4120 )
4121 });
4122 } else {
4123 ensure_sufficient_stack(|| {
4124 self.note_obligation_cause_code(
4125 body_id,
4126 err,
4127 parent_predicate,
4128 param_env,
4129 cause_code.peel_derives(),
4130 obligated_types,
4131 seen_requirements,
4132 )
4133 });
4134 }
4135 }
4136 ObligationCauseCode::ImplDerived(ref data) => {
4137 let mut parent_trait_pred =
4138 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4139 let parent_def_id = parent_trait_pred.def_id();
4140 if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
4141 && !tcx.features().enabled(sym::try_trait_v2)
4142 {
4143 return;
4147 }
4148 if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
4149 let parent_predicate =
4150 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
4151
4152 ensure_sufficient_stack(|| {
4154 self.note_obligation_cause_code(
4155 body_id,
4156 err,
4157 parent_predicate,
4158 param_env,
4159 &data.derived.parent_code,
4160 obligated_types,
4161 seen_requirements,
4162 )
4163 });
4164 return;
4165 }
4166 let self_ty_str =
4167 tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
4168 let trait_name = tcx.short_string(
4169 parent_trait_pred.print_modifiers_and_trait_path(),
4170 err.long_ty_path(),
4171 );
4172 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for `{0}` to implement `{1}`",
self_ty_str, trait_name))
})format!("required for `{self_ty_str}` to implement `{trait_name}`");
4173 let mut is_auto_trait = false;
4174 match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
4175 Some(Node::Item(hir::Item {
4176 kind: hir::ItemKind::Trait { is_auto, ident, .. },
4177 ..
4178 })) => {
4179 is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
hir::IsAuto::Yes => true,
_ => false,
}matches!(is_auto, hir::IsAuto::Yes);
4182 err.span_note(ident.span, msg);
4183 }
4184 Some(Node::Item(hir::Item {
4185 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
4186 ..
4187 })) => {
4188 let mut spans = Vec::with_capacity(2);
4189 if let Some(of_trait) = of_trait
4190 && !of_trait.trait_ref.path.span.in_derive_expansion()
4191 {
4192 spans.push(of_trait.trait_ref.path.span);
4193 }
4194 spans.push(self_ty.span);
4195 let mut spans: MultiSpan = spans.into();
4196 let mut derived = false;
4197 if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
{
ExpnKind::Macro(MacroKind::Derive, _) => true,
_ => false,
}matches!(
4198 self_ty.span.ctxt().outer_expn_data().kind,
4199 ExpnKind::Macro(MacroKind::Derive, _)
4200 ) || #[allow(non_exhaustive_omitted_patterns)] match of_trait.map(|t|
t.trait_ref.path.span.ctxt().outer_expn_data().kind) {
Some(ExpnKind::Macro(MacroKind::Derive, _)) => true,
_ => false,
}matches!(
4201 of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
4202 Some(ExpnKind::Macro(MacroKind::Derive, _))
4203 ) {
4204 derived = true;
4205 spans.push_span_label(
4206 data.span,
4207 if data.span.in_derive_expansion() {
4208 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter would need to implement `{0}`",
trait_name))
})format!("type parameter would need to implement `{trait_name}`")
4209 } else {
4210 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied trait bound"))
})format!("unsatisfied trait bound")
4211 },
4212 );
4213 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
4214 if let Some(pred) = predicate.as_trait_clause()
4217 && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
4218 && let Some(DesugaringKind::DefaultBound { .. }) =
4219 data.span.desugaring_kind()
4220 {
4221 spans.push_span_label(
4222 data.span,
4223 "unsatisfied trait bound implicitly introduced here",
4224 );
4225 } else {
4226 spans.push_span_label(
4227 data.span,
4228 "unsatisfied trait bound introduced here",
4229 );
4230 }
4231 }
4232 err.span_note(spans, msg);
4233 if derived && trait_name != "Copy" {
4234 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider manually implementing `{0}` to avoid undesired bounds",
trait_name))
})format!(
4235 "consider manually implementing `{trait_name}` to avoid undesired \
4236 bounds",
4237 ));
4238 }
4239 point_at_assoc_type_restriction(
4240 tcx,
4241 err,
4242 &self_ty_str,
4243 &trait_name,
4244 predicate,
4245 &generics,
4246 &data,
4247 );
4248 }
4249 _ => {
4250 err.note(msg);
4251 }
4252 };
4253
4254 let mut parent_predicate = parent_trait_pred;
4255 let mut data = &data.derived;
4256 let mut count = 0;
4257 seen_requirements.insert(parent_def_id);
4258 if is_auto_trait {
4259 while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
4262 let child_trait_ref =
4263 self.resolve_vars_if_possible(derived.parent_trait_pred);
4264 let child_def_id = child_trait_ref.def_id();
4265 if seen_requirements.insert(child_def_id) {
4266 break;
4267 }
4268 data = derived;
4269 parent_predicate = child_trait_ref.upcast(tcx);
4270 parent_trait_pred = child_trait_ref;
4271 }
4272 }
4273 while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
4274 let child_trait_pred =
4276 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
4277 let child_def_id = child_trait_pred.def_id();
4278 if seen_requirements.insert(child_def_id) {
4279 break;
4280 }
4281 count += 1;
4282 data = &child.derived;
4283 parent_predicate = child_trait_pred.upcast(tcx);
4284 parent_trait_pred = child_trait_pred;
4285 }
4286 if count > 0 {
4287 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
count, if count == 1 { "" } else { "s" }))
})format!(
4288 "{} redundant requirement{} hidden",
4289 count,
4290 pluralize!(count)
4291 ));
4292 let self_ty = tcx.short_string(
4293 parent_trait_pred.skip_binder().self_ty(),
4294 err.long_ty_path(),
4295 );
4296 let trait_path = tcx.short_string(
4297 parent_trait_pred.print_modifiers_and_trait_path(),
4298 err.long_ty_path(),
4299 );
4300 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for `{0}` to implement `{1}`",
self_ty, trait_path))
})format!("required for `{self_ty}` to implement `{trait_path}`"));
4301 }
4302 ensure_sufficient_stack(|| {
4304 self.note_obligation_cause_code(
4305 body_id,
4306 err,
4307 parent_predicate,
4308 param_env,
4309 &data.parent_code,
4310 obligated_types,
4311 seen_requirements,
4312 )
4313 });
4314 }
4315 ObligationCauseCode::ImplDerivedHost(ref data) => {
4316 let self_ty = tcx.short_string(
4317 self.resolve_vars_if_possible(data.derived.parent_host_pred.self_ty()),
4318 err.long_ty_path(),
4319 );
4320 let trait_path = tcx.short_string(
4321 data.derived
4322 .parent_host_pred
4323 .map_bound(|pred| pred.trait_ref)
4324 .print_only_trait_path(),
4325 err.long_ty_path(),
4326 );
4327 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for `{1}` to implement `{0} {2}`",
data.derived.parent_host_pred.skip_binder().constness,
self_ty, trait_path))
})format!(
4328 "required for `{self_ty}` to implement `{} {trait_path}`",
4329 data.derived.parent_host_pred.skip_binder().constness,
4330 );
4331 match tcx.hir_get_if_local(data.impl_def_id) {
4332 Some(Node::Item(hir::Item {
4333 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
4334 ..
4335 })) => {
4336 let mut spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self_ty.span]))vec![self_ty.span];
4337 spans.extend(of_trait.map(|t| t.trait_ref.path.span));
4338 let mut spans: MultiSpan = spans.into();
4339 spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
4340 err.span_note(spans, msg);
4341 }
4342 _ => {
4343 err.note(msg);
4344 }
4345 }
4346 ensure_sufficient_stack(|| {
4347 self.note_obligation_cause_code(
4348 body_id,
4349 err,
4350 data.derived.parent_host_pred,
4351 param_env,
4352 &data.derived.parent_code,
4353 obligated_types,
4354 seen_requirements,
4355 )
4356 });
4357 }
4358 ObligationCauseCode::BuiltinDerivedHost(ref data) => {
4359 ensure_sufficient_stack(|| {
4360 self.note_obligation_cause_code(
4361 body_id,
4362 err,
4363 data.parent_host_pred,
4364 param_env,
4365 &data.parent_code,
4366 obligated_types,
4367 seen_requirements,
4368 )
4369 });
4370 }
4371 ObligationCauseCode::WellFormedDerived(ref data) => {
4372 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
4373 let parent_predicate = parent_trait_ref;
4374 ensure_sufficient_stack(|| {
4376 self.note_obligation_cause_code(
4377 body_id,
4378 err,
4379 parent_predicate,
4380 param_env,
4381 &data.parent_code,
4382 obligated_types,
4383 seen_requirements,
4384 )
4385 });
4386 }
4387 ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
4388 ensure_sufficient_stack(|| {
4390 self.note_obligation_cause_code(
4391 body_id,
4392 err,
4393 predicate,
4394 param_env,
4395 nested,
4396 obligated_types,
4397 seen_requirements,
4398 )
4399 });
4400 let mut multispan = MultiSpan::from(span);
4401 multispan.push_span_label(span, "required by this bound");
4402 err.span_note(
4403 multispan,
4404 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by a bound on the type alias `{0}`",
tcx.item_name(def_id)))
})format!("required by a bound on the type alias `{}`", tcx.item_name(def_id)),
4405 );
4406 }
4407 ObligationCauseCode::FunctionArg {
4408 arg_hir_id, call_hir_id, ref parent_code, ..
4409 } => {
4410 self.note_function_argument_obligation(
4411 body_id,
4412 err,
4413 arg_hir_id,
4414 parent_code,
4415 param_env,
4416 predicate,
4417 call_hir_id,
4418 );
4419 ensure_sufficient_stack(|| {
4420 self.note_obligation_cause_code(
4421 body_id,
4422 err,
4423 predicate,
4424 param_env,
4425 parent_code,
4426 obligated_types,
4427 seen_requirements,
4428 )
4429 });
4430 }
4431 ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
4434 if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
4435 ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
4436 let item_name = tcx.item_name(trait_item_def_id);
4437 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the requirement `{0}` appears on the `impl`\'s {1} `{2}` but not on the corresponding trait\'s {1}",
predicate, kind, item_name))
})format!(
4438 "the requirement `{predicate}` appears on the `impl`'s {kind} \
4439 `{item_name}` but not on the corresponding trait's {kind}",
4440 );
4441 let sp = tcx
4442 .opt_item_ident(trait_item_def_id)
4443 .map(|i| i.span)
4444 .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
4445 let mut assoc_span: MultiSpan = sp.into();
4446 assoc_span.push_span_label(
4447 sp,
4448 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this trait\'s {0} doesn\'t have the requirement `{1}`",
kind, predicate))
})format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
4449 );
4450 if let Some(ident) = tcx
4451 .opt_associated_item(trait_item_def_id)
4452 .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
4453 {
4454 assoc_span.push_span_label(ident.span, "in this trait");
4455 }
4456 err.span_note(assoc_span, msg);
4457 }
4458 ObligationCauseCode::TrivialBound => {
4459 tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
4460 }
4461 ObligationCauseCode::OpaqueReturnType(expr_info) => {
4462 let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
4463 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
4464 let expr = tcx.hir_expect_expr(hir_id);
4465 (expr_ty, expr)
4466 } else if let Some(body_id) = tcx.hir_node_by_def_id(body_id).body_id()
4467 && let body = tcx.hir_body(body_id)
4468 && let hir::ExprKind::Block(block, _) = body.value.kind
4469 && let Some(expr) = block.expr
4470 && let Some(expr_ty) = self
4471 .typeck_results
4472 .as_ref()
4473 .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
4474 && let Some(pred) = predicate.as_clause()
4475 && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
4476 && self.can_eq(param_env, pred.self_ty(), expr_ty)
4477 {
4478 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
4479 (expr_ty, expr)
4480 } else {
4481 return;
4482 };
4483 err.span_label(
4484 expr.span,
4485 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("return type was inferred to be `{0}` here",
expr_ty))
})
}with_forced_trimmed_paths!(format!(
4486 "return type was inferred to be `{expr_ty}` here",
4487 )),
4488 );
4489 suggest_remove_deref(err, &expr);
4490 }
4491 ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
4492 err.span_note(
4493 span,
4494 "unsized values must be place expressions and cannot be put in temporaries",
4495 );
4496 }
4497 ObligationCauseCode::CompareEii { .. } => {
4498 {
::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
4499 }
4500 }
4501 }
4502
4503 #[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("suggest_await_before_try",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4503u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["obligation",
"trait_pred", "span", "trait_pred.self_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_pred.self_ty())
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let future_trait =
self.tcx.require_lang_item(LangItem::Future, span);
let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
let impls_future =
self.type_implements_trait(future_trait,
[self.tcx.instantiate_bound_regions_with_erased(self_ty)],
obligation.param_env);
if !impls_future.must_apply_modulo_regions() { return; }
let item_def_id =
self.tcx.associated_item_def_ids(future_trait)[0];
let projection_ty =
trait_pred.map_bound(|trait_pred|
{
Ty::new_projection(self.tcx, item_def_id,
[trait_pred.self_ty()])
});
let InferOk { value: projection_ty, .. } =
self.at(&obligation.cause,
obligation.param_env).normalize(Unnormalized::new_wip(projection_ty));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4539",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4539u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["normalized_projection_type"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.resolve_vars_if_possible(projection_ty))
as &dyn Value))])
});
} else { ; }
};
let try_obligation =
self.mk_trait_obligation_with_new_self_ty(obligation.param_env,
trait_pred.map_bound(|trait_pred|
(trait_pred, projection_ty.skip_binder())));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4546",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4546u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["try_trait_obligation"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&try_obligation)
as &dyn Value))])
});
} else { ; }
};
if self.predicate_may_hold(&try_obligation) &&
let Ok(snippet) =
self.tcx.sess.source_map().span_to_snippet(span) &&
snippet.ends_with('?') {
match self.tcx.coroutine_kind(obligation.cause.body_id) {
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
_)) => {
err.span_suggestion_verbose(span.with_hi(span.hi() -
BytePos(1)).shrink_to_hi(),
"consider `await`ing on the `Future`", ".await",
Applicability::MaybeIncorrect);
}
_ => {
let mut span: MultiSpan =
span.with_lo(span.hi() - BytePos(1)).into();
span.push_span_label(self.tcx.def_span(obligation.cause.body_id),
"this is not `async`");
err.span_note(span,
"this implements `Future` and its output type supports \
`?`, but the future cannot be awaited in a synchronous function");
}
}
}
}
}
}#[instrument(
4504 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
4505 )]
4506 pub(super) fn suggest_await_before_try(
4507 &self,
4508 err: &mut Diag<'_>,
4509 obligation: &PredicateObligation<'tcx>,
4510 trait_pred: ty::PolyTraitPredicate<'tcx>,
4511 span: Span,
4512 ) {
4513 let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
4514
4515 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
4516 let impls_future = self.type_implements_trait(
4517 future_trait,
4518 [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
4519 obligation.param_env,
4520 );
4521 if !impls_future.must_apply_modulo_regions() {
4522 return;
4523 }
4524
4525 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
4526 let projection_ty = trait_pred.map_bound(|trait_pred| {
4528 Ty::new_projection(
4529 self.tcx,
4530 item_def_id,
4531 [trait_pred.self_ty()],
4533 )
4534 });
4535 let InferOk { value: projection_ty, .. } = self
4536 .at(&obligation.cause, obligation.param_env)
4537 .normalize(Unnormalized::new_wip(projection_ty));
4538
4539 debug!(
4540 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
4541 );
4542 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
4543 obligation.param_env,
4544 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
4545 );
4546 debug!(try_trait_obligation = ?try_obligation);
4547 if self.predicate_may_hold(&try_obligation)
4548 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
4549 && snippet.ends_with('?')
4550 {
4551 match self.tcx.coroutine_kind(obligation.cause.body_id) {
4552 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4553 err.span_suggestion_verbose(
4554 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
4555 "consider `await`ing on the `Future`",
4556 ".await",
4557 Applicability::MaybeIncorrect,
4558 );
4559 }
4560 _ => {
4561 let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
4562 span.push_span_label(
4563 self.tcx.def_span(obligation.cause.body_id),
4564 "this is not `async`",
4565 );
4566 err.span_note(
4567 span,
4568 "this implements `Future` and its output type supports \
4569 `?`, but the future cannot be awaited in a synchronous function",
4570 );
4571 }
4572 }
4573 }
4574 }
4575
4576 pub(super) fn suggest_floating_point_literal(
4577 &self,
4578 obligation: &PredicateObligation<'tcx>,
4579 err: &mut Diag<'_>,
4580 trait_pred: ty::PolyTraitPredicate<'tcx>,
4581 ) {
4582 let rhs_span = match obligation.cause.code() {
4583 ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
4584 _ => return,
4585 };
4586 if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
4587 && let ty::Infer(InferTy::IntVar(_)) =
4588 trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4589 {
4590 err.span_suggestion_verbose(
4591 rhs_span.shrink_to_hi(),
4592 "consider using a floating-point literal by writing it with `.0`",
4593 ".0",
4594 Applicability::MaybeIncorrect,
4595 );
4596 }
4597 }
4598
4599 pub fn can_suggest_derive(
4600 &self,
4601 obligation: &PredicateObligation<'tcx>,
4602 trait_pred: ty::PolyTraitPredicate<'tcx>,
4603 ) -> bool {
4604 if trait_pred.polarity() == ty::PredicatePolarity::Negative {
4605 return false;
4606 }
4607 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4608 return false;
4609 };
4610 let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
4611 ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
4612 _ => return false,
4613 };
4614 let is_derivable_trait = match diagnostic_name {
4615 sym::Copy | sym::Clone => true,
4616 _ if adt.is_union() => false,
4617 sym::PartialEq | sym::PartialOrd => {
4618 let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
4619 trait_pred.skip_binder().self_ty() == rhs_ty
4620 }
4621 sym::Eq | sym::Ord | sym::Hash | sym::Debug | sym::Default => true,
4622 _ => false,
4623 };
4624 is_derivable_trait &&
4625 adt.all_fields().all(|field| {
4627 let field_ty = ty::GenericArg::from(field.ty(self.tcx, args).skip_norm_wip());
4628 let trait_args = match diagnostic_name {
4629 sym::PartialEq | sym::PartialOrd => {
4630 Some(field_ty)
4631 }
4632 _ => None,
4633 };
4634 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
4635 trait_ref: ty::TraitRef::new(self.tcx,
4636 trait_pred.def_id(),
4637 [field_ty].into_iter().chain(trait_args),
4638 ),
4639 ..*tr
4640 });
4641 let field_obl = Obligation::new(
4642 self.tcx,
4643 obligation.cause.clone(),
4644 obligation.param_env,
4645 trait_pred,
4646 );
4647 self.predicate_must_hold_modulo_regions(&field_obl)
4648 })
4649 }
4650
4651 pub fn suggest_derive(
4652 &self,
4653 obligation: &PredicateObligation<'tcx>,
4654 err: &mut Diag<'_>,
4655 trait_pred: ty::PolyTraitPredicate<'tcx>,
4656 ) {
4657 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4658 return;
4659 };
4660 let adt = match trait_pred.skip_binder().self_ty().kind() {
4661 ty::Adt(adt, _) if adt.did().is_local() => adt,
4662 _ => return,
4663 };
4664 if self.can_suggest_derive(obligation, trait_pred) {
4665 err.span_suggestion_verbose(
4666 self.tcx.def_span(adt.did()).shrink_to_lo(),
4667 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
trait_pred.skip_binder().self_ty(), diagnostic_name))
})format!(
4668 "consider annotating `{}` with `#[derive({})]`",
4669 trait_pred.skip_binder().self_ty(),
4670 diagnostic_name,
4671 ),
4672 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
diagnostic_name))
})format!("#[derive({diagnostic_name})]\n"),
4674 Applicability::MaybeIncorrect,
4675 );
4676 }
4677 }
4678
4679 pub(super) fn suggest_dereferencing_index(
4680 &self,
4681 obligation: &PredicateObligation<'tcx>,
4682 err: &mut Diag<'_>,
4683 trait_pred: ty::PolyTraitPredicate<'tcx>,
4684 ) {
4685 if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
4686 && self
4687 .tcx
4688 .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
4689 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4690 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
4691 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
4692 {
4693 err.span_suggestion_verbose(
4694 obligation.cause.span.shrink_to_lo(),
4695 "dereference this index",
4696 '*',
4697 Applicability::MachineApplicable,
4698 );
4699 }
4700 }
4701
4702 fn note_function_argument_obligation<G: EmissionGuarantee>(
4703 &self,
4704 body_id: LocalDefId,
4705 err: &mut Diag<'_, G>,
4706 arg_hir_id: HirId,
4707 parent_code: &ObligationCauseCode<'tcx>,
4708 param_env: ty::ParamEnv<'tcx>,
4709 failed_pred: ty::Predicate<'tcx>,
4710 call_hir_id: HirId,
4711 ) {
4712 let tcx = self.tcx;
4713 if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
4714 && let Some(typeck_results) = &self.typeck_results
4715 {
4716 if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
4717 && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
4718 && let Some(failed_pred) = failed_pred.as_trait_clause()
4719 && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
4720 && self.predicate_must_hold_modulo_regions(&Obligation::misc(
4721 tcx, expr.span, body_id, param_env, pred,
4722 ))
4723 && expr.span.hi() != rcvr.span.hi()
4724 {
4725 let should_sugg = match tcx.hir_node(call_hir_id) {
4726 Node::Expr(hir::Expr {
4727 kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
4728 ..
4729 }) if let Some((DefKind::AssocFn, did)) =
4730 typeck_results.type_dependent_def(call_hir_id)
4731 && call_receiver.hir_id == arg_hir_id =>
4732 {
4733 if tcx.inherent_impl_of_assoc(did).is_some() {
4737 Some(ty) == typeck_results.node_type_opt(arg_hir_id)
4739 } else {
4740 let trait_id = tcx
4742 .trait_of_assoc(did)
4743 .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
4744 let args = typeck_results.node_args(call_hir_id);
4745 let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
4746 .with_replaced_self_ty(tcx, ty);
4747 self.type_implements_trait(tr.def_id, tr.args, param_env)
4748 .must_apply_modulo_regions()
4749 }
4750 }
4751 _ => true,
4752 };
4753
4754 if should_sugg {
4755 err.span_suggestion_verbose(
4756 expr.span.with_lo(rcvr.span.hi()),
4757 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing this method call, as the receiver has type `{0}` and `{1}` trivially holds",
ty, pred))
})format!(
4758 "consider removing this method call, as the receiver has type `{ty}` and \
4759 `{pred}` trivially holds",
4760 ),
4761 "",
4762 Applicability::MaybeIncorrect,
4763 );
4764 }
4765 }
4766 if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
4767 let inner_expr = expr.peel_blocks();
4768 let ty = typeck_results
4769 .expr_ty_adjusted_opt(inner_expr)
4770 .unwrap_or(Ty::new_misc_error(tcx));
4771 let span = inner_expr.span;
4772 if Some(span) != err.span.primary_span()
4773 && !span.in_external_macro(tcx.sess.source_map())
4774 {
4775 err.span_label(
4776 span,
4777 if ty.references_error() {
4778 String::new()
4779 } else {
4780 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4781 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this tail expression is of type `{0}`",
ty))
})format!("this tail expression is of type `{ty}`")
4782 },
4783 );
4784 if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
4785 && let ty::ClauseKind::Trait(pred) = clause
4786 && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
4787 {
4788 if let [stmt, ..] = block.stmts
4789 && let hir::StmtKind::Semi(value) = stmt.kind
4790 && let hir::ExprKind::Closure(hir::Closure {
4791 body, fn_decl_span, ..
4792 }) = value.kind
4793 && let body = tcx.hir_body(*body)
4794 && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
4795 {
4796 err.multipart_suggestion(
4799 "you might have meant to open the closure body instead of placing \
4800 a closure within a block",
4801 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.with_hi(value.span.lo()), String::new()),
(fn_decl_span.shrink_to_hi(), " {".to_string())]))vec![
4802 (expr.span.with_hi(value.span.lo()), String::new()),
4803 (fn_decl_span.shrink_to_hi(), " {".to_string()),
4804 ],
4805 Applicability::MaybeIncorrect,
4806 );
4807 } else {
4808 err.span_suggestion_verbose(
4810 expr.span.shrink_to_lo(),
4811 "you might have meant to create the closure instead of a block",
4812 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}| ",
(0..pred.trait_ref.args.len() -
1).map(|_| "_").collect::<Vec<_>>().join(", ")))
})format!(
4813 "|{}| ",
4814 (0..pred.trait_ref.args.len() - 1)
4815 .map(|_| "_")
4816 .collect::<Vec<_>>()
4817 .join(", ")
4818 ),
4819 Applicability::MaybeIncorrect,
4820 );
4821 }
4822 }
4823 }
4824 }
4825
4826 let mut type_diffs = ::alloc::vec::Vec::new()vec![];
4831 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
4832 && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
4833 && let where_clauses =
4834 self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args)
4835 && let Some(where_pred) = where_clauses.predicates.get(idx)
4836 {
4837 let where_pred = where_pred.as_ref().skip_norm_wip();
4838 if let Some(where_pred) = where_pred.as_trait_clause()
4839 && let Some(failed_pred) = failed_pred.as_trait_clause()
4840 && where_pred.def_id() == failed_pred.def_id()
4841 {
4842 self.enter_forall(where_pred, |where_pred| {
4843 let failed_pred = self.instantiate_binder_with_fresh_vars(
4844 expr.span,
4845 BoundRegionConversionTime::FnCall,
4846 failed_pred,
4847 );
4848
4849 let zipped =
4850 iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
4851 for (expected, actual) in zipped {
4852 self.probe(|_| {
4853 match self
4854 .at(&ObligationCause::misc(expr.span, body_id), param_env)
4855 .eq(DefineOpaqueTypes::Yes, expected, actual)
4858 {
4859 Ok(_) => (), Err(err) => type_diffs.push(err),
4861 }
4862 })
4863 }
4864 })
4865 } else if let Some(where_pred) = where_pred.as_projection_clause()
4866 && let Some(failed_pred) = failed_pred.as_projection_clause()
4867 && let Some(found) = failed_pred.skip_binder().term.as_type()
4868 {
4869 type_diffs = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TypeError::Sorts(ty::error::ExpectedFound {
expected: where_pred.skip_binder().projection_term.expect_ty().to_ty(self.tcx),
found,
})]))vec![TypeError::Sorts(ty::error::ExpectedFound {
4870 expected: where_pred
4871 .skip_binder()
4872 .projection_term
4873 .expect_ty()
4874 .to_ty(self.tcx),
4875 found,
4876 })];
4877 }
4878 }
4879 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4880 && let hir::Path { res: Res::Local(hir_id), .. } = path
4881 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4882 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
4883 && let Some(binding_expr) = local.init
4884 {
4885 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
4889 } else {
4890 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
4891 }
4892 }
4893 let call_node = tcx.hir_node(call_hir_id);
4894 if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
4895 call_node
4896 {
4897 if Some(rcvr.span) == err.span.primary_span() {
4898 err.replace_span_with(path.ident.span, true);
4899 }
4900 }
4901
4902 if let Node::Expr(expr) = call_node {
4903 if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
4904 | hir::ExprKind::MethodCall(
4905 hir::PathSegment { ident: Ident { span, .. }, .. },
4906 ..,
4907 ) = expr.kind
4908 {
4909 if Some(*span) != err.span.primary_span() {
4910 let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
4911 {
4912 "required by this formatting parameter"
4913 } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
4914 "required by a formatting parameter in this expression"
4915 } else {
4916 "required by a bound introduced by this call"
4917 };
4918 err.span_label(*span, msg);
4919 }
4920 }
4921
4922 if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
4923 self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
4924 }
4925 }
4926 }
4927
4928 fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
4929 &self,
4930 failed_pred: ty::Predicate<'tcx>,
4931 param_env: ty::ParamEnv<'tcx>,
4932 err: &mut Diag<'_, G>,
4933 expr: &hir::Expr<'_>,
4934 ) {
4935 let tcx = self.tcx;
4936 let infcx = self.infcx;
4937 let Some(typeck_results) = self.typeck_results.as_ref() else { return };
4938
4939 let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
4941 return;
4942 };
4943 if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
4944 return;
4945 }
4946
4947 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. }))
4950 = failed_pred.kind().skip_binder()
4951 && tcx.is_fn_trait(trait_ref.def_id)
4952 && let [self_ty, found_ty] = trait_ref.args.as_slice()
4953 && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
4954 && let fn_sig @ ty::FnSig {
4955 ..
4956 } = fn_ty.fn_sig(tcx).skip_binder()
4957 && fn_sig.abi() == ExternAbi::Rust
4958 && !fn_sig.c_variadic()
4959 && fn_sig.safety() == hir::Safety::Safe
4960
4961 && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
4963 && !target_ty.has_escaping_bound_vars()
4964
4965 && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
4967 && let &[found_ty] = tys.as_slice()
4968 && !found_ty.has_escaping_bound_vars()
4969
4970 && let Some(deref_target_did) = tcx.lang_items().deref_target()
4972 && let projection = Ty::new_projection_from_args(tcx,deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
4973 && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(projection))
4974 && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
4975 && infcx.can_eq(param_env, deref_target, target_ty)
4976 {
4977 let help = if let hir::Mutability::Mut = needs_mut
4978 && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
4979 && infcx
4980 .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
4981 .must_apply_modulo_regions()
4982 {
4983 Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
4984 } else if let hir::Mutability::Not = needs_mut {
4985 Some(("call `Option::as_deref()` first", ".as_deref()"))
4986 } else {
4987 None
4988 };
4989
4990 if let Some((msg, sugg)) = help {
4991 err.span_suggestion_with_style(
4992 expr.span.shrink_to_hi(),
4993 msg,
4994 sugg,
4995 Applicability::MaybeIncorrect,
4996 SuggestionStyle::ShowAlways,
4997 );
4998 }
4999 }
5000 }
5001
5002 fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
5003 &self,
5004 assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
5005 typeck_results: &TypeckResults<'tcx>,
5006 type_diffs: &[TypeError<'tcx>],
5007 param_env: ty::ParamEnv<'tcx>,
5008 path_segment: &hir::PathSegment<'_>,
5009 args: &[hir::Expr<'_>],
5010 prev_ty: Ty<'_>,
5011 err: &mut Diag<'_, G>,
5012 ) {
5013 let tcx = self.tcx;
5014 for entry in assocs_in_this_method {
5017 let Some((_span, (def_id, ty))) = entry else {
5018 continue;
5019 };
5020 for diff in type_diffs {
5021 let TypeError::Sorts(expected_found) = diff else {
5022 continue;
5023 };
5024 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5025 && path_segment.ident.name == sym::iter
5026 && self.can_eq(
5027 param_env,
5028 Ty::new_ref(
5029 tcx,
5030 tcx.lifetimes.re_erased,
5031 expected_found.found,
5032 ty::Mutability::Not,
5033 ),
5034 *ty,
5035 )
5036 && let [] = args
5037 {
5038 err.span_suggestion_verbose(
5040 path_segment.ident.span,
5041 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider consuming the `{0}` to construct the `Iterator`",
prev_ty))
})format!("consider consuming the `{prev_ty}` to construct the `Iterator`"),
5042 "into_iter".to_string(),
5043 Applicability::MachineApplicable,
5044 );
5045 }
5046 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5047 && path_segment.ident.name == sym::into_iter
5048 && self.can_eq(
5049 param_env,
5050 expected_found.found,
5051 Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
5052 )
5053 && let [] = args
5054 {
5055 err.span_suggestion_verbose(
5057 path_segment.ident.span,
5058 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
prev_ty))
})format!(
5059 "consider not consuming the `{prev_ty}` to construct the `Iterator`"
5060 ),
5061 "iter".to_string(),
5062 Applicability::MachineApplicable,
5063 );
5064 }
5065 if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
5066 && path_segment.ident.name == sym::map
5067 && self.can_eq(param_env, expected_found.found, *ty)
5068 && let [arg] = args
5069 && let hir::ExprKind::Closure(closure) = arg.kind
5070 {
5071 let body = tcx.hir_body(closure.body);
5072 if let hir::ExprKind::Block(block, None) = body.value.kind
5073 && let None = block.expr
5074 && let [.., stmt] = block.stmts
5075 && let hir::StmtKind::Semi(expr) = stmt.kind
5076 && expected_found.found.is_unit()
5080 && expr.span.hi() != stmt.span.hi()
5085 {
5086 err.span_suggestion_verbose(
5087 expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
5088 "consider removing this semicolon",
5089 String::new(),
5090 Applicability::MachineApplicable,
5091 );
5092 }
5093 let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
5094 && let Some(expr) = block.expr
5095 {
5096 expr
5097 } else {
5098 body.value
5099 };
5100 if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
5101 && path_segment.ident.name == sym::clone
5102 && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
5103 && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
5104 && self.can_eq(param_env, expr_ty, rcvr_ty)
5105 && let ty::Ref(_, ty, _) = expr_ty.kind()
5106 {
5107 err.span_label(
5108 span,
5109 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this method call is cloning the reference `{0}`, not `{1}` which doesn\'t implement `Clone`",
expr_ty, ty))
})format!(
5110 "this method call is cloning the reference `{expr_ty}`, not \
5111 `{ty}` which doesn't implement `Clone`",
5112 ),
5113 );
5114 let ty::Param(..) = ty.kind() else {
5115 continue;
5116 };
5117 let node =
5118 tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
5119
5120 let pred = ty::Binder::dummy(ty::TraitPredicate {
5121 trait_ref: ty::TraitRef::new(
5122 tcx,
5123 tcx.require_lang_item(LangItem::Clone, span),
5124 [*ty],
5125 ),
5126 polarity: ty::PredicatePolarity::Positive,
5127 });
5128 let Some(generics) = node.generics() else {
5129 continue;
5130 };
5131 let Some(body_id) = node.body_id() else {
5132 continue;
5133 };
5134 suggest_restriction(
5135 tcx,
5136 tcx.hir_body_owner_def_id(body_id),
5137 generics,
5138 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
})format!("type parameter `{ty}`"),
5139 err,
5140 node.fn_sig(),
5141 None,
5142 pred,
5143 None,
5144 );
5145 }
5146 }
5147 }
5148 }
5149 }
5150
5151 fn point_at_chain<G: EmissionGuarantee>(
5152 &self,
5153 expr: &hir::Expr<'_>,
5154 typeck_results: &TypeckResults<'tcx>,
5155 type_diffs: Vec<TypeError<'tcx>>,
5156 param_env: ty::ParamEnv<'tcx>,
5157 err: &mut Diag<'_, G>,
5158 ) {
5159 let mut primary_spans = ::alloc::vec::Vec::new()vec![];
5160 let mut span_labels = ::alloc::vec::Vec::new()vec![];
5161
5162 let tcx = self.tcx;
5163
5164 let mut print_root_expr = true;
5165 let mut assocs = ::alloc::vec::Vec::new()vec![];
5166 let mut expr = expr;
5167 let mut prev_ty = self.resolve_vars_if_possible(
5168 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5169 );
5170 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
5171 expr = rcvr_expr;
5175 let assocs_in_this_method =
5176 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
5177 prev_ty = self.resolve_vars_if_possible(
5178 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5179 );
5180 self.look_for_iterator_item_mistakes(
5181 &assocs_in_this_method,
5182 typeck_results,
5183 &type_diffs,
5184 param_env,
5185 path_segment,
5186 args,
5187 prev_ty,
5188 err,
5189 );
5190 assocs.push(assocs_in_this_method);
5191
5192 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5193 && let hir::Path { res: Res::Local(hir_id), .. } = path
5194 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5195 {
5196 let parent = self.tcx.parent_hir_node(binding.hir_id);
5197 if let hir::Node::LetStmt(local) = parent
5199 && let Some(binding_expr) = local.init
5200 {
5201 expr = binding_expr;
5203 }
5204 if let hir::Node::Param(param) = parent {
5205 let prev_ty = self.resolve_vars_if_possible(
5207 typeck_results
5208 .node_type_opt(param.hir_id)
5209 .unwrap_or(Ty::new_misc_error(tcx)),
5210 );
5211 let assocs_in_this_method = self.probe_assoc_types_at_expr(
5212 &type_diffs,
5213 param.ty_span,
5214 prev_ty,
5215 param.hir_id,
5216 param_env,
5217 );
5218 if assocs_in_this_method.iter().any(|a| a.is_some()) {
5219 assocs.push(assocs_in_this_method);
5220 print_root_expr = false;
5221 }
5222 break;
5223 }
5224 }
5225 }
5226 if let Some(ty) = typeck_results.expr_ty_opt(expr)
5229 && print_root_expr
5230 {
5231 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5232 span_labels.push((expr.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this expression has type `{0}`",
ty))
})format!("this expression has type `{ty}`")));
5236 };
5237 let mut assocs = assocs.into_iter().peekable();
5240 while let Some(assocs_in_method) = assocs.next() {
5241 let Some(prev_assoc_in_method) = assocs.peek() else {
5242 for entry in assocs_in_method {
5243 let Some((span, (assoc, ty))) = entry else {
5244 continue;
5245 };
5246 if primary_spans.is_empty()
5247 || type_diffs.iter().any(|diff| {
5248 let TypeError::Sorts(expected_found) = diff else {
5249 return false;
5250 };
5251 self.can_eq(param_env, expected_found.found, ty)
5252 })
5253 {
5254 primary_spans.push(span);
5260 }
5261 span_labels.push((
5262 span,
5263 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is `{1}` here",
self.tcx.def_path_str(assoc), ty))
})
}with_forced_trimmed_paths!(format!(
5264 "`{}` is `{ty}` here",
5265 self.tcx.def_path_str(assoc),
5266 )),
5267 ));
5268 }
5269 break;
5270 };
5271 for (entry, prev_entry) in
5272 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
5273 {
5274 match (entry, prev_entry) {
5275 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
5276 let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5277
5278 let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
5279 if !self.can_eq(param_env, ty, *prev_ty) {
5280 if type_diffs.iter().any(|diff| {
5281 let TypeError::Sorts(expected_found) = diff else {
5282 return false;
5283 };
5284 self.can_eq(param_env, expected_found.found, ty)
5285 }) {
5286 primary_spans.push(span);
5287 }
5288 span_labels
5289 .push((span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` changed to `{1}` here",
assoc, ty_str))
})format!("`{assoc}` changed to `{ty_str}` here")));
5290 } else {
5291 span_labels.push((span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` remains `{1}` here", assoc,
ty_str))
})format!("`{assoc}` remains `{ty_str}` here")));
5292 }
5293 }
5294 (Some((span, (assoc, ty))), None) => {
5295 span_labels.push((
5296 span,
5297 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is `{1}` here",
self.tcx.def_path_str(assoc), self.ty_to_string(ty)))
})
}with_forced_trimmed_paths!(format!(
5298 "`{}` is `{}` here",
5299 self.tcx.def_path_str(assoc),
5300 self.ty_to_string(ty),
5301 )),
5302 ));
5303 }
5304 (None, Some(_)) | (None, None) => {}
5305 }
5306 }
5307 }
5308 if !primary_spans.is_empty() {
5309 let mut multi_span: MultiSpan = primary_spans.into();
5310 for (span, label) in span_labels {
5311 multi_span.push_span_label(span, label);
5312 }
5313 err.span_note(
5314 multi_span,
5315 "the method call chain might not have had the expected associated types",
5316 );
5317 }
5318 }
5319
5320 fn probe_assoc_types_at_expr(
5321 &self,
5322 type_diffs: &[TypeError<'tcx>],
5323 span: Span,
5324 prev_ty: Ty<'tcx>,
5325 body_id: HirId,
5326 param_env: ty::ParamEnv<'tcx>,
5327 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
5328 let ocx = ObligationCtxt::new(self.infcx);
5329 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
5330 for diff in type_diffs {
5331 let TypeError::Sorts(expected_found) = diff else {
5332 continue;
5333 };
5334 let &ty::Alias(ty::AliasTy { kind: kind @ ty::Projection { def_id }, .. }) =
5335 expected_found.expected.kind()
5336 else {
5337 continue;
5338 };
5339
5340 let args = GenericArgs::for_item(self.tcx, def_id, |param, _| {
5344 if param.index == 0 {
5345 if true {
{
match param.kind {
ty::GenericParamDefKind::Type { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"ty::GenericParamDefKind::Type { .. }",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(param.kind, ty::GenericParamDefKind::Type { .. });
5346 return prev_ty.into();
5347 }
5348 self.var_for_def(span, param)
5349 });
5350 let ty = self.infcx.next_ty_var(span);
5354 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
5356 ty::ClauseKind::Projection(ty::ProjectionPredicate {
5357 projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args),
5358 term: ty.into(),
5359 }),
5360 ));
5361 let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
5362 ocx.register_obligation(Obligation::misc(
5364 self.tcx,
5365 span,
5366 body_def_id,
5367 param_env,
5368 projection,
5369 ));
5370 if ocx.try_evaluate_obligations().is_empty()
5371 && let ty = self.resolve_vars_if_possible(ty)
5372 && !ty.is_ty_var()
5373 {
5374 assocs_in_this_method.push(Some((span, (def_id, ty))));
5375 } else {
5376 assocs_in_this_method.push(None);
5381 }
5382 }
5383 assocs_in_this_method
5384 }
5385
5386 pub(super) fn suggest_convert_to_slice(
5390 &self,
5391 err: &mut Diag<'_>,
5392 obligation: &PredicateObligation<'tcx>,
5393 trait_pred: ty::PolyTraitPredicate<'tcx>,
5394 candidate_impls: &[ImplCandidate<'tcx>],
5395 span: Span,
5396 ) {
5397 if span.in_external_macro(self.tcx.sess.source_map()) {
5398 return;
5399 }
5400 let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
5403 obligation.cause.code()
5404 else {
5405 return;
5406 };
5407
5408 let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
5413 ty::Array(element_ty, _) => (element_ty, None),
5414
5415 ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
5416 ty::Array(element_ty, _) => (element_ty, Some(mutability)),
5417 _ => return,
5418 },
5419
5420 _ => return,
5421 };
5422
5423 let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
5426 ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
5427 if let ty::Slice(e) = *t.kind()
5428 && e == element_ty
5429 && m == mutability.unwrap_or(m)
5430 {
5431 mutability = Some(m);
5433 true
5434 } else {
5435 false
5436 }
5437 }
5438 _ => false,
5439 };
5440
5441 if let Some(slice_ty) = candidate_impls
5443 .iter()
5444 .map(|trait_ref| trait_ref.trait_ref.self_ty())
5445 .find(|t| is_slice(*t))
5446 {
5447 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("convert the array to a `{0}` slice instead",
slice_ty))
})format!("convert the array to a `{slice_ty}` slice instead");
5448
5449 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
5450 let mut suggestions = ::alloc::vec::Vec::new()vec![];
5451 if snippet.starts_with('&') {
5452 } else if let Some(hir::Mutability::Mut) = mutability {
5453 suggestions.push((span.shrink_to_lo(), "&mut ".into()));
5454 } else {
5455 suggestions.push((span.shrink_to_lo(), "&".into()));
5456 }
5457 suggestions.push((span.shrink_to_hi(), "[..]".into()));
5458 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
5459 } else {
5460 err.span_help(span, msg);
5461 }
5462 }
5463 }
5464
5465 pub(super) fn suggest_tuple_wrapping(
5470 &self,
5471 err: &mut Diag<'_>,
5472 root_obligation: &PredicateObligation<'tcx>,
5473 obligation: &PredicateObligation<'tcx>,
5474 ) {
5475 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
5476 return;
5477 };
5478
5479 let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
5480
5481 let trait_ref = root_pred.map_bound(|root_pred| {
5482 root_pred.trait_ref.with_replaced_self_ty(
5483 self.tcx,
5484 Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
5485 )
5486 });
5487
5488 let obligation =
5489 Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
5490
5491 if self.predicate_must_hold_modulo_regions(&obligation) {
5492 let arg_span = self.tcx.hir_span(*arg_hir_id);
5493 err.multipart_suggestion(
5494 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use a unary tuple instead"))
})format!("use a unary tuple instead"),
5495 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(arg_span.shrink_to_lo(), "(".into()),
(arg_span.shrink_to_hi(), ",)".into())]))vec![(arg_span.shrink_to_lo(), "(".into()), (arg_span.shrink_to_hi(), ",)".into())],
5496 Applicability::MaybeIncorrect,
5497 );
5498 }
5499 }
5500
5501 pub(super) fn suggest_shadowed_inherent_method(
5502 &self,
5503 err: &mut Diag<'_>,
5504 obligation: &PredicateObligation<'tcx>,
5505 trait_predicate: ty::PolyTraitPredicate<'tcx>,
5506 ) {
5507 let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else {
5508 return;
5509 };
5510 let Node::Expr(call) = self.tcx.hir_node(*call_hir_id) else { return };
5511 let hir::ExprKind::MethodCall(segment, rcvr, args, ..) = call.kind else { return };
5512 let Some(typeck) = &self.typeck_results else { return };
5513 let Some(rcvr_ty) = typeck.expr_ty_adjusted_opt(rcvr) else { return };
5514 let rcvr_ty = self.resolve_vars_if_possible(rcvr_ty);
5515 let autoderef = (self.autoderef_steps)(rcvr_ty);
5516 for (ty, def_id) in autoderef.iter().filter_map(|(ty, obligations)| {
5517 if let ty::Adt(def, _) = ty.kind()
5518 && *ty != rcvr_ty.peel_refs()
5519 && obligations.iter().all(|obligation| self.predicate_may_hold(obligation))
5520 {
5521 Some((ty, def.did()))
5522 } else {
5523 None
5524 }
5525 }) {
5526 for impl_def_id in self.tcx.inherent_impls(def_id) {
5527 if *impl_def_id == trait_predicate.def_id() {
5528 continue;
5529 }
5530 for m in self
5531 .tcx
5532 .provided_trait_methods(*impl_def_id)
5533 .filter(|m| m.name() == segment.ident.name)
5534 {
5535 let fn_sig = self.tcx.fn_sig(m.def_id);
5536 if fn_sig.skip_binder().inputs().skip_binder().len() != args.len() + 1 {
5537 continue;
5538 }
5539 let rcvr_ty = fn_sig.skip_binder().input(0).skip_binder();
5540 let (mutability, _ty) = match rcvr_ty.kind() {
5541 ty::Ref(_, ty, hir::Mutability::Mut) => ("&mut ", ty),
5542 ty::Ref(_, ty, _) => ("&", ty),
5543 _ => ("", &rcvr_ty),
5544 };
5545 let path = self.tcx.def_path_str(def_id);
5546 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there\'s an inherent method on `{0}` of the same name, which can be auto-dereferenced from `{1}`",
ty, rcvr_ty))
})format!(
5547 "there's an inherent method on `{ty}` of the same name, which can be \
5548 auto-dereferenced from `{rcvr_ty}`"
5549 ));
5550 err.multipart_suggestion(
5551 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to access the inherent method on `{0}`, use the fully-qualified path",
ty))
})format!(
5552 "to access the inherent method on `{ty}`, use the fully-qualified path",
5553 ),
5554 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(call.span.until(rcvr.span),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2}::{0}({1}", m.name(),
mutability, path))
})),
match &args {
[] =>
(rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
")".to_string()),
[first, ..] =>
(rcvr.span.between(first.span), ", ".to_string()),
}]))vec![
5555 (
5556 call.span.until(rcvr.span),
5557 format!("{path}::{}({}", m.name(), mutability),
5558 ),
5559 match &args {
5560 [] => (
5561 rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
5562 ")".to_string(),
5563 ),
5564 [first, ..] => (rcvr.span.between(first.span), ", ".to_string()),
5565 },
5566 ],
5567 Applicability::MaybeIncorrect,
5568 );
5569 }
5570 }
5571 }
5572 }
5573
5574 pub(super) fn explain_hrtb_projection(
5575 &self,
5576 diag: &mut Diag<'_>,
5577 pred: ty::PolyTraitPredicate<'tcx>,
5578 param_env: ty::ParamEnv<'tcx>,
5579 cause: &ObligationCause<'tcx>,
5580 ) {
5581 if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
5582 {
5583 self.probe(|_| {
5584 let ocx = ObligationCtxt::new(self);
5585 self.enter_forall(pred, |pred| {
5586 let pred = ocx.normalize(
5587 &ObligationCause::dummy(),
5588 param_env,
5589 Unnormalized::new_wip(pred),
5590 );
5591 ocx.register_obligation(Obligation::new(
5592 self.tcx,
5593 ObligationCause::dummy(),
5594 param_env,
5595 pred,
5596 ));
5597 });
5598 if !ocx.try_evaluate_obligations().is_empty() {
5599 return;
5601 }
5602
5603 if let ObligationCauseCode::FunctionArg {
5604 call_hir_id,
5605 arg_hir_id,
5606 parent_code: _,
5607 } = cause.code()
5608 {
5609 let arg_span = self.tcx.hir_span(*arg_hir_id);
5610 let mut sp: MultiSpan = arg_span.into();
5611
5612 sp.push_span_label(
5613 arg_span,
5614 "the trait solver is unable to infer the \
5615 generic types that should be inferred from this argument",
5616 );
5617 sp.push_span_label(
5618 self.tcx.hir_span(*call_hir_id),
5619 "add turbofish arguments to this call to \
5620 specify the types manually, even if it's redundant",
5621 );
5622 diag.span_note(
5623 sp,
5624 "this is a known limitation of the trait solver that \
5625 will be lifted in the future",
5626 );
5627 } else {
5628 let mut sp: MultiSpan = cause.span.into();
5629 sp.push_span_label(
5630 cause.span,
5631 "try adding turbofish arguments to this expression to \
5632 specify the types manually, even if it's redundant",
5633 );
5634 diag.span_note(
5635 sp,
5636 "this is a known limitation of the trait solver that \
5637 will be lifted in the future",
5638 );
5639 }
5640 });
5641 }
5642 }
5643
5644 pub(super) fn suggest_desugaring_async_fn_in_trait(
5645 &self,
5646 err: &mut Diag<'_>,
5647 trait_pred: ty::PolyTraitPredicate<'tcx>,
5648 ) {
5649 if self.tcx.features().return_type_notation() {
5651 return;
5652 }
5653
5654 let trait_def_id = trait_pred.def_id();
5655
5656 if !self.tcx.trait_is_auto(trait_def_id) {
5658 return;
5659 }
5660
5661 let ty::Alias(alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, .. }) =
5663 trait_pred.self_ty().skip_binder().kind()
5664 else {
5665 return;
5666 };
5667 let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
5668 self.tcx.opt_rpitit_info(*def_id)
5669 else {
5670 return;
5671 };
5672
5673 let auto_trait = self.tcx.def_path_str(trait_def_id);
5674 let Some(fn_def_id) = fn_def_id.as_local() else {
5676 if self.tcx.asyncness(fn_def_id).is_async() {
5678 err.span_note(
5679 self.tcx.def_span(fn_def_id),
5680 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` is an `async fn` in trait, which does not automatically imply that its future is `{2}`",
alias_ty.trait_ref(self.tcx), self.tcx.item_name(fn_def_id),
auto_trait))
})format!(
5681 "`{}::{}` is an `async fn` in trait, which does not \
5682 automatically imply that its future is `{auto_trait}`",
5683 alias_ty.trait_ref(self.tcx),
5684 self.tcx.item_name(fn_def_id)
5685 ),
5686 );
5687 }
5688 return;
5689 };
5690 let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
5691 return;
5692 };
5693
5694 let (sig, body) = item.expect_fn();
5696 let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
5697 sig.decl.output
5698 else {
5699 return;
5701 };
5702
5703 if opaq_def.def_id.to_def_id() != opaque_def_id {
5706 return;
5707 }
5708
5709 let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
5710 self.tcx,
5711 *sig,
5712 *body,
5713 opaque_def_id.expect_local(),
5714 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}", auto_trait))
})format!(" + {auto_trait}"),
5715 ) else {
5716 return;
5717 };
5718
5719 let function_name = self.tcx.def_path_str(fn_def_id);
5720 err.multipart_suggestion(
5721 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` can be made part of the associated future\'s guarantees for all implementations of `{1}`",
auto_trait, function_name))
})format!(
5722 "`{auto_trait}` can be made part of the associated future's \
5723 guarantees for all implementations of `{function_name}`"
5724 ),
5725 sugg,
5726 Applicability::MachineApplicable,
5727 );
5728 }
5729
5730 pub fn ty_kind_suggestion(
5731 &self,
5732 param_env: ty::ParamEnv<'tcx>,
5733 ty: Ty<'tcx>,
5734 ) -> Option<String> {
5735 let tcx = self.infcx.tcx;
5736 let implements_default = |ty| {
5737 let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
5738 return false;
5739 };
5740 self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
5741 };
5742
5743 Some(match *ty.kind() {
5744 ty::Never | ty::Error(_) => return None,
5745 ty::Bool => "false".to_string(),
5746 ty::Char => "\'x\'".to_string(),
5747 ty::Int(_) | ty::Uint(_) => "42".into(),
5748 ty::Float(_) => "3.14159".into(),
5749 ty::Slice(_) => "[]".to_string(),
5750 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
5751 "vec![]".to_string()
5752 }
5753 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
5754 "String::new()".to_string()
5755 }
5756 ty::Adt(def, args) if def.is_box() => {
5757 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Box::new({0})",
self.ty_kind_suggestion(param_env, args[0].expect_ty())?))
})format!("Box::new({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
5758 }
5759 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
5760 "None".to_string()
5761 }
5762 ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
5763 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Ok({0})",
self.ty_kind_suggestion(param_env, args[0].expect_ty())?))
})format!("Ok({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
5764 }
5765 ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
5766 ty::Ref(_, ty, mutability) => {
5767 if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
5768 "\"\"".to_string()
5769 } else {
5770 let ty = self.ty_kind_suggestion(param_env, ty)?;
5771 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
ty))
})format!("&{}{ty}", mutability.prefix_str())
5772 }
5773 }
5774 ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
5775 if len == 0 {
5776 "[]".to_string()
5777 } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
5778 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[{0}; {1}]",
self.ty_kind_suggestion(param_env, ty)?, len))
})format!("[{}; {}]", self.ty_kind_suggestion(param_env, ty)?, len)
5780 } else {
5781 "/* value */".to_string()
5782 }
5783 }
5784 ty::Tuple(tys) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}{1})",
tys.iter().map(|ty|
self.ty_kind_suggestion(param_env,
ty)).collect::<Option<Vec<String>>>()?.join(", "),
if tys.len() == 1 { "," } else { "" }))
})format!(
5785 "({}{})",
5786 tys.iter()
5787 .map(|ty| self.ty_kind_suggestion(param_env, ty))
5788 .collect::<Option<Vec<String>>>()?
5789 .join(", "),
5790 if tys.len() == 1 { "," } else { "" }
5791 ),
5792 _ => "/* value */".to_string(),
5793 })
5794 }
5795
5796 pub(super) fn suggest_add_result_as_return_type(
5800 &self,
5801 obligation: &PredicateObligation<'tcx>,
5802 err: &mut Diag<'_>,
5803 trait_pred: ty::PolyTraitPredicate<'tcx>,
5804 ) {
5805 if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
5806 return;
5807 }
5808
5809 fn choose_suggest_items<'tcx, 'hir>(
5816 tcx: TyCtxt<'tcx>,
5817 node: hir::Node<'hir>,
5818 ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
5819 match node {
5820 hir::Node::Item(item)
5821 if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
5822 {
5823 Some((sig.decl, body_id))
5824 }
5825 hir::Node::ImplItem(item)
5826 if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
5827 {
5828 let parent = tcx.parent_hir_node(item.hir_id());
5829 if let hir::Node::Item(item) = parent
5830 && let hir::ItemKind::Impl(imp) = item.kind
5831 && imp.of_trait.is_none()
5832 {
5833 return Some((sig.decl, body_id));
5834 }
5835 None
5836 }
5837 _ => None,
5838 }
5839 }
5840
5841 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
5842 if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
5843 && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
5844 && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
5845 && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
5846 && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5847 && self.tcx.is_diagnostic_item(sym::Result, def.did())
5848 {
5849 let mut sugg_spans =
5850 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ret_span,
" -> Result<(), Box<dyn std::error::Error>>".to_string())]))vec![(ret_span, " -> Result<(), Box<dyn std::error::Error>>".to_string())];
5851 let body = self.tcx.hir_body(body_id);
5852 if let hir::ExprKind::Block(b, _) = body.value.kind
5853 && b.expr.is_none()
5854 {
5855 let span = self.tcx.sess.source_map().end_point(b.span);
5857 sugg_spans.push((
5858 span.shrink_to_lo(),
5859 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", " Ok(())\n",
self.tcx.sess.source_map().indentation_before(span).unwrap_or_default()))
})format!(
5860 "{}{}",
5861 " Ok(())\n",
5862 self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
5863 ),
5864 ));
5865 }
5866 err.multipart_suggestion(
5867 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding return type"))
})format!("consider adding return type"),
5868 sugg_spans,
5869 Applicability::MaybeIncorrect,
5870 );
5871 }
5872 }
5873
5874 #[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("suggest_unsized_bound_if_applicable",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5874u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
obligation.predicate.kind().skip_binder() else { return; };
let (ObligationCauseCode::WhereClause(item_def_id, span) |
ObligationCauseCode::WhereClauseInExpr(item_def_id, span,
..)) =
*obligation.cause.code().peel_derives() else { return; };
if span.is_dummy() { return; }
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5894",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5894u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["pred",
"item_def_id", "span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&pred) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&item_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&span) as
&dyn Value))])
});
} else { ; }
};
let (Some(node), true) =
(self.tcx.hir_get_if_local(item_def_id),
self.tcx.is_lang_item(pred.def_id(),
LangItem::Sized)) else { return; };
let Some(generics) = node.generics() else { return; };
let sized_trait = self.tcx.lang_items().sized_trait();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5907",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5907u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["generics.params"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&generics.params)
as &dyn Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5908",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5908u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["generics.predicates"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&generics.predicates)
as &dyn Value))])
});
} else { ; }
};
let Some(DesugaringKind::DefaultBound { def }) =
span.desugaring_kind() else { return; };
let Some(param) =
generics.params.iter().find(|param|
param.def_id.to_def_id() == def) else { return; };
let explicitly_sized =
generics.bounds_for_param(param.def_id).flat_map(|bp|
bp.bounds).any(|bound|
bound.trait_ref().and_then(|tr| tr.trait_def_id()) ==
sized_trait);
if explicitly_sized { return; }
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5925",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5925u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["param"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m) as
&dyn Value))])
});
} else { ; }
};
match node {
hir::Node::Item(item @ hir::Item {
kind: hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) |
hir::ItemKind::Union(..), .. }) => {
if self.suggest_indirection_for_unsized(err, item, param) {
return;
}
}
_ => {}
};
let (span, separator, open_paren_sp) =
if let Some((s, open_paren_sp)) =
generics.bounds_span_for_suggestions(param.def_id) {
(s, " +", open_paren_sp)
} else {
(param.name.ident().span.shrink_to_hi(), ":", None)
};
let mut suggs = ::alloc::vec::Vec::new();
let suggestion =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ?Sized", separator))
});
if let Some(open_paren_sp) = open_paren_sp {
suggs.push((open_paren_sp, "(".to_string()));
suggs.push((span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("){0}", suggestion))
})));
} else { suggs.push((span, suggestion)); }
err.multipart_suggestion("consider relaxing the implicit `Sized` restriction",
suggs, Applicability::MachineApplicable);
}
}
}#[instrument(level = "debug", skip_all)]
5875 pub(super) fn suggest_unsized_bound_if_applicable(
5876 &self,
5877 err: &mut Diag<'_>,
5878 obligation: &PredicateObligation<'tcx>,
5879 ) {
5880 let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
5881 obligation.predicate.kind().skip_binder()
5882 else {
5883 return;
5884 };
5885 let (ObligationCauseCode::WhereClause(item_def_id, span)
5886 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
5887 *obligation.cause.code().peel_derives()
5888 else {
5889 return;
5890 };
5891 if span.is_dummy() {
5892 return;
5893 }
5894 debug!(?pred, ?item_def_id, ?span);
5895
5896 let (Some(node), true) = (
5897 self.tcx.hir_get_if_local(item_def_id),
5898 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
5899 ) else {
5900 return;
5901 };
5902
5903 let Some(generics) = node.generics() else {
5904 return;
5905 };
5906 let sized_trait = self.tcx.lang_items().sized_trait();
5907 debug!(?generics.params);
5908 debug!(?generics.predicates);
5909 let Some(DesugaringKind::DefaultBound { def }) = span.desugaring_kind() else {
5910 return;
5911 };
5912 let Some(param) = generics.params.iter().find(|param| param.def_id.to_def_id() == def)
5913 else {
5914 return;
5915 };
5916 let explicitly_sized = generics
5919 .bounds_for_param(param.def_id)
5920 .flat_map(|bp| bp.bounds)
5921 .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
5922 if explicitly_sized {
5923 return;
5924 }
5925 debug!(?param);
5926 match node {
5927 hir::Node::Item(
5928 item @ hir::Item {
5929 kind:
5931 hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
5932 ..
5933 },
5934 ) => {
5935 if self.suggest_indirection_for_unsized(err, item, param) {
5936 return;
5937 }
5938 }
5939 _ => {}
5940 };
5941
5942 let (span, separator, open_paren_sp) =
5944 if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
5945 (s, " +", open_paren_sp)
5946 } else {
5947 (param.name.ident().span.shrink_to_hi(), ":", None)
5948 };
5949
5950 let mut suggs = vec![];
5951 let suggestion = format!("{separator} ?Sized");
5952
5953 if let Some(open_paren_sp) = open_paren_sp {
5954 suggs.push((open_paren_sp, "(".to_string()));
5955 suggs.push((span, format!("){suggestion}")));
5956 } else {
5957 suggs.push((span, suggestion));
5958 }
5959
5960 err.multipart_suggestion(
5961 "consider relaxing the implicit `Sized` restriction",
5962 suggs,
5963 Applicability::MachineApplicable,
5964 );
5965 }
5966
5967 fn suggest_indirection_for_unsized(
5968 &self,
5969 err: &mut Diag<'_>,
5970 item: &hir::Item<'tcx>,
5971 param: &hir::GenericParam<'tcx>,
5972 ) -> bool {
5973 let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
5977 visitor.visit_item(item);
5978 if visitor.invalid_spans.is_empty() {
5979 return false;
5980 }
5981 let mut multispan: MultiSpan = param.span.into();
5982 multispan.push_span_label(
5983 param.span,
5984 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this could be changed to `{0}: ?Sized`...",
param.name.ident()))
})format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
5985 );
5986 for sp in visitor.invalid_spans {
5987 multispan.push_span_label(
5988 sp,
5989 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...if indirection were used here: `Box<{0}>`",
param.name.ident()))
})format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
5990 );
5991 }
5992 err.span_help(
5993 multispan,
5994 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you could relax the implicit `Sized` bound on `{0}` if it were used through indirection like `&{0}` or `Box<{0}>`",
param.name.ident()))
})format!(
5995 "you could relax the implicit `Sized` bound on `{T}` if it were \
5996 used through indirection like `&{T}` or `Box<{T}>`",
5997 T = param.name.ident(),
5998 ),
5999 );
6000 true
6001 }
6002 pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
6003 &self,
6004 err: &mut Diag<'_>,
6005 predicate: T,
6006 param_env: ty::ParamEnv<'tcx>,
6007 cause_code: &ObligationCauseCode<'tcx>,
6008 ) where
6009 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
6010 {
6011 let tcx = self.tcx;
6012 let predicate = predicate.upcast(tcx);
6013 match *cause_code {
6014 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
6015 if let Some(typeck_results) = &self.typeck_results
6016 && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
6017 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
6018 && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
6019 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
6020 {
6021 if let Some(pred) = predicate.as_trait_clause()
6022 && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
6023 && self
6024 .infcx
6025 .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
6026 .must_apply_modulo_regions()
6027 {
6028 let lhs_span = tcx.hir_span(lhs_hir_id);
6029 let sm = tcx.sess.source_map();
6030 if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
6031 && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
6032 {
6033 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `PartialEq<{1}>`",
rhs_ty, lhs_ty))
})format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
6034 err.multipart_suggestion(
6035 "consider swapping the equality",
6036 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lhs_span, rhs_snippet), (rhs_span, lhs_snippet)]))vec![(lhs_span, rhs_snippet), (rhs_span, lhs_snippet)],
6037 Applicability::MaybeIncorrect,
6038 );
6039 }
6040 }
6041 }
6042 _ => {}
6043 }
6044 }
6045}
6046
6047fn hint_missing_borrow<'tcx>(
6049 infcx: &InferCtxt<'tcx>,
6050 param_env: ty::ParamEnv<'tcx>,
6051 span: Span,
6052 found: Ty<'tcx>,
6053 expected: Ty<'tcx>,
6054 found_node: Node<'_>,
6055 err: &mut Diag<'_>,
6056) {
6057 if #[allow(non_exhaustive_omitted_patterns)] match found_node {
Node::TraitItem(..) => true,
_ => false,
}matches!(found_node, Node::TraitItem(..)) {
6058 return;
6059 }
6060
6061 let found_args = match found.kind() {
6062 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6063 kind => {
6064 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("found was converted to a FnPtr above but is now {0:?}",
kind))span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
6065 }
6066 };
6067 let expected_args = match expected.kind() {
6068 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6069 kind => {
6070 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("expected was converted to a FnPtr above but is now {0:?}",
kind))span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
6071 }
6072 };
6073
6074 let Some(fn_decl) = found_node.fn_decl() else {
6076 return;
6077 };
6078
6079 let args = fn_decl.inputs.iter();
6080
6081 let mut to_borrow = Vec::new();
6082 let mut remove_borrow = Vec::new();
6083
6084 for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
6085 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
6086 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
6087
6088 if infcx.can_eq(param_env, found_ty, expected_ty) {
6089 if found_refs.len() < expected_refs.len()
6091 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
6092 {
6093 to_borrow.push((
6094 arg.span.shrink_to_lo(),
6095 expected_refs[..expected_refs.len() - found_refs.len()]
6096 .iter()
6097 .map(|mutbl| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()))
6098 .collect::<Vec<_>>()
6099 .join(""),
6100 ));
6101 } else if found_refs.len() > expected_refs.len() {
6102 let mut span = arg.span.shrink_to_lo();
6103 let mut left = found_refs.len() - expected_refs.len();
6104 let mut ty = arg;
6105 while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
6106 && left > 0
6107 {
6108 span = span.with_hi(mut_ty.ty.span.lo());
6109 ty = mut_ty.ty;
6110 left -= 1;
6111 }
6112 if left == 0 {
6113 remove_borrow.push((span, String::new()));
6114 }
6115 }
6116 }
6117 }
6118
6119 if !to_borrow.is_empty() {
6120 err.subdiagnostic(diagnostics::AdjustSignatureBorrow::Borrow { to_borrow });
6121 }
6122
6123 if !remove_borrow.is_empty() {
6124 err.subdiagnostic(diagnostics::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
6125 }
6126}
6127
6128#[derive(#[automatically_derived]
impl<'v> ::core::fmt::Debug for SelfVisitor<'v> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "SelfVisitor",
"paths", &self.paths, "name", &&self.name)
}
}Debug)]
6131pub struct SelfVisitor<'v> {
6132 pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
6133 pub name: Option<Symbol>,
6134}
6135
6136impl<'v> Visitor<'v> for SelfVisitor<'v> {
6137 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
6138 if let hir::TyKind::Path(path) = ty.kind
6139 && let hir::QPath::TypeRelative(inner_ty, segment) = path
6140 && (Some(segment.ident.name) == self.name || self.name.is_none())
6141 && let hir::TyKind::Path(inner_path) = inner_ty.kind
6142 && let hir::QPath::Resolved(None, inner_path) = inner_path
6143 && let Res::SelfTyAlias { .. } = inner_path.res
6144 {
6145 self.paths.push(ty.as_unambig_ty());
6146 }
6147 hir::intravisit::walk_ty(self, ty);
6148 }
6149}
6150
6151#[derive(#[automatically_derived]
impl<'v> ::core::default::Default for ReturnsVisitor<'v> {
#[inline]
fn default() -> ReturnsVisitor<'v> {
ReturnsVisitor {
returns: ::core::default::Default::default(),
in_block_tail: ::core::default::Default::default(),
}
}
}Default)]
6154pub struct ReturnsVisitor<'v> {
6155 pub returns: Vec<&'v hir::Expr<'v>>,
6156 in_block_tail: bool,
6157}
6158
6159impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
6160 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6161 match ex.kind {
6166 hir::ExprKind::Ret(Some(ex)) => {
6167 self.returns.push(ex);
6168 }
6169 hir::ExprKind::Block(block, _) if self.in_block_tail => {
6170 self.in_block_tail = false;
6171 for stmt in block.stmts {
6172 hir::intravisit::walk_stmt(self, stmt);
6173 }
6174 self.in_block_tail = true;
6175 if let Some(expr) = block.expr {
6176 self.visit_expr(expr);
6177 }
6178 }
6179 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
6180 self.visit_expr(then);
6181 if let Some(el) = else_opt {
6182 self.visit_expr(el);
6183 }
6184 }
6185 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
6186 for arm in arms {
6187 self.visit_expr(arm.body);
6188 }
6189 }
6190 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
6192 _ => self.returns.push(ex),
6193 }
6194 }
6195
6196 fn visit_body(&mut self, body: &hir::Body<'v>) {
6197 if !!self.in_block_tail {
::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
6198 self.in_block_tail = true;
6199 hir::intravisit::walk_body(self, body);
6200 }
6201}
6202
6203#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
#[inline]
fn default() -> AwaitsVisitor {
AwaitsVisitor { awaits: ::core::default::Default::default() }
}
}Default)]
6205struct AwaitsVisitor {
6206 awaits: Vec<HirId>,
6207}
6208
6209impl<'v> Visitor<'v> for AwaitsVisitor {
6210 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6211 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
6212 self.awaits.push(id)
6213 }
6214 hir::intravisit::walk_expr(self, ex)
6215 }
6216}
6217
6218pub trait NextTypeParamName {
6222 fn next_type_param_name(&self, name: Option<&str>) -> String;
6223}
6224
6225impl NextTypeParamName for &[hir::GenericParam<'_>] {
6226 fn next_type_param_name(&self, name: Option<&str>) -> String {
6227 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
6229 let name = name.as_deref();
6230
6231 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
6233
6234 let used_names: Vec<Symbol> = self
6236 .iter()
6237 .filter_map(|param| match param.name {
6238 hir::ParamName::Plain(ident) => Some(ident.name),
6239 _ => None,
6240 })
6241 .collect();
6242
6243 possible_names
6245 .iter()
6246 .find(|n| !used_names.contains(&Symbol::intern(n)))
6247 .unwrap_or(&"ParamName")
6248 .to_string()
6249 }
6250}
6251
6252struct ReplaceImplTraitVisitor<'a> {
6254 ty_spans: &'a mut Vec<Span>,
6255 param_did: DefId,
6256}
6257
6258impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
6259 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
6260 if let hir::TyKind::Path(hir::QPath::Resolved(
6261 None,
6262 hir::Path { res: Res::Def(_, segment_did), .. },
6263 )) = t.kind
6264 {
6265 if self.param_did == *segment_did {
6266 self.ty_spans.push(t.span);
6271 return;
6272 }
6273 }
6274
6275 hir::intravisit::walk_ty(self, t);
6276 }
6277}
6278
6279pub(super) fn get_explanation_based_on_obligation<'tcx>(
6280 tcx: TyCtxt<'tcx>,
6281 obligation: &PredicateObligation<'tcx>,
6282 trait_predicate: ty::PolyTraitPredicate<'tcx>,
6283 pre_message: String,
6284 long_ty_path: &mut Option<PathBuf>,
6285) -> String {
6286 if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
6287 "consider using `()`, or a `Result`".to_owned()
6288 } else {
6289 let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
6290 ty::FnDef(_, _) => Some("fn item"),
6291 ty::Closure(_, _) => Some("closure"),
6292 _ => None,
6293 };
6294
6295 let desc = match ty_desc {
6296 Some(desc) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", desc))
})format!(" {desc}"),
6297 None => String::new(),
6298 };
6299 if let ty::PredicatePolarity::Positive = trait_predicate.polarity() {
6300 let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
6305 && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
6306 == Some(false);
6307 let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
6308
6309 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2}the {3}trait `{0}` is not implemented for{4} `{1}`",
trait_predicate.print_modifiers_and_trait_path(),
tcx.short_string(trait_predicate.self_ty().skip_binder(),
long_ty_path), pre_message, unstable, desc))
})format!(
6310 "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
6311 trait_predicate.print_modifiers_and_trait_path(),
6312 tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
6313 )
6314 } else {
6315 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}the trait bound `{1}` is not satisfied",
pre_message, trait_predicate))
})format!("{pre_message}the trait bound `{trait_predicate}` is not satisfied")
6319 }
6320 }
6321}
6322
6323struct ReplaceImplTraitFolder<'tcx> {
6325 tcx: TyCtxt<'tcx>,
6326 param: &'tcx ty::GenericParamDef,
6327 replace_ty: Ty<'tcx>,
6328}
6329
6330impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
6331 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
6332 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
6333 if self.param.index == *index {
6334 return self.replace_ty;
6335 }
6336 }
6337 t.super_fold_with(self)
6338 }
6339
6340 fn cx(&self) -> TyCtxt<'tcx> {
6341 self.tcx
6342 }
6343}
6344
6345pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
6346 tcx: TyCtxt<'tcx>,
6347 sig: hir::FnSig<'tcx>,
6348 body: hir::TraitFn<'tcx>,
6349 opaque_def_id: LocalDefId,
6350 add_bounds: &str,
6351) -> Option<Vec<(Span, String)>> {
6352 let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
6353 return None;
6354 };
6355 let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
6356
6357 let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
6358 let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
6359 return None;
6361 };
6362 let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
6363 else {
6364 return None;
6366 };
6367 let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
6368 else {
6369 return None;
6371 };
6372
6373 let mut sugg = if future_output_ty.span.is_empty() {
6374 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(async_span, String::new()),
(future_output_ty.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" -> impl std::future::Future<Output = ()>{0}",
add_bounds))
}))]))vec![
6375 (async_span, String::new()),
6376 (
6377 future_output_ty.span,
6378 format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
6379 ),
6380 ]
6381 } else {
6382 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(future_output_ty.span.shrink_to_lo(),
"impl std::future::Future<Output = ".to_owned()),
(future_output_ty.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(">{0}", add_bounds))
})), (async_span, String::new())]))vec![
6383 (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
6384 (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
6385 (async_span, String::new()),
6386 ]
6387 };
6388
6389 if let hir::TraitFn::Provided(body) = body {
6391 let body = tcx.hir_body(body);
6392 let body_span = body.value.span;
6393 let body_span_without_braces =
6394 body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
6395 if body_span_without_braces.is_empty() {
6396 sugg.push((body_span_without_braces, " async {} ".to_owned()));
6397 } else {
6398 sugg.extend([
6399 (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
6400 (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
6401 ]);
6402 }
6403 }
6404
6405 Some(sugg)
6406}
6407
6408fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
6411 tcx: TyCtxt<'_>,
6412 err: &mut Diag<'_, G>,
6413 self_ty_str: &str,
6414 trait_name: &str,
6415 predicate: ty::Predicate<'_>,
6416 generics: &hir::Generics<'_>,
6417 data: &ImplDerivedCause<'_>,
6418) {
6419 let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
6420 return;
6421 };
6422 let ty::ClauseKind::Projection(proj) = clause else {
6423 return;
6424 };
6425 let Some(name) = tcx
6426 .opt_rpitit_info(proj.def_id())
6427 .and_then(|data| match data {
6428 ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => Some(tcx.item_name(fn_def_id)),
6429 ty::ImplTraitInTraitData::Impl { .. } => None,
6430 })
6431 .or_else(|| tcx.opt_item_name(proj.def_id()))
6432 else {
6433 return;
6434 };
6435 let mut predicates = generics.predicates.iter().peekable();
6436 let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
6437 while let Some(pred) = predicates.next() {
6438 let curr_span = pred.span;
6439 let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
6440 continue;
6441 };
6442 let mut bounds = pred.bounds.iter();
6443 while let Some(bound) = bounds.next() {
6444 let Some(trait_ref) = bound.trait_ref() else {
6445 continue;
6446 };
6447 if bound.span() != data.span {
6448 continue;
6449 }
6450 if let hir::TyKind::Path(path) = pred.bounded_ty.kind
6451 && let hir::QPath::TypeRelative(ty, segment) = path
6452 && segment.ident.name == name
6453 && let hir::TyKind::Path(inner_path) = ty.kind
6454 && let hir::QPath::Resolved(None, inner_path) = inner_path
6455 && let Res::SelfTyAlias { .. } = inner_path.res
6456 {
6457 let span = if pred.origin == hir::PredicateOrigin::WhereClause
6460 && generics
6461 .predicates
6462 .iter()
6463 .filter(|p| {
6464 #[allow(non_exhaustive_omitted_patterns)] match p.kind {
hir::WherePredicateKind::BoundPredicate(p) if
hir::PredicateOrigin::WhereClause == p.origin => true,
_ => false,
}matches!(
6465 p.kind,
6466 hir::WherePredicateKind::BoundPredicate(p)
6467 if hir::PredicateOrigin::WhereClause == p.origin
6468 )
6469 })
6470 .count()
6471 == 1
6472 {
6473 generics.where_clause_span
6476 } else if let Some(next_pred) = predicates.peek()
6477 && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
6478 && pred.origin == next.origin
6479 {
6480 curr_span.until(next_pred.span)
6482 } else if let Some((prev, prev_span)) = prev
6483 && pred.origin == prev.origin
6484 {
6485 prev_span.shrink_to_hi().to(curr_span)
6487 } else if pred.origin == hir::PredicateOrigin::WhereClause {
6488 curr_span.with_hi(generics.where_clause_span.hi())
6489 } else {
6490 curr_span
6491 };
6492
6493 err.span_suggestion_verbose(
6494 span,
6495 "associated type for the current `impl` cannot be restricted in `where` \
6496 clauses, remove this bound",
6497 "",
6498 Applicability::MaybeIncorrect,
6499 );
6500 }
6501 if let Some(new) =
6502 tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
6503 tcx,
6504 Ident::with_dummy_span(name),
6505 ty::AssocTag::Type,
6506 data.impl_or_alias_def_id,
6507 )
6508 {
6509 let span = tcx.def_span(new.def_id);
6512 err.span_label(
6513 span,
6514 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("associated type `<{0} as {1}>::{2}` is specified here",
self_ty_str, trait_name, name))
})format!(
6515 "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
6516 here",
6517 ),
6518 );
6519 let mut visitor = SelfVisitor { name: Some(name), .. };
6522 visitor.visit_trait_ref(trait_ref);
6523 for path in visitor.paths {
6524 err.span_suggestion_verbose(
6525 path.span,
6526 "replace the associated type with the type specified in this `impl`",
6527 tcx.type_of(new.def_id).skip_binder(),
6528 Applicability::MachineApplicable,
6529 );
6530 }
6531 } else {
6532 let mut visitor = SelfVisitor { name: None, .. };
6533 visitor.visit_trait_ref(trait_ref);
6534 let span: MultiSpan =
6535 visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
6536 err.span_note(
6537 span,
6538 "associated types for the current `impl` cannot be restricted in `where` \
6539 clauses",
6540 );
6541 }
6542 }
6543 prev = Some((pred, curr_span));
6544 }
6545}
6546
6547fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
6548 let mut refs = ::alloc::vec::Vec::new()vec![];
6549
6550 while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
6551 ty = *new_ty;
6552 refs.push(*mutbl);
6553 }
6554
6555 (ty, refs)
6556}
6557
6558struct FindTypeParam {
6561 param: rustc_span::Symbol,
6562 invalid_spans: Vec<Span> = Vec::new(),
6563 nested: bool = false,
6564}
6565
6566impl<'v> Visitor<'v> for FindTypeParam {
6567 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
6568 }
6570
6571 fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
6572 match ty.kind {
6579 hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
6580 hir::TyKind::Path(hir::QPath::Resolved(None, path))
6581 if let [segment] = path.segments
6582 && segment.ident.name == self.param =>
6583 {
6584 if !self.nested {
6585 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6585",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6585u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("FindTypeParam::visit_ty")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty) as
&dyn Value))])
});
} else { ; }
};debug!(?ty, "FindTypeParam::visit_ty");
6586 self.invalid_spans.push(ty.span);
6587 }
6588 }
6589 hir::TyKind::Path(_) => {
6590 let prev = self.nested;
6591 self.nested = true;
6592 hir::intravisit::walk_ty(self, ty);
6593 self.nested = prev;
6594 }
6595 _ => {
6596 hir::intravisit::walk_ty(self, ty);
6597 }
6598 }
6599 }
6600}
6601
6602struct ParamFinder {
6605 params: Vec<Symbol> = Vec::new(),
6606}
6607
6608impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
6609 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
6610 match t.kind() {
6611 ty::Param(p) => self.params.push(p.name),
6612 _ => {}
6613 }
6614 t.super_visit_with(self)
6615 }
6616}
6617
6618impl ParamFinder {
6619 fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
6622 if self.params.is_empty() {
6623 return true;
6626 }
6627 generics.params.iter().any(|p| match p.name {
6628 hir::ParamName::Plain(p_name) => {
6629 self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
6631 }
6632 _ => true,
6633 })
6634 }
6635}