1use std::borrow::Cow;
4use std::path::PathBuf;
5use std::{debug_assert_matches, iter};
6
7use itertools::{EitherOrBoth, Itertools};
8use rustc_attr_ir::lang_items::{self, LangItem};
9use rustc_data_structures::fx::FxHashSet;
10use rustc_errors::codes::*;
11use rustc_errors::{
12 Applicability, Diag, MultiSpan, Style, SuggestionStyle, pluralize, struct_span_code_err,
13};
14use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
15use rustc_hir::def_id::DefId;
16use rustc_hir::intravisit::Visitor;
17use rustc_hir::{
18 self as hir, AmbigArg, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node,
19 expr_needs_parens,
20};
21use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
22use rustc_infer::traits::ImplSource;
23use rustc_middle::middle::privacy::Level;
24use rustc_middle::traits::IsConstable;
25use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind};
26use rustc_middle::ty::error::TypeError;
27use rustc_middle::ty::print::{
28 PrintPolyTraitClauseExt as _, PrintPolyTraitRefExt, PrintTraitClauseExt as _,
29 PrintTraitRefExt as _, with_forced_trimmed_paths, with_no_trimmed_paths,
30 with_types_for_suggestion,
31};
32use rustc_middle::ty::{
33 self, AdtKind, CallerBoundsIterator, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt,
34 TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitableExt, TypeVisitor,
35 TypeckResults, Unnormalized, Upcast, suggest_arbitrary_trait_bound,
36 suggest_constraining_type_param,
37};
38use rustc_span::def_id::LocalDefId;
39use rustc_span::{
40 BytePos, DUMMY_SP, DesugaringKind, ExpnKind, Ident, MacroKind, Span, Symbol, bug, kw, span_bug,
41 sym,
42};
43use tracing::{debug, instrument};
44
45use super::{
46 DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode,
47 PredicateObligation,
48};
49use crate::diagnostics;
50use crate::error_reporting::TypeErrCtxt;
51use crate::infer::InferCtxtExt as _;
52use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
53use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt, SelectionContext};
54
55#[derive(#[automatically_derived]impl ::core::fmt::Debug for CoroutineInteriorOrUpvar {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Interior(__self_0, __self_1) =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Interior", __self_0, &__self_1),
Self::Upvar(__self_0) =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Upvar",
&__self_0),
}
}
}Debug)]
56pub enum CoroutineInteriorOrUpvar {
57 Interior(Span, Option<(Span, Option<Span>)>),
59 Upvar(Span),
61}
62
63#[derive(#[automatically_derived]impl<'a, 'tcx> ::core::fmt::Debug for
CoroutineData<'a, 'tcx> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "CoroutineData",
&&self.0)
}
}Debug)]
66struct CoroutineData<'a, 'tcx>(&'a TypeckResults<'tcx>);
67
68impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
69 fn try_get_upvar_span<F>(
73 &self,
74 infer_context: &InferCtxt<'tcx>,
75 coroutine_did: DefId,
76 ty_matches: F,
77 ) -> Option<CoroutineInteriorOrUpvar>
78 where
79 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
80 {
81 infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| {
82 upvars.iter().find_map(|(upvar_id, upvar)| {
83 let upvar_ty = self.0.node_type(*upvar_id);
84 let upvar_ty = infer_context.deeply_resolve_ignoring_regions(upvar_ty);
85 ty_matches(ty::Binder::dummy(upvar_ty))
86 .then(|| CoroutineInteriorOrUpvar::Upvar(upvar.span))
87 })
88 })
89 }
90
91 fn get_from_await_ty<F>(
95 &self,
96 visitor: AwaitsVisitor,
97 tcx: TyCtxt<'tcx>,
98 ty_matches: F,
99 ) -> Option<Span>
100 where
101 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
102 {
103 visitor
104 .awaits
105 .into_iter()
106 .map(|id| tcx.hir_expect_expr(id))
107 .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
108 .map(|expr| expr.span)
109 }
110}
111
112fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
113 (
114 generics.tail_span_for_predicate_suggestion(),
115 {
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)),
116 )
117}
118
119pub fn suggest_restriction<'tcx>(
123 tcx: TyCtxt<'tcx>,
124 item_id: LocalDefId,
125 hir_generics: &hir::Generics<'tcx>,
126 msg: &str,
127 err: &mut Diag<'_>,
128 fn_sig: Option<&hir::FnSig<'_>>,
129 projection: Option<ty::ProjectionAliasTy<'_>>,
130 trait_pred: ty::PolyTraitClause<'tcx>,
131 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
137) {
138 if hir_generics.where_clause_span.from_expansion()
139 || hir_generics.where_clause_span.desugaring_kind().is_some()
140 || projection.is_some_and(|projection| {
141 (tcx.is_impl_trait_in_trait(projection.kind) && !tcx.features().return_type_notation())
142 || tcx.lookup_stability(projection.kind).is_some_and(|stab| stab.is_unstable())
143 })
144 {
145 return;
146 }
147 let generics = tcx.generics_of(item_id);
148 if let Some((param, bound_str, fn_sig)) =
150 fn_sig.zip(projection).and_then(|(sig, p)| match *p.projection_self_ty().kind() {
151 ty::Param(param) => {
153 let param_def = generics.type_param(param, tcx);
154 if param_def.kind.is_synthetic() {
155 let bound_str =
156 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
157 return Some((param_def, bound_str, sig));
158 }
159 None
160 }
161 _ => None,
162 })
163 {
164 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
165 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
166 tcx,
167 param,
168 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
169 .to_ty(tcx),
170 });
171 if !trait_pred.is_suggestable(tcx, false) {
172 return;
173 }
174 let mut ty_spans = ::alloc::vec::Vec::new()vec![];
182 for input in fn_sig.decl.inputs {
183 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
184 .visit_ty_unambig(input);
185 }
186 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}");
188
189 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![
190 if let Some(span) = hir_generics.span_for_param_suggestion() {
191 (span, format!(", {type_param}"))
192 } else {
193 (hir_generics.span, format!("<{type_param}>"))
194 },
195 predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
198 ];
199 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
200
201 err.multipart_suggestion(
204 "introduce a type parameter with a trait bound instead of using `impl Trait`",
205 sugg,
206 Applicability::MaybeIncorrect,
207 );
208 } else {
209 if !trait_pred.is_suggestable(tcx, false) {
210 return;
211 }
212 let (sp, suggestion) = match (
214 hir_generics
215 .params
216 .iter()
217 .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, .. })),
218 super_traits,
219 ) {
220 (_, None) => predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
221 (None, Some((ident, []))) => (
222 ident.span.shrink_to_hi(),
223 ::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()),
224 ),
225 (_, Some((_, [.., bounds]))) => (
226 bounds.span().shrink_to_hi(),
227 ::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()),
228 ),
229 (Some(_), Some((_, []))) => (
230 hir_generics.span.shrink_to_hi(),
231 ::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()),
232 ),
233 };
234
235 err.span_suggestion_verbose(
236 sp,
237 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider further restricting {0}",
msg))
})format!("consider further restricting {msg}"),
238 suggestion,
239 Applicability::MachineApplicable,
240 );
241 }
242}
243
244struct PeeledRef<'tcx> {
247 span: Span,
249 peeled_ty: Ty<'tcx>,
251}
252
253impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
254 pub fn note_field_shadowed_by_private_candidate_in_cause(
255 &self,
256 err: &mut Diag<'_>,
257 cause: &ObligationCause<'tcx>,
258 param_env: ty::ParamEnv<'tcx>,
259 ) {
260 let mut hir_ids = FxHashSet::default();
261 let mut next_code = Some(cause.code());
264 while let Some(cause_code) = next_code {
265 match cause_code {
266 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
267 hir_ids.insert(*lhs_hir_id);
268 hir_ids.insert(*rhs_hir_id);
269 }
270 ObligationCauseCode::FunctionArg { arg_hir_id, .. }
271 | ObligationCauseCode::ReturnValue(arg_hir_id)
272 | ObligationCauseCode::AwaitableExpr(arg_hir_id)
273 | ObligationCauseCode::BlockTailExpression(arg_hir_id, _)
274 | ObligationCauseCode::UnOp { hir_id: arg_hir_id } => {
275 hir_ids.insert(*arg_hir_id);
276 }
277 ObligationCauseCode::OpaqueReturnType(Some((_, hir_id))) => {
278 hir_ids.insert(*hir_id);
279 }
280 _ => {}
281 }
282 next_code = cause_code.parent();
283 }
284
285 if !cause.span.is_dummy()
286 && let Some(body) = self.tcx.hir_maybe_body_owned_by(cause.body_def_id)
287 {
288 let mut expr_finder = FindExprBySpan::new(cause.span, self.tcx);
289 expr_finder.visit_body(body);
290 if let Some(expr) = expr_finder.result {
291 hir_ids.insert(expr.hir_id);
292 }
293 }
294
295 #[allow(rustc::potential_query_instability)]
297 let mut hir_ids: Vec<_> = hir_ids.into_iter().collect();
298 let source_map = self.tcx.sess.source_map();
299 hir_ids.sort_by_cached_key(|hir_id| {
300 let span = self.tcx.hir_span(*hir_id);
301 let lo = source_map.lookup_byte_offset(span.lo());
302 let hi = source_map.lookup_byte_offset(span.hi());
303 (lo.sf.name.prefer_remapped_unconditionally().to_string(), lo.pos.0, hi.pos.0)
304 });
305
306 for hir_id in hir_ids {
307 self.note_field_shadowed_by_private_candidate(err, hir_id, param_env);
308 }
309 }
310
311 pub fn note_field_shadowed_by_private_candidate(
312 &self,
313 err: &mut Diag<'_>,
314 hir_id: hir::HirId,
315 param_env: ty::ParamEnv<'tcx>,
316 ) {
317 let Some(typeck_results) = &self.typeck_results else {
318 return;
319 };
320 let Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
321 return;
322 };
323 let hir::ExprKind::Field(base_expr, field_ident) = expr.kind else {
324 return;
325 };
326
327 let Some(base_ty) = typeck_results.expr_ty_opt(base_expr) else {
328 return;
329 };
330 let base_ty = self.deeply_resolve_ignoring_regions(base_ty);
331 if base_ty.references_error() {
332 return;
333 }
334
335 let mut private_candidate: Option<(Ty<'tcx>, Ty<'tcx>, Span)> = None;
336
337 for (deref_base_ty, _) in (self.autoderef_steps)(base_ty) {
338 let ty::Adt(base_def, args) = deref_base_ty.kind() else {
339 continue;
340 };
341
342 if base_def.is_enum() {
343 continue;
344 }
345
346 let (adjusted_ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
347 field_ident,
348 base_def.did(),
349 self.tcx.parent_module_from_def_id(typeck_results.hir_owner.def_id),
350 );
351
352 let Some((_, field_def)) =
353 base_def.non_enum_variant().fields.iter_enumerated().find(|(_, field)| {
354 field.ident(self.tcx).normalize_to_macros_2_0() == adjusted_ident
355 })
356 else {
357 continue;
358 };
359 let field_span = self
360 .tcx
361 .def_ident_span(field_def.did)
362 .unwrap_or_else(|| self.tcx.def_span(field_def.did));
363
364 if field_def.vis.is_accessible_from(def_scope, self.tcx) {
365 let accessible_field_ty = field_def.ty(self.tcx, *args).skip_norm_wip();
366 if let Some((private_base_ty, private_field_ty, private_field_span)) =
367 private_candidate
368 && !self.can_eq(param_env, private_field_ty, accessible_field_ty)
369 {
370 let private_struct_span = match private_base_ty.kind() {
371 ty::Adt(private_base_def, _) => self
372 .tcx
373 .def_ident_span(private_base_def.did())
374 .unwrap_or_else(|| self.tcx.def_span(private_base_def.did())),
375 _ => DUMMY_SP,
376 };
377 let accessible_struct_span = self
378 .tcx
379 .def_ident_span(base_def.did())
380 .unwrap_or_else(|| self.tcx.def_span(base_def.did()));
381 let deref_impl_span = (typeck_results
382 .expr_adjustments(base_expr)
383 .iter()
384 .filter(|adj| {
385 #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
Adjust::Deref(DerefAdjustKind::Overloaded(_)) => true,
_ => false,
}matches!(adj.kind, Adjust::Deref(DerefAdjustKind::Overloaded(_)))
386 })
387 .count()
388 == 1)
389 .then(|| {
390 self.probe(|_| {
391 let deref_trait_did =
392 self.tcx.require_lang_item(LangItem::Deref, DUMMY_SP);
393 let trait_ref =
394 ty::TraitRef::new(self.tcx, deref_trait_did, [private_base_ty]);
395 let obligation: Obligation<'tcx, ty::Predicate<'tcx>> =
396 Obligation::new(
397 self.tcx,
398 ObligationCause::dummy(),
399 param_env,
400 trait_ref,
401 );
402 let Ok(Some(ImplSource::UserDefined(impl_data))) =
403 SelectionContext::new(self)
404 .select(&obligation.with(self.tcx, trait_ref))
405 else {
406 return None;
407 };
408 Some(self.tcx.def_span(impl_data.impl_def_id))
409 })
410 })
411 .flatten();
412
413 let mut note_spans: MultiSpan = private_struct_span.into();
414 if private_struct_span != DUMMY_SP {
415 note_spans.push_span_label(private_struct_span, "in this struct");
416 }
417 if private_field_span != DUMMY_SP {
418 note_spans.push_span_label(
419 private_field_span,
420 "if this field wasn't private, it would be accessible",
421 );
422 }
423 if accessible_struct_span != DUMMY_SP {
424 note_spans.push_span_label(
425 accessible_struct_span,
426 "this struct is accessible through auto-deref",
427 );
428 }
429 if field_span != DUMMY_SP {
430 note_spans
431 .push_span_label(field_span, "this is the field that was accessed");
432 }
433 if let Some(deref_impl_span) = deref_impl_span
434 && deref_impl_span != DUMMY_SP
435 {
436 note_spans.push_span_label(
437 deref_impl_span,
438 "the field was accessed through this `Deref`",
439 );
440 }
441
442 err.span_note(
443 note_spans,
444 ::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!(
445 "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"
446 ),
447 );
448 }
449
450 return;
453 }
454
455 private_candidate.get_or_insert((
456 deref_base_ty,
457 field_def.ty(self.tcx, *args).skip_norm_wip(),
458 field_span,
459 ));
460 }
461 }
462
463 pub fn suggest_restricting_param_bound(
464 &self,
465 err: &mut Diag<'_>,
466 trait_pred: ty::PolyTraitClause<'tcx>,
467 associated_ty: Option<(&'static str, Ty<'tcx>)>,
468 mut body_def_id: LocalDefId,
469 ) {
470 if trait_pred.skip_binder().polarity != ty::ClausePolarity::Positive {
471 return;
472 }
473
474 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
475
476 let self_ty = trait_pred.skip_binder().self_ty();
477 let (param_ty, projection) = match *self_ty.kind() {
478 ty::Param(_) => (true, None),
479 ty::Alias(_, alias) => {
480 if let Some(projection) = alias.try_to_projection() {
481 (false, Some(projection))
482 } else {
483 (false, None)
484 }
485 }
486 _ => (false, None),
487 };
488
489 let mut finder = ParamFinder { .. };
490 finder.visit_binder(&trait_pred);
491
492 loop {
495 let node = self.tcx.hir_node_by_def_id(body_def_id);
496 match node {
497 hir::Node::Item(hir::Item {
498 kind: hir::ItemKind::Trait { ident, generics, bounds, .. },
499 ..
500 }) if self_ty == self.tcx.types.self_param => {
501 if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
502 suggest_restriction(
504 self.tcx,
505 body_def_id,
506 generics,
507 "`Self`",
508 err,
509 None,
510 projection,
511 trait_pred,
512 Some((&ident, bounds)),
513 );
514 return;
515 }
516
517 hir::Node::TraitItem(hir::TraitItem {
518 generics,
519 kind: hir::TraitItemKind::Fn(..),
520 ..
521 }) if self_ty == self.tcx.types.self_param => {
522 if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
523 suggest_restriction(
525 self.tcx,
526 body_def_id,
527 generics,
528 "`Self`",
529 err,
530 None,
531 projection,
532 trait_pred,
533 None,
534 );
535 return;
536 }
537
538 hir::Node::TraitItem(hir::TraitItem {
539 generics,
540 kind: hir::TraitItemKind::Fn(fn_sig, ..),
541 ..
542 })
543 | hir::Node::ImplItem(hir::ImplItem {
544 generics,
545 kind: hir::ImplItemKind::Fn(fn_sig, ..),
546 ..
547 })
548 | hir::Node::Item(hir::Item {
549 kind: hir::ItemKind::Fn { sig: fn_sig, generics, .. },
550 ..
551 }) if projection.is_some() => {
552 suggest_restriction(
554 self.tcx,
555 body_def_id,
556 generics,
557 "the associated type",
558 err,
559 Some(fn_sig),
560 projection,
561 trait_pred,
562 None,
563 );
564 return;
565 }
566 hir::Node::Item(hir::Item {
567 kind:
568 hir::ItemKind::Trait { generics, .. }
569 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
570 ..
571 }) if projection.is_some() => {
572 suggest_restriction(
574 self.tcx,
575 body_def_id,
576 generics,
577 "the associated type",
578 err,
579 None,
580 projection,
581 trait_pred,
582 None,
583 );
584 return;
585 }
586
587 hir::Node::Item(hir::Item {
588 kind:
589 hir::ItemKind::Struct(_, generics, _)
590 | hir::ItemKind::Enum(_, generics, _)
591 | hir::ItemKind::Union(_, generics, _)
592 | hir::ItemKind::Trait { generics, .. }
593 | hir::ItemKind::Impl(hir::Impl { generics, .. })
594 | hir::ItemKind::Fn { generics, .. }
595 | hir::ItemKind::TyAlias(_, generics, _)
596 | hir::ItemKind::Const(_, generics, _, _)
597 | hir::ItemKind::TraitAlias(_, _, generics, _),
598 ..
599 })
600 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
601 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
602 if param_ty =>
603 {
604 if !trait_pred.skip_binder().trait_ref.args.as_slice()[1..]
613 .iter()
614 .all(|g| g.is_suggestable(self.tcx, false))
615 {
616 return;
617 }
618 let param_name = self_ty.to_string();
620 let mut constraint = {
let _guard = NoTrimmedGuard::new();
trait_pred.print_modifiers_and_trait_path().to_string()
}with_no_trimmed_paths!(
621 trait_pred.print_modifiers_and_trait_path().to_string()
622 );
623
624 if let Some((name, term)) = associated_ty {
625 if let Some(stripped) = constraint.strip_suffix('>') {
628 constraint = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, {1} = {2}>", stripped, name,
term))
})format!("{stripped}, {name} = {term}>");
629 } else {
630 constraint.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} = {1}>", name, term))
})format!("<{name} = {term}>"));
631 }
632 }
633
634 if suggest_constraining_type_param(
635 self.tcx,
636 generics,
637 err,
638 ¶m_name,
639 &constraint,
640 Some(trait_pred.def_id()),
641 None,
642 ) {
643 return;
644 }
645 }
646
647 hir::Node::TraitItem(hir::TraitItem {
648 generics,
649 kind: hir::TraitItemKind::Fn(..),
650 ..
651 })
652 | hir::Node::ImplItem(hir::ImplItem {
653 generics,
654 impl_kind: hir::ImplItemImplKind::Inherent { .. },
655 kind: hir::ImplItemKind::Fn(..),
656 ..
657 }) if finder.can_suggest_bound(generics) => {
658 suggest_arbitrary_trait_bound(
660 self.tcx,
661 generics,
662 err,
663 trait_pred,
664 associated_ty,
665 );
666 }
667 hir::Node::Item(hir::Item {
668 kind:
669 hir::ItemKind::Struct(_, generics, _)
670 | hir::ItemKind::Enum(_, generics, _)
671 | hir::ItemKind::Union(_, generics, _)
672 | hir::ItemKind::Trait { generics, .. }
673 | hir::ItemKind::Impl(hir::Impl { generics, .. })
674 | hir::ItemKind::Fn { generics, .. }
675 | hir::ItemKind::TyAlias(_, generics, _)
676 | hir::ItemKind::Const(_, generics, _, _)
677 | hir::ItemKind::TraitAlias(_, _, generics, _),
678 ..
679 }) if finder.can_suggest_bound(generics) => {
680 if suggest_arbitrary_trait_bound(
682 self.tcx,
683 generics,
684 err,
685 trait_pred,
686 associated_ty,
687 ) {
688 return;
689 }
690 }
691 hir::Node::Crate(..) => return,
692
693 _ => {}
694 }
695 body_def_id = self.tcx.local_parent(body_def_id);
696 }
697 }
698
699 pub(super) fn suggest_dereferences(
702 &self,
703 obligation: &PredicateObligation<'tcx>,
704 err: &mut Diag<'_>,
705 trait_pred: ty::PolyTraitClause<'tcx>,
706 ) -> bool {
707 let mut code = obligation.cause.code();
708 if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
709 && let Some(typeck_results) = &self.typeck_results
710 && let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
711 && let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
712 {
713 let mut real_trait_pred = trait_pred;
717 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
718 code = parent_code;
719 if let Some(parent_trait_pred) = parent_trait_pred {
720 real_trait_pred = parent_trait_pred;
721 }
722 }
723
724 let real_ty = self.tcx.instantiate_bound_regions_with_erased(real_trait_pred.self_ty());
727 if !self.can_eq(obligation.param_env, real_ty, arg_ty) {
728 return false;
729 }
730
731 let (is_under_ref, base_ty, span) = match expr.kind {
738 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, subexpr)
739 if let &ty::Ref(region, base_ty, hir::Mutability::Not) = real_ty.kind() =>
740 {
741 (Some(region), base_ty, subexpr.span)
742 }
743 hir::ExprKind::AddrOf(..) => return false,
745 _ => (None, real_ty, obligation.cause.span),
746 };
747
748 let autoderef = (self.autoderef_steps)(base_ty);
749 let mut is_boxed = base_ty.is_box();
750 if let Some(steps) = autoderef.into_iter().position(|(mut ty, obligations)| {
751 let can_deref = is_under_ref.is_some()
754 || self.type_is_copy_modulo_regions(obligation.param_env, ty)
755 || ty.is_numeric() || is_boxed && self.type_is_sized_modulo_regions(obligation.param_env, ty);
757 is_boxed &= ty.is_box();
758
759 if let Some(region) = is_under_ref {
761 ty = Ty::new_ref(self.tcx, region, ty, hir::Mutability::Not);
762 }
763
764 let real_trait_pred_and_ty =
766 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
767 let obligation = self.mk_trait_obligation_with_new_self_ty(
768 obligation.param_env,
769 real_trait_pred_and_ty,
770 );
771
772 can_deref
773 && obligations
774 .iter()
775 .chain([&obligation])
776 .all(|obligation| self.predicate_may_hold(obligation))
777 }) && steps > 0
778 {
779 if span.in_external_macro(self.tcx.sess.source_map()) {
780 return false;
781 }
782
783 if is_under_ref.is_some()
786 && steps == 1
787 && #[allow(non_exhaustive_omitted_patterns)] match base_ty.kind() {
ty::Ref(_, _, hir::Mutability::Not) => true,
_ => false,
}matches!(base_ty.kind(), ty::Ref(_, _, hir::Mutability::Not))
788 && !expr.span.from_expansion()
789 && self.suggest_remove_reference(obligation, err, real_trait_pred)
790 {
791 return true;
792 }
793 let derefs = "*".repeat(steps);
794 let msg = "consider dereferencing here";
795
796 let call_node = self.tcx.hir_node(*call_hir_id);
797 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!(
798 call_node,
799 Node::Expr(hir::Expr {
800 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
801 ..
802 })
803 if receiver_expr.hir_id == *arg_hir_id
804 );
805 if is_receiver {
806 err.multipart_suggestion(
807 msg,
808 ::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![
809 (span.shrink_to_lo(), format!("({derefs}")),
810 (span.shrink_to_hi(), ")".to_string()),
811 ],
812 Applicability::MachineApplicable,
813 )
814 } else {
815 err.span_suggestion_verbose(
816 span.shrink_to_lo(),
817 msg,
818 derefs,
819 Applicability::MachineApplicable,
820 )
821 };
822 return true;
823 }
824 } else if let (
825 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. },
826 predicate,
827 ) = code.peel_derives_with_predicate()
828 && let Some(typeck_results) = &self.typeck_results
829 && let hir::Node::Expr(lhs) = self.tcx.hir_node(*lhs_hir_id)
830 && let hir::Node::Expr(rhs) = self.tcx.hir_node(*rhs_hir_id)
831 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs)
832 && let trait_pred = predicate.unwrap_or(trait_pred)
833 && lang_items::BINARY_OPERATORS
835 .iter()
836 .filter_map(|&op| self.tcx.lang_items().get(op))
837 .any(|op| {
838 op == trait_pred.skip_binder().trait_ref.def_id
839 })
840 {
841 let trait_pred = predicate.unwrap_or(trait_pred);
843 let lhs_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
844 let lhs_autoderef = (self.autoderef_steps)(lhs_ty);
845 let rhs_autoderef = (self.autoderef_steps)(rhs_ty);
846 let first_lhs = lhs_autoderef.first().unwrap().clone();
847 let first_rhs = rhs_autoderef.first().unwrap().clone();
848 let mut autoderefs = lhs_autoderef
849 .into_iter()
850 .enumerate()
851 .rev()
852 .zip_longest(rhs_autoderef.into_iter().enumerate().rev())
853 .map(|t| match t {
854 EitherOrBoth::Both(a, b) => (a, b),
855 EitherOrBoth::Left(a) => (a, (0, first_rhs.clone())),
856 EitherOrBoth::Right(b) => ((0, first_lhs.clone()), b),
857 })
858 .rev();
859 if let Some((lsteps, rsteps)) =
860 autoderefs.find_map(|((lsteps, (l_ty, _)), (rsteps, (r_ty, _)))| {
861 let trait_pred_and_ty = trait_pred.map_bound(|inner| {
865 (
866 ty::TraitClause {
867 trait_ref: ty::TraitRef::new_from_args(
868 self.tcx,
869 inner.trait_ref.def_id,
870 self.tcx.mk_args(
871 &[
872 &[l_ty.into(), r_ty.into()],
873 &inner.trait_ref.args.as_slice()[2..],
874 ]
875 .concat(),
876 ),
877 ),
878 ..inner
879 },
880 l_ty,
881 )
882 });
883 let obligation = self.mk_trait_obligation_with_new_self_ty(
884 obligation.param_env,
885 trait_pred_and_ty,
886 );
887 self.predicate_may_hold(&obligation).then_some(match (lsteps, rsteps) {
888 (_, 0) => (Some(lsteps), None),
889 (0, _) => (None, Some(rsteps)),
890 _ => (Some(lsteps), Some(rsteps)),
891 })
892 })
893 {
894 let make_sugg = |mut expr: &Expr<'_>, mut steps| {
895 if expr.span.in_external_macro(self.tcx.sess.source_map()) {
896 return None;
897 }
898 let mut prefix_span = expr.span.shrink_to_lo();
899 let mut msg = "consider dereferencing here";
900 if let hir::ExprKind::AddrOf(_, _, inner) = expr.kind {
901 msg = "consider removing the borrow and dereferencing instead";
902 if let hir::ExprKind::AddrOf(..) = inner.kind {
903 msg = "consider removing the borrows and dereferencing instead";
904 }
905 }
906 while let hir::ExprKind::AddrOf(_, _, inner) = expr.kind
907 && steps > 0
908 {
909 prefix_span = prefix_span.with_hi(inner.span.lo());
910 expr = inner;
911 steps -= 1;
912 }
913 if steps == 0 {
915 return Some((
916 msg.trim_end_matches(" and dereferencing instead"),
917 ::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())],
918 ));
919 }
920 let derefs = "*".repeat(steps);
921 let needs_parens = steps > 0 && expr_needs_parens(expr);
922 let mut suggestion = if needs_parens {
923 ::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![
924 (
925 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
926 format!("{derefs}("),
927 ),
928 (expr.span.shrink_to_hi(), ")".to_string()),
929 ]
930 } else {
931 ::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![(
932 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
933 format!("{derefs}"),
934 )]
935 };
936 if !prefix_span.is_empty() {
938 suggestion.push((prefix_span, String::new()));
939 }
940 Some((msg, suggestion))
941 };
942
943 if let Some(lsteps) = lsteps
944 && let Some(rsteps) = rsteps
945 && lsteps > 0
946 && rsteps > 0
947 {
948 let Some((_, mut suggestion)) = make_sugg(lhs, lsteps) else {
949 return false;
950 };
951 let Some((_, mut rhs_suggestion)) = make_sugg(rhs, rsteps) else {
952 return false;
953 };
954 suggestion.append(&mut rhs_suggestion);
955 err.multipart_suggestion(
956 "consider dereferencing both sides of the expression",
957 suggestion,
958 Applicability::MachineApplicable,
959 );
960 return true;
961 } else if let Some(lsteps) = lsteps
962 && lsteps > 0
963 {
964 let Some((msg, suggestion)) = make_sugg(lhs, lsteps) else {
965 return false;
966 };
967 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
968 return true;
969 } else if let Some(rsteps) = rsteps
970 && rsteps > 0
971 {
972 let Some((msg, suggestion)) = make_sugg(rhs, rsteps) else {
973 return false;
974 };
975 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
976 return true;
977 }
978 }
979 }
980 false
981 }
982
983 fn get_closure_name(
987 &self,
988 def_id: DefId,
989 err: &mut Diag<'_>,
990 msg: Cow<'static, str>,
991 ) -> Option<Symbol> {
992 let get_name = |err: &mut Diag<'_>, kind: &hir::PatKind<'_>| -> Option<Symbol> {
993 match &kind {
996 hir::PatKind::Binding(hir::BindingMode::NONE, _, ident, None) => Some(ident.name),
997 _ => {
998 err.note(msg);
999 None
1000 }
1001 }
1002 };
1003
1004 let hir_id = self.tcx.local_def_id_to_hir_id(def_id.as_local()?);
1005 match self.tcx.parent_hir_node(hir_id) {
1006 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(local), .. }) => {
1007 get_name(err, &local.pat.kind)
1008 }
1009 hir::Node::LetStmt(local) => get_name(err, &local.pat.kind),
1012 _ => None,
1013 }
1014 }
1015
1016 pub(super) fn suggest_fn_call(
1020 &self,
1021 obligation: &PredicateObligation<'tcx>,
1022 err: &mut Diag<'_>,
1023 trait_pred: ty::PolyTraitClause<'tcx>,
1024 ) -> bool {
1025 if self.typeck_results.is_none() {
1028 return false;
1029 }
1030
1031 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
1032 obligation.predicate.kind().skip_binder()
1033 && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1034 {
1035 return false;
1037 }
1038
1039 let self_ty = self.instantiate_binder_with_fresh_vars(
1040 DUMMY_SP,
1041 BoundRegionConversionTime::FnCall,
1042 trait_pred.self_ty(),
1043 );
1044
1045 let Some((def_id_or_name, output, inputs)) =
1046 self.extract_callable_info(obligation.cause.body_def_id, obligation.param_env, self_ty)
1047 else {
1048 return false;
1049 };
1050
1051 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
1053
1054 let new_obligation =
1055 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1056 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
1057 return false;
1058 }
1059
1060 if let ty::CoroutineClosure(def_id, args) = *self_ty.kind()
1064 && let sig = args.as_coroutine_closure().coroutine_closure_sig().skip_binder()
1065 && let ty::Tuple(inputs) = *sig.tupled_inputs_ty.kind()
1066 && inputs.is_empty()
1067 && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Future)
1068 && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1069 && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) =
1070 self.tcx.hir_node(*arg_hir_id)
1071 && let Some(hir::Node::Expr(hir::Expr {
1072 kind: hir::ExprKind::Closure(closure), ..
1073 })) = self.tcx.hir_get_if_local(def_id)
1074 && let hir::ClosureKind::CoroutineClosure(CoroutineDesugaring::Async) = closure.kind
1075 && let Some(arg_span) = closure.fn_arg_span
1076 && obligation.cause.span.contains(arg_span)
1077 {
1078 let mut body = self.tcx.hir_body(closure.body).value;
1079 let peeled = body.peel_blocks().peel_drop_temps();
1080 if let hir::ExprKind::Closure(inner) = peeled.kind {
1081 body = self.tcx.hir_body(inner.body).value;
1082 }
1083 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(..)) {
1084 return false;
1085 }
1086
1087 let sm = self.tcx.sess.source_map();
1088 let removal_span = if let Ok(snippet) =
1089 sm.span_to_snippet(arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1)))
1090 && snippet.ends_with(' ')
1091 {
1092 arg_span.with_hi(arg_span.hi() + rustc_span::BytePos(1))
1094 } else {
1095 arg_span
1096 };
1097 err.span_suggestion_verbose(
1098 removal_span,
1099 "use `async {}` instead of `async || {}` to introduce an async block",
1100 "",
1101 Applicability::MachineApplicable,
1102 );
1103 return true;
1104 }
1105
1106 let msg = match def_id_or_name {
1108 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
1109 DefKind::Ctor(CtorOf::Struct, _) => {
1110 Cow::from("use parentheses to construct this tuple struct")
1111 }
1112 DefKind::Ctor(CtorOf::Variant, _) => {
1113 Cow::from("use parentheses to construct this tuple variant")
1114 }
1115 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!(
1116 "use parentheses to call this {}",
1117 self.tcx.def_kind_descr(kind, def_id)
1118 )),
1119 },
1120 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}")),
1121 };
1122
1123 let args = inputs
1124 .into_iter()
1125 .map(|ty| {
1126 if ty.is_suggestable(self.tcx, false) {
1127 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", ty))
})format!("/* {ty} */")
1128 } else {
1129 "/* value */".to_string()
1130 }
1131 })
1132 .collect::<Vec<_>>()
1133 .join(", ");
1134
1135 let callee_hir_id = match obligation.cause.code() {
1136 ObligationCauseCode::FunctionArg { arg_hir_id, .. }
1137 if obligation.cause.span.can_be_used_for_suggestions() =>
1138 {
1139 Some(*arg_hir_id)
1140 }
1141 code => match code.peel_derives() {
1145 ObligationCauseCode::ForLoopIterator(iter_hir_id)
1146 if self.tcx.hir_span(*iter_hir_id).can_be_used_for_suggestions() =>
1147 {
1148 Some(*iter_hir_id)
1149 }
1150 _ => None,
1151 },
1152 };
1153
1154 if let Some(callee_hir_id) = callee_hir_id {
1155 let span = obligation.cause.span;
1156
1157 let arg_expr = match self.tcx.hir_node(callee_hir_id) {
1158 hir::Node::Expr(expr) => Some(expr),
1159 _ => None,
1160 };
1161
1162 let is_closure_expr =
1163 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(..)));
1164
1165 if args.is_empty()
1168 && let Some(expr) = arg_expr
1169 && let hir::ExprKind::Closure(closure) = expr.kind
1170 {
1171 let mut body = self.tcx.hir_body(closure.body).value;
1172
1173 if let hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) =
1175 closure.kind
1176 {
1177 let peeled = body.peel_blocks().peel_drop_temps();
1178 if let hir::ExprKind::Closure(inner) = peeled.kind {
1179 body = self.tcx.hir_body(inner.body).value;
1180 }
1181 }
1182
1183 let peeled_body = body.peel_blocks().peel_drop_temps();
1184 if let hir::ExprKind::Call(callee, call_args) = peeled_body.kind
1185 && call_args.is_empty()
1186 && let hir::ExprKind::Block(..) = callee.peel_blocks().peel_drop_temps().kind
1187 {
1188 return false;
1189 }
1190 }
1191
1192 if is_closure_expr {
1193 err.multipart_suggestions(
1194 msg,
1195 ::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![
1196 (span.shrink_to_lo(), "(".to_string()),
1197 (span.shrink_to_hi(), format!(")({args})")),
1198 ]],
1199 Applicability::HasPlaceholders,
1200 );
1201 } else {
1202 err.span_suggestion_verbose(
1203 span.shrink_to_hi(),
1204 msg,
1205 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", args))
})format!("({args})"),
1206 Applicability::HasPlaceholders,
1207 );
1208 }
1209 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
1210 let name = match self.tcx.hir_get_if_local(def_id) {
1211 Some(hir::Node::Expr(hir::Expr {
1212 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
1213 ..
1214 })) => {
1215 err.span_label(*fn_decl_span, "consider calling this closure");
1216 let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
1217 return false;
1218 };
1219 name.to_string()
1220 }
1221 Some(hir::Node::Item(hir::Item {
1222 kind: hir::ItemKind::Fn { ident, .. }, ..
1223 })) => {
1224 err.span_label(ident.span, "consider calling this function");
1225 ident.to_string()
1226 }
1227 Some(hir::Node::Ctor(..)) => {
1228 let name = self.tcx.def_path_str(def_id);
1229 err.span_label(
1230 self.tcx.def_span(def_id),
1231 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling the constructor for `{0}`",
name))
})format!("consider calling the constructor for `{name}`"),
1232 );
1233 name
1234 }
1235 _ => return false,
1236 };
1237 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}({2})`", msg, name, args))
})format!("{msg}: `{name}({args})`"));
1238 }
1239 true
1240 }
1241
1242 pub(super) fn suggest_cast_to_fn_pointer(
1243 &self,
1244 obligation: &PredicateObligation<'tcx>,
1245 err: &mut Diag<'_>,
1246 leaf_trait_predicate: ty::PolyTraitClause<'tcx>,
1247 main_trait_predicate: ty::PolyTraitClause<'tcx>,
1248 span: Span,
1249 ) -> bool {
1250 let &[candidate] = &self.find_similar_impl_candidates(
1251 leaf_trait_predicate.def_id(),
1252 leaf_trait_predicate.self_ty().skip_binder(),
1253 )[..] else {
1254 return false;
1255 };
1256 let candidate = candidate.trait_ref;
1257
1258 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!(
1259 (candidate.self_ty().kind(), main_trait_predicate.self_ty().skip_binder().kind(),),
1260 (ty::FnPtr(..), ty::FnDef(..))
1261 ) {
1262 return false;
1263 }
1264
1265 let parenthesized_cast = |span: Span| {
1266 ::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![
1267 (span.shrink_to_lo(), "(".to_string()),
1268 (span.shrink_to_hi(), format!(" as {})", candidate.self_ty())),
1269 ]
1270 };
1271 let suggestion = if self.tcx.sess.source_map().span_followed_by(span, ".").is_some() {
1273 parenthesized_cast(span)
1274 } else if let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) {
1275 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1276 expr_finder.visit_expr(body.value);
1277 if let Some(expr) = expr_finder.result
1278 && let hir::ExprKind::AddrOf(_, _, expr) = expr.kind
1279 {
1280 parenthesized_cast(expr.span)
1281 } else {
1282 ::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()))]
1283 }
1284 } else {
1285 ::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()))]
1286 };
1287
1288 let trait_ = self.tcx.short_string(candidate.print_trait_sugared(), err.long_ty_path());
1289 let self_ty = self.tcx.short_string(candidate.self_ty(), err.long_ty_path());
1290 err.multipart_suggestion(
1291 ::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!(
1292 "the trait `{trait_}` is implemented for fn pointer \
1293 `{self_ty}`, try casting using `as`",
1294 ),
1295 suggestion,
1296 Applicability::MaybeIncorrect,
1297 );
1298 true
1299 }
1300
1301 pub(super) fn check_for_binding_assigned_block_without_tail_expression(
1302 &self,
1303 obligation: &PredicateObligation<'tcx>,
1304 err: &mut Diag<'_>,
1305 trait_pred: ty::PolyTraitClause<'tcx>,
1306 ) {
1307 let mut span = obligation.cause.span;
1308 while span.from_expansion() {
1309 span.remove_mark();
1311 }
1312 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1313 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
1314 return;
1315 };
1316 expr_finder.visit_expr(body.value);
1317 let Some(expr) = expr_finder.result else {
1318 return;
1319 };
1320 let Some(typeck) = &self.typeck_results else {
1321 return;
1322 };
1323 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
1324 return;
1325 };
1326 if !ty.is_unit() {
1327 return;
1328 };
1329 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
1330 return;
1331 };
1332 let Res::Local(hir_id) = path.res else {
1333 return;
1334 };
1335 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
1336 return;
1337 };
1338 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
1339 self.tcx.parent_hir_node(pat.hir_id)
1340 else {
1341 return;
1342 };
1343 let hir::ExprKind::Block(block, None) = init.kind else {
1344 return;
1345 };
1346 if block.expr.is_some() {
1347 return;
1348 }
1349 let [.., stmt] = block.stmts else {
1350 err.span_label(block.span, "this empty block is missing a tail expression");
1351 return;
1352 };
1353 if stmt.span.from_expansion() {
1356 return;
1357 }
1358 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
1359 return;
1360 };
1361 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1362 err.span_label(block.span, "this block is missing a tail expression");
1363 return;
1364 };
1365 let ty =
1366 self.resolve_numeric_literals_with_default(self.deeply_resolve_ignoring_regions(ty));
1367 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1368
1369 let new_obligation =
1370 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1371 if !#[allow(non_exhaustive_omitted_patterns)] match tail_expr.kind {
hir::ExprKind::Err(_) => true,
_ => false,
}matches!(tail_expr.kind, hir::ExprKind::Err(_))
1372 && self.predicate_must_hold_modulo_regions(&new_obligation)
1373 {
1374 err.span_suggestion_short(
1375 stmt.span.with_lo(tail_expr.span.hi()),
1376 "remove this semicolon",
1377 "",
1378 Applicability::MachineApplicable,
1379 );
1380 } else {
1381 err.span_label(block.span, "this block is missing a tail expression");
1382 }
1383 }
1384
1385 pub(super) fn suggest_add_clone_to_arg(
1386 &self,
1387 obligation: &PredicateObligation<'tcx>,
1388 err: &mut Diag<'_>,
1389 trait_pred: ty::PolyTraitClause<'tcx>,
1390 ) -> bool {
1391 let self_ty = self.deeply_resolve_ignoring_regions(trait_pred.self_ty());
1392 self.enter_forall(self_ty, |ty: Ty<'_>| {
1393 let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_def_id) else {
1394 return false;
1395 };
1396 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
1397 let ty::Param(param) = inner_ty.kind() else { return false };
1398 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1399 else {
1400 return false;
1401 };
1402
1403 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, obligation.cause.span);
1404 let has_clone = |ty| {
1405 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
1406 .must_apply_modulo_regions()
1407 };
1408
1409 let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
1410 Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
1412 Node::Expr(Expr {
1415 kind:
1416 hir::ExprKind::MethodCall(
1417 hir::PathSegment { ident, .. },
1418 _receiver,
1419 [],
1420 call_span,
1421 ),
1422 hir_id,
1423 ..
1424 }) if ident.name == sym::clone
1425 && !call_span.from_expansion()
1426 && !has_clone(*inner_ty) =>
1427 {
1428 let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
1430 let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
1431 else {
1432 return false;
1433 };
1434 if self.tcx.trait_of_assoc(did) != Some(clone_trait) {
1435 return false;
1436 }
1437 Some(ident.span)
1438 }
1439 _ => return false,
1440 };
1441
1442 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1443 obligation.param_env,
1444 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1445 );
1446
1447 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1448 if !has_clone(param.to_ty(self.tcx)) {
1449 suggest_constraining_type_param(
1450 self.tcx,
1451 generics,
1452 err,
1453 param.name.as_str(),
1454 "Clone",
1455 Some(clone_trait),
1456 None,
1457 );
1458 }
1459 if let Some(existing_clone_call) = existing_clone_call {
1460 err.span_note(
1461 existing_clone_call,
1462 ::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!(
1463 "this `clone()` copies the reference, \
1464 which does not do anything, \
1465 because `{inner_ty}` does not implement `Clone`"
1466 ),
1467 );
1468 } else {
1469 err.span_suggestion_verbose(
1470 obligation.cause.span.shrink_to_hi(),
1471 "consider using clone here",
1472 ".clone()".to_string(),
1473 Applicability::MaybeIncorrect,
1474 );
1475 }
1476 return true;
1477 }
1478 false
1479 })
1480 }
1481
1482 pub fn extract_callable_info(
1486 &self,
1487 body_def_id: LocalDefId,
1488 param_env: ty::ParamEnv<'tcx>,
1489 found: Ty<'tcx>,
1490 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1491 let Some((def_id_or_name, output, inputs)) =
1493 (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1494 ty::FnPtr(sig_tys, _) => Some((
1495 DefIdOrName::Name("function pointer"),
1496 sig_tys.output(),
1497 sig_tys.inputs(),
1498 )),
1499 ty::FnDef(def_id, _) => {
1500 let fn_sig = found.fn_sig(self.tcx);
1501 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1502 }
1503 ty::Closure(def_id, args) => {
1504 let fn_sig = args.as_closure().sig();
1505 Some((
1506 DefIdOrName::DefId(def_id),
1507 fn_sig.output(),
1508 fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1509 ))
1510 }
1511 ty::CoroutineClosure(def_id, args) => {
1512 let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1513 Some((
1514 DefIdOrName::DefId(def_id),
1515 sig_parts.map_bound(|sig| {
1516 sig.to_coroutine(
1517 self.tcx,
1518 args.as_coroutine_closure().parent_args(),
1519 self.next_ty_var(DUMMY_SP),
1522 self.tcx.coroutine_for_closure(def_id),
1523 self.next_ty_var(DUMMY_SP),
1524 )
1525 }),
1526 sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1527 ))
1528 }
1529 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
1530 self.tcx
1531 .item_self_bounds(def_id)
1532 .instantiate(self.tcx, args)
1533 .skip_norm_wip()
1534 .iter()
1535 .find_map(|pred| {
1536 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1537 && self
1538 .tcx
1539 .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1540 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1542 {
1543 Some((
1544 DefIdOrName::DefId(def_id),
1545 pred.kind().rebind(proj.term.expect_type()),
1546 pred.kind().rebind(args.as_slice()),
1547 ))
1548 } else {
1549 None
1550 }
1551 })
1552 }
1553 ty::Dynamic(data, _) => data.iter().find_map(|pred| {
1554 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1555 && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1556 && let ty::Tuple(args) = proj.args.type_at(0).kind()
1558 {
1559 Some((
1560 DefIdOrName::Name("trait object"),
1561 pred.rebind(proj.term.expect_type()),
1562 pred.rebind(args.as_slice()),
1563 ))
1564 } else {
1565 None
1566 }
1567 }),
1568 ty::Param(param) => {
1569 let generics = self.tcx.generics_of(body_def_id);
1570 let name = if generics.count() > param.index as usize
1571 && let def = generics.param_at(param.index as usize, self.tcx)
1572 && #[allow(non_exhaustive_omitted_patterns)] match def.kind {
ty::GenericParamDefKind::Type { .. } => true,
_ => false,
}matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1573 && def.name == param.name
1574 {
1575 DefIdOrName::DefId(def.def_id)
1576 } else {
1577 DefIdOrName::Name("type parameter")
1578 };
1579
1580 param_env.caller_bounds().non_trait_clauses().iter().find_map(|clause| {
1581 if let ty::ClauseKind::Projection(proj) = clause.kind().skip_binder()
1582 && self
1583 .tcx
1584 .is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
1585 && proj.projection_term.self_ty() == found
1586 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1588 {
1589 Some((
1590 name,
1591 clause.kind().rebind(proj.term.expect_type()),
1592 clause.kind().rebind(args.as_slice()),
1593 ))
1594 } else {
1595 None
1596 }
1597 })
1598 }
1599 _ => None,
1600 })
1601 else {
1602 return None;
1603 };
1604
1605 let output = self.instantiate_binder_with_fresh_vars(
1606 DUMMY_SP,
1607 BoundRegionConversionTime::FnCall,
1608 output,
1609 );
1610 let inputs = inputs
1611 .skip_binder()
1612 .iter()
1613 .map(|ty| {
1614 self.instantiate_binder_with_fresh_vars(
1615 DUMMY_SP,
1616 BoundRegionConversionTime::FnCall,
1617 inputs.rebind(*ty),
1618 )
1619 })
1620 .collect();
1621
1622 let InferOk { value: output, obligations: _ } =
1626 self.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(output));
1627
1628 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1629 }
1630
1631 pub(super) fn where_clause_expr_matches_failed_self_ty(
1632 &self,
1633 obligation: &PredicateObligation<'tcx>,
1634 old_self_ty: Ty<'tcx>,
1635 ) -> bool {
1636 let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code() else {
1637 return true;
1638 };
1639 let (Some(typeck_results), Some(body)) = (
1640 self.typeck_results.as_ref(),
1641 self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id),
1642 ) else {
1643 return true;
1644 };
1645
1646 let mut expr_finder = FindExprBySpan::new(obligation.cause.span, self.tcx);
1647 expr_finder.visit_expr(body.value);
1648 let Some(expr) = expr_finder.result else {
1649 return true;
1650 };
1651
1652 let inner_old_self_ty = match old_self_ty.kind() {
1653 ty::Ref(_, inner_ty, _) => Some(*inner_ty),
1654 _ => None,
1655 };
1656
1657 typeck_results.expr_ty_adjusted_opt(expr).is_some_and(|expr_ty| {
1658 self.can_eq(obligation.param_env, expr_ty, old_self_ty)
1659 || inner_old_self_ty
1660 .is_some_and(|inner_ty| self.can_eq(obligation.param_env, expr_ty, inner_ty))
1661 })
1662 }
1663
1664 pub(super) fn suggest_add_reference_to_arg(
1665 &self,
1666 obligation: &PredicateObligation<'tcx>,
1667 err: &mut Diag<'_>,
1668 poly_trait_pred: ty::PolyTraitClause<'tcx>,
1669 has_custom_message: bool,
1670 ) -> bool {
1671 let span = obligation.cause.span;
1672 let param_env = obligation.param_env;
1673
1674 let mk_result = |trait_pred_and_new_ty| {
1675 let obligation =
1676 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1677 self.predicate_must_hold_modulo_regions(&obligation)
1678 };
1679
1680 let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| {
1681 (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1682 });
1683 let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| {
1684 (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1685 });
1686
1687 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1688 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1689
1690 let mut point_at_relevant_args =
1691 |pred_ty: Ty<'tcx>, args_and_inputs: Vec<(hir::Expr<'_>, Ty<'tcx>)>| {
1692 let Some(typeck_results) = &self.typeck_results else { return false };
1693
1694 let erased_self_ty =
1695 self.tcx.instantiate_bound_regions_with_erased(poly_trait_pred.self_ty());
1696 let mut spans = ::alloc::vec::Vec::new()vec![];
1697 for (arg, input) in args_and_inputs {
1698 let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(&arg) else { continue };
1699 let pred_has_arg_type = self.infcx.can_eq(param_env, arg_ty, erased_self_ty);
1700 let arg_is_type_param = self.infcx.can_eq(param_env, pred_ty, input);
1701 if pred_has_arg_type && arg_is_type_param {
1702 err.span_label(
1703 arg.span,
1704 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` doesn\'t satisfy the trait bound",
arg_ty))
})format!("`{arg_ty}` doesn't satisfy the trait bound"),
1705 );
1706 spans.push(arg.span);
1707 }
1708 }
1709 let this = if spans.len() == 1 { "this" } else { "these" }pluralize!("this", spans.len());
1710 if !spans.is_empty() {
1711 if imm_ref_self_ty_satisfies_pred {
1712 err.multipart_suggestion(
1713 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider borrowing {0} argument",
this))
})format!("consider borrowing {this} argument"),
1714 spans.iter().map(|sp| (sp.shrink_to_lo(), "&".into())).collect(),
1715 Applicability::MaybeIncorrect,
1716 );
1717 }
1718 if mut_ref_self_ty_satisfies_pred {
1719 err.multipart_suggestion(
1720 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider mutably borrowing {0} argument",
this))
})format!("consider mutably borrowing {this} argument"),
1721 spans.iter().map(|sp| (sp.shrink_to_lo(), "&mut ".into())).collect(),
1722 Applicability::MaybeIncorrect,
1723 );
1724 }
1725 }
1726 !spans.is_empty()
1727 };
1728 let code = match obligation.cause.code() {
1729 ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1730 c @ ObligationCauseCode::WhereClauseInExpr(def_id, _, hir_id, idx)
1733 if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
1734 {
1735 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id) {
1737 if let hir::ExprKind::Call(base, _) = expr.kind
1740 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) =
1741 base.kind
1742 && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id)
1743 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind
1744 && ty.span == span
1745 {
1746 let sugg_msg = |pre: &str| {
1752 ::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!(
1753 "you likely meant to call the associated function `{FN}` for type \
1754 `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \
1755 type `{TY}`",
1756 FN = segment.ident,
1757 TY = poly_trait_pred.self_ty(),
1758 )
1759 };
1760 match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl)
1761 {
1762 (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => {
1763 err.multipart_suggestion(
1764 sugg_msg(mtbl.prefix_str()),
1765 ::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![
1766 (outer.span.shrink_to_lo(), "<".to_string()),
1767 (span.shrink_to_hi(), ">".to_string()),
1768 ],
1769 Applicability::MachineApplicable,
1770 );
1771 }
1772 (true, _, hir::Mutability::Mut) => {
1773 err.multipart_suggestion(
1775 sugg_msg("mut "),
1776 ::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![
1777 (outer.span.shrink_to_lo().until(span), "<&".to_string()),
1778 (span.shrink_to_hi(), ">".to_string()),
1779 ],
1780 Applicability::MachineApplicable,
1781 );
1782 }
1783 (_, true, hir::Mutability::Not) => {
1784 err.multipart_suggestion(
1785 sugg_msg(""),
1786 ::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![
1787 (
1788 outer.span.shrink_to_lo().until(span),
1789 "<&mut ".to_string(),
1790 ),
1791 (span.shrink_to_hi(), ">".to_string()),
1792 ],
1793 Applicability::MachineApplicable,
1794 );
1795 }
1796 _ => {}
1797 }
1798 return false;
1800 } else if let hir::ExprKind::Call(_, args) = expr.kind {
1801 if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(*def_id) {
DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => true,
_ => false,
}matches!(
1803 self.tcx.def_kind(*def_id),
1804 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
1805 ) && let Some(pred) = self
1806 .tcx
1807 .clauses_of(*def_id)
1808 .instantiate_identity(self.tcx)
1809 .clauses
1810 .into_iter()
1811 .nth(*idx)
1812 && let Some(pred) = pred.as_trait_clause()
1813 && !self.tcx.features().non_lifetime_binders()
1816 {
1817 let pred_ty = self.tcx.instantiate_bound_regions_with_erased(
1818 pred.self_ty().skip_norm_wip(),
1819 );
1820 let fn_sig = self.tcx.instantiate_bound_regions_with_erased(
1821 self.tcx.fn_sig(*def_id).instantiate_identity().skip_norm_wip(),
1822 );
1823 if point_at_relevant_args(
1824 pred_ty,
1825 args.into_iter()
1826 .zip(fn_sig.inputs())
1827 .map(|(e, t)| (*e, *t))
1828 .collect(),
1829 ) {
1830 return false;
1831 }
1832 }
1833 }
1834 }
1835 c
1836 }
1837 c @ ObligationCauseCode::WhereClauseInExpr(def_id, _, hir_id, idx)
1838 if let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1839 && let hir::ExprKind::MethodCall(_segment, rcvr, args, ..) = expr.kind
1840 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(*def_id) {
DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => true,
_ => false,
}matches!(
1842 self.tcx.def_kind(*def_id),
1843 DefKind::AssocFn | DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn)
1844 )
1845 && let Some(pred) = self
1846 .tcx
1847 .clauses_of(*def_id)
1848 .instantiate_identity(self.tcx)
1849 .clauses
1850 .into_iter()
1851 .nth(*idx)
1852 && let Some(pred) = pred.as_trait_clause()
1853 && !self.tcx.features().non_lifetime_binders() =>
1856 {
1857 let fn_sig = self.tcx.instantiate_bound_regions_with_erased(
1858 self.tcx.fn_sig(*def_id).instantiate_identity().skip_norm_wip(),
1859 );
1860 let pred_ty =
1862 self.tcx.instantiate_bound_regions_with_erased(pred.self_ty().skip_norm_wip());
1863 if point_at_relevant_args(
1864 pred_ty,
1865 [rcvr]
1866 .into_iter()
1867 .chain(args.into_iter())
1868 .zip(fn_sig.inputs())
1869 .map(|(e, t)| (*e, *t))
1870 .collect(),
1871 ) {
1872 return false;
1873 }
1874 c
1875 }
1876 c if #[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1877 span.ctxt().outer_expn_data().kind,
1878 ExpnKind::Desugaring(DesugaringKind::ForLoop)
1879 ) =>
1880 {
1881 c
1882 }
1883 _ => return false,
1884 };
1885
1886 let mut never_suggest_borrow: Vec<_> =
1890 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1891 .iter()
1892 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1893 .collect();
1894
1895 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1896 never_suggest_borrow.push(def_id);
1897 }
1898
1899 let mut try_borrowing = |old_pred: ty::PolyTraitClause<'tcx>,
1901 blacklist: &[DefId]|
1902 -> bool {
1903 if blacklist.contains(&old_pred.def_id()) {
1904 return false;
1905 }
1906 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1908 (
1909 trait_pred,
1910 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1911 )
1912 });
1913 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1914 (
1915 trait_pred,
1916 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1917 )
1918 });
1919
1920 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1921 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1922
1923 let (ref_inner_ty_satisfies_pred, ref_inner_ty_is_mut) =
1924 if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1925 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1926 {
1927 (
1928 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1929 mutability.is_mut(),
1930 )
1931 } else {
1932 (false, false)
1933 };
1934
1935 let is_immut = imm_ref_self_ty_satisfies_pred
1936 || (ref_inner_ty_satisfies_pred && !ref_inner_ty_is_mut);
1937 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_is_mut;
1938 if !is_immut && !is_mut {
1939 return false;
1940 }
1941 let Ok(_snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1942 return false;
1943 };
1944 if !#[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1952 span.ctxt().outer_expn_data().kind,
1953 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1954 ) {
1955 return false;
1956 }
1957 let mut label = || {
1964 let is_sized = match obligation.predicate.kind().skip_binder() {
1967 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
1968 self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1969 }
1970 _ => false,
1971 };
1972
1973 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!(
1974 "the trait bound `{}` is not satisfied",
1975 self.tcx.short_string(old_pred, err.long_ty_path()),
1976 );
1977 let self_ty_str = self.tcx.short_string(old_pred.self_ty(), err.long_ty_path());
1978 let trait_path = self
1979 .tcx
1980 .short_string(old_pred.print_modifiers_and_trait_path(), err.long_ty_path());
1981
1982 if has_custom_message {
1983 let msg = if is_sized {
1984 "the trait bound `Sized` is not satisfied".into()
1985 } else {
1986 msg
1987 };
1988 err.note(msg);
1989 } else {
1990 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)];
1991 }
1992 if is_sized {
1993 err.span_label(
1994 span,
1995 ::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}`"),
1996 );
1997 } else {
1998 err.span_label(
1999 span,
2000 ::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}`"),
2001 );
2002 }
2003 };
2004
2005 let mut sugg_prefixes = ::alloc::vec::Vec::new()vec![];
2006 if is_immut {
2007 sugg_prefixes.push("&");
2008 }
2009 if is_mut {
2010 sugg_prefixes.push("&mut ");
2011 }
2012 let sugg_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider{0} borrowing here",
if is_mut && !is_immut { " mutably" } else { "" }))
})format!(
2013 "consider{} borrowing here",
2014 if is_mut && !is_immut { " mutably" } else { "" },
2015 );
2016
2017 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
2021 return false;
2022 };
2023 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2024 expr_finder.visit_expr(body.value);
2025
2026 if let Some(ty) = expr_finder.ty_result {
2027 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(ty.hir_id)
2028 && let hir::ExprKind::Path(hir::QPath::TypeRelative(_, _)) = expr.kind
2029 && ty.span == span
2030 {
2031 label();
2034 err.multipart_suggestions(
2035 sugg_msg,
2036 sugg_prefixes.into_iter().map(|sugg_prefix| {
2037 ::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![
2038 (span.shrink_to_lo(), format!("<{sugg_prefix}")),
2039 (span.shrink_to_hi(), ">".to_string()),
2040 ]
2041 }),
2042 Applicability::MaybeIncorrect,
2043 );
2044 return true;
2045 }
2046 return false;
2047 }
2048 let Some(expr) = expr_finder.result else {
2049 return false;
2050 };
2051 if let hir::ExprKind::AddrOf(_, _, _) = expr.kind {
2052 return false;
2053 }
2054 let old_self_ty = old_pred.skip_binder().self_ty();
2055 if !old_self_ty.has_escaping_bound_vars()
2056 && !self.where_clause_expr_matches_failed_self_ty(
2057 obligation,
2058 self.tcx.instantiate_bound_regions_with_erased(old_pred.self_ty()),
2059 )
2060 {
2061 return false;
2062 }
2063 let needs_parens_post = expr_needs_parens(expr);
2064 let needs_parens_pre = match self.tcx.parent_hir_node(expr.hir_id) {
2065 Node::Expr(e)
2066 if let hir::ExprKind::MethodCall(_, base, _, _) = e.kind
2067 && base.hir_id == expr.hir_id =>
2068 {
2069 true
2070 }
2071 _ => false,
2072 };
2073
2074 label();
2075 let suggestions = sugg_prefixes.into_iter().map(|sugg_prefix| {
2076 match (needs_parens_pre, needs_parens_post) {
2077 (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())],
2078 (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![
2081 (span.shrink_to_lo(), format!("{sugg_prefix}(")),
2082 (span.shrink_to_hi(), ")".to_string()),
2083 ],
2084 (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![
2087 (span.shrink_to_lo(), format!("({sugg_prefix}")),
2088 (span.shrink_to_hi(), ")".to_string()),
2089 ],
2090 (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![
2091 (span.shrink_to_lo(), format!("({sugg_prefix}(")),
2092 (span.shrink_to_hi(), "))".to_string()),
2093 ],
2094 }
2095 });
2096 err.multipart_suggestions(sugg_msg, suggestions, Applicability::MaybeIncorrect);
2097 return true;
2098 };
2099
2100 if let ObligationCauseCode::ImplDerived(cause) = &*code {
2101 try_borrowing(cause.derived.parent_trait_pred, &[])
2102 } else if let ObligationCauseCode::WhereClause(..)
2103 | ObligationCauseCode::WhereClauseInExpr(..) = code
2104 {
2105 try_borrowing(poly_trait_pred, &never_suggest_borrow)
2106 } else {
2107 false
2108 }
2109 }
2110
2111 pub(super) fn suggest_borrowing_for_object_cast(
2113 &self,
2114 err: &mut Diag<'_>,
2115 obligation: &PredicateObligation<'tcx>,
2116 self_ty: Ty<'tcx>,
2117 target_ty: Ty<'tcx>,
2118 ) {
2119 let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
2120 return;
2121 };
2122 let ty::Dynamic(predicates, _) = object_ty.kind() else {
2123 return;
2124 };
2125 let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
2126
2127 for predicate in predicates.iter() {
2128 if !self.predicate_must_hold_modulo_regions(
2129 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
2130 ) {
2131 return;
2132 }
2133 }
2134
2135 err.span_suggestion_verbose(
2136 obligation.cause.span.shrink_to_lo(),
2137 ::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!(
2138 "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
2139 ),
2140 "&",
2141 Applicability::MaybeIncorrect,
2142 );
2143 }
2144
2145 fn peel_expr_refs(
2150 &self,
2151 mut expr: &'tcx hir::Expr<'tcx>,
2152 mut ty: Ty<'tcx>,
2153 ) -> (Vec<PeeledRef<'tcx>>, Option<&'tcx hir::Param<'tcx>>) {
2154 let mut refs = Vec::new();
2155 'outer: loop {
2156 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
2157 let span =
2158 if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
2159 expr.span.until(borrowed_span)
2160 } else {
2161 break 'outer;
2162 };
2163
2164 let span = match self.tcx.sess.source_map().span_to_snippet(span) {
2170 Ok(ref snippet) if snippet.starts_with("&") => span,
2171 Ok(ref snippet) if let Some(amp) = snippet.find('&') => {
2172 span.with_lo(span.lo() + BytePos(amp as u32))
2173 }
2174 _ => break 'outer,
2175 };
2176
2177 let ty::Ref(_, inner_ty, _) = ty.kind() else {
2178 break 'outer;
2179 };
2180 ty = *inner_ty;
2181 refs.push(PeeledRef { span, peeled_ty: ty });
2182 expr = borrowed;
2183 }
2184 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
2185 && let Res::Local(hir_id) = path.res
2186 && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
2187 {
2188 match self.tcx.parent_hir_node(binding.hir_id) {
2189 hir::Node::LetStmt(local)
2191 if local.ty.is_none()
2192 && let Some(init) = local.init =>
2193 {
2194 expr = init;
2195 continue;
2196 }
2197 hir::Node::LetStmt(local)
2200 if #[allow(non_exhaustive_omitted_patterns)] match local.source {
hir::LocalSource::AsyncFn => true,
_ => false,
}matches!(local.source, hir::LocalSource::AsyncFn)
2201 && let Some(init) = local.init
2202 && let hir::ExprKind::Path(hir::QPath::Resolved(None, arg_path)) =
2203 init.kind
2204 && let Res::Local(arg_hir_id) = arg_path.res
2205 && let hir::Node::Pat(arg_binding) = self.tcx.hir_node(arg_hir_id)
2206 && let hir::Node::Param(param) =
2207 self.tcx.parent_hir_node(arg_binding.hir_id) =>
2208 {
2209 return (refs, Some(param));
2210 }
2211 hir::Node::Param(param) => {
2213 return (refs, Some(param));
2214 }
2215 _ => break 'outer,
2216 }
2217 } else {
2218 break 'outer;
2219 }
2220 }
2221 (refs, None)
2222 }
2223
2224 pub(super) fn suggest_remove_reference(
2227 &self,
2228 obligation: &PredicateObligation<'tcx>,
2229 err: &mut Diag<'_>,
2230 trait_pred: ty::PolyTraitClause<'tcx>,
2231 ) -> bool {
2232 let mut span = obligation.cause.span;
2233 let mut trait_pred = trait_pred;
2234 let mut code = obligation.cause.code();
2235 while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
2236 code = c;
2239 trait_pred = parent_trait_pred;
2240 }
2241 while span.desugaring_kind().is_some() {
2242 span.remove_mark();
2244 }
2245 let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
2246 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id) else {
2247 return false;
2248 };
2249 expr_finder.visit_expr(body.value);
2250 let mut maybe_suggest = |suggested_ty, count, suggestions| {
2251 let trait_pred_and_suggested_ty =
2253 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2254
2255 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2256 obligation.param_env,
2257 trait_pred_and_suggested_ty,
2258 );
2259
2260 if self.predicate_may_hold(&new_obligation) {
2261 let msg = if count == 1 {
2262 "consider removing the leading `&`-reference".to_string()
2263 } else {
2264 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
2265 };
2266
2267 err.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
2268 true
2269 } else {
2270 false
2271 }
2272 };
2273
2274 let mut count = 0;
2277 let mut suggestions = ::alloc::vec::Vec::new()vec![];
2278 let mut suggested_ty = trait_pred.self_ty().skip_binder();
2280 if let Some(mut hir_ty) = expr_finder.ty_result {
2281 while let hir::TyKind::Ref(_, ref_ty, _) = &hir_ty.kind {
2282 count += 1;
2283 let span = hir_ty.span.until(ref_ty.span);
2284 suggestions.push((span, String::new()));
2285
2286 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
2287 break;
2288 };
2289 suggested_ty = *inner_ty;
2290
2291 hir_ty = ref_ty;
2292
2293 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
2294 return true;
2295 }
2296 }
2297 }
2298
2299 let Some(expr) = expr_finder.result else {
2301 return false;
2302 };
2303 let suggested_ty = trait_pred.self_ty().skip_binder();
2305 let (peeled_refs, _) = self.peel_expr_refs(expr, suggested_ty);
2306 for (i, peeled) in peeled_refs.iter().enumerate() {
2307 let suggestions: Vec<_> =
2308 peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2309 if maybe_suggest(peeled.peeled_ty, i + 1, suggestions) {
2310 return true;
2311 }
2312 }
2313 false
2314 }
2315
2316 fn suggest_remove_ref_from_param(&self, param: &hir::Param<'_>, err: &mut Diag<'_>) -> bool {
2318 if let Some(decl) = self.tcx.parent_hir_node(param.hir_id).fn_decl()
2319 && let Some(input_ty) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
2320 && let hir::TyKind::Ref(_, ty, _) = input_ty.kind
2321 {
2322 let ref_span = input_ty.span.until(ty.span);
2323 match self.tcx.sess.source_map().span_to_snippet(ref_span) {
2324 Ok(snippet) if snippet.starts_with("&") => {
2325 err.span_suggestion_verbose(
2326 ref_span,
2327 "consider removing the `&` from the parameter type",
2328 "",
2329 Applicability::MaybeIncorrect,
2330 );
2331 return true;
2332 }
2333 _ => {}
2334 }
2335 }
2336 false
2337 }
2338
2339 pub(super) fn suggest_remove_await(
2340 &self,
2341 obligation: &PredicateObligation<'tcx>,
2342 err: &mut Diag<'_>,
2343 ) {
2344 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
2345 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2346 {
2347 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2355 obligation.predicate.kind().skip_binder()
2356 {
2357 let self_ty = pred.self_ty();
2358 let future_trait =
2359 self.tcx.require_lang_item(LangItem::Future, obligation.cause.span);
2360
2361 let has_future = {
2363 let mut ty = self_ty;
2364 loop {
2365 match *ty.kind() {
2366 ty::Ref(_, inner_ty, _)
2367 if !#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind() {
ty::Dynamic(..) => true,
_ => false,
}matches!(inner_ty.kind(), ty::Dynamic(..)) =>
2368 {
2369 if self
2370 .type_implements_trait(
2371 future_trait,
2372 [inner_ty],
2373 obligation.param_env,
2374 )
2375 .must_apply_modulo_regions()
2376 {
2377 break true;
2378 }
2379 ty = inner_ty;
2380 }
2381 _ => break false,
2382 }
2383 }
2384 };
2385
2386 if has_future {
2387 let (peeled_refs, terminal_param) = self.peel_expr_refs(expr, self_ty);
2388
2389 for (i, peeled) in peeled_refs.iter().enumerate() {
2391 if self
2392 .type_implements_trait(
2393 future_trait,
2394 [peeled.peeled_ty],
2395 obligation.param_env,
2396 )
2397 .must_apply_modulo_regions()
2398 {
2399 let count = i + 1;
2400 let msg = if count == 1 {
2401 "consider removing the leading `&`-reference".to_string()
2402 } else {
2403 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
2404 };
2405 let suggestions: Vec<_> =
2406 peeled_refs[..=i].iter().map(|r| (r.span, String::new())).collect();
2407 err.multipart_suggestion(
2408 msg,
2409 suggestions,
2410 Applicability::MachineApplicable,
2411 );
2412 return;
2413 }
2414 }
2415
2416 if peeled_refs.is_empty()
2420 && let Some(param) = terminal_param
2421 && self.suggest_remove_ref_from_param(param, err)
2422 {
2423 return;
2424 }
2425
2426 err.help(
2428 "a reference to a future is not a future; \
2429 consider removing the leading `&`-reference",
2430 );
2431 return;
2432 }
2433 }
2434
2435 if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
2437 && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
2438 {
2439 let removal_span = self
2440 .tcx
2441 .sess
2442 .source_map()
2443 .span_extend_while_whitespace(expr_span)
2444 .shrink_to_hi()
2445 .to(await_expr.span.shrink_to_hi());
2446 err.span_suggestion_verbose(
2447 removal_span,
2448 "remove the `.await`",
2449 "",
2450 Applicability::MachineApplicable,
2451 );
2452 } else {
2453 err.span_label(obligation.cause.span, "remove the `.await`");
2454 }
2455 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
2457 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
2458 obligation.predicate.kind().skip_binder()
2459 {
2460 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()));
2461 }
2462 if let Some(typeck_results) = &self.typeck_results
2463 && let ty = typeck_results.expr_ty_adjusted(base)
2464 && let ty::FnDef(def_id, _args) = ty.kind()
2465 && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
2466 {
2467 let (ident, _, _, _) = item.expect_fn();
2468 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");
2469 if item.vis_span.is_empty() {
2470 err.span_suggestion_verbose(
2471 item.span.shrink_to_lo(),
2472 msg,
2473 "async ",
2474 Applicability::MaybeIncorrect,
2475 );
2476 } else {
2477 err.span_suggestion_verbose(
2478 item.vis_span.shrink_to_hi(),
2479 msg,
2480 " async",
2481 Applicability::MaybeIncorrect,
2482 );
2483 }
2484 }
2485 }
2486 }
2487 }
2488
2489 pub(super) fn suggest_change_mut(
2492 &self,
2493 obligation: &PredicateObligation<'tcx>,
2494 err: &mut Diag<'_>,
2495 trait_pred: ty::PolyTraitClause<'tcx>,
2496 ) {
2497 let points_at_arg =
2498 #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
ObligationCauseCode::FunctionArg { .. } => true,
_ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
2499
2500 let span = obligation.cause.span;
2501 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
2502 let refs_number =
2503 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
2504 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
2505 return;
2507 }
2508 let trait_pred = self.deeply_resolve_ignoring_regions(trait_pred);
2509 if trait_pred.has_non_region_infer() {
2510 return;
2513 }
2514
2515 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
2517 {
2518 let suggested_ty = match mutability {
2519 hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
2520 hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
2521 };
2522
2523 let trait_pred_and_suggested_ty =
2525 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
2526
2527 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
2528 obligation.param_env,
2529 trait_pred_and_suggested_ty,
2530 );
2531 let suggested_ty_would_satisfy_obligation = self
2532 .evaluate_obligation_no_overflow(&new_obligation)
2533 .must_apply_modulo_regions();
2534 if suggested_ty_would_satisfy_obligation {
2535 let sp = self
2536 .tcx
2537 .sess
2538 .source_map()
2539 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
2540 if points_at_arg
2541 && mutability.is_not()
2542 && refs_number > 0
2543 && span.can_be_used_for_suggestions()
2547 {
2548 if snippet
2550 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
2551 .starts_with("mut")
2552 {
2553 return;
2554 }
2555 err.span_suggestion_verbose(
2556 sp,
2557 "consider changing this borrow's mutability",
2558 "&mut ",
2559 Applicability::MachineApplicable,
2560 );
2561 } else {
2562 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!(
2563 "`{}` is implemented for `{}`, but not for `{}`",
2564 trait_pred.print_modifiers_and_trait_path(),
2565 suggested_ty,
2566 trait_pred.skip_binder().self_ty(),
2567 ));
2568 }
2569 }
2570 }
2571 }
2572 }
2573
2574 pub(super) fn suggest_semicolon_removal(
2575 &self,
2576 obligation: &PredicateObligation<'tcx>,
2577 err: &mut Diag<'_>,
2578 span: Span,
2579 trait_pred: ty::PolyTraitClause<'tcx>,
2580 ) -> bool {
2581 if !trait_pred.self_ty().skip_binder().is_unit() {
2582 return false;
2583 }
2584 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
2585 if let hir::Node::Item(hir::Item {
2586 kind: hir::ItemKind::Fn { sig, body: body_id, .. }, ..
2587 }) = node
2588 && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
2589 && sig.decl.output.span().overlaps(span)
2590 && let Some(candidate) = self.removable_trailing_semicolon(blk, obligation, trait_pred)
2591 {
2592 self.emit_semicolon_removal_suggestion(
2595 err,
2596 trait_pred,
2597 candidate,
2598 Applicability::MachineApplicable,
2599 );
2600 return true;
2601 }
2602 self.suggest_semicolon_removal_in_closure_arg(obligation, err, trait_pred)
2603 }
2604
2605 fn removable_trailing_semicolon(
2608 &self,
2609 block: &hir::Block<'tcx>,
2610 obligation: &PredicateObligation<'tcx>,
2611 trait_pred: ty::PolyTraitClause<'tcx>,
2612 ) -> Option<(&'tcx hir::Stmt<'tcx>, &'tcx hir::Expr<'tcx>, Ty<'tcx>)> {
2613 if block.expr.is_none()
2614 && let Some(stmt) = block.stmts.last()
2615 && let hir::StmtKind::Semi(expr) = stmt.kind
2616 && !stmt.span.from_expansion()
2617 && !#[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Err(_) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Err(_))
2618 && let Some(typeck_results) = &self.typeck_results
2620 && let Some(ty) =
2621 typeck_results.expr_ty_opt(expr).map(|ty| self.deeply_resolve_ignoring_regions(ty))
2622 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
2623 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
2624 ))
2625 {
2626 Some((stmt, expr, ty))
2627 } else {
2628 None
2629 }
2630 }
2631
2632 fn emit_semicolon_removal_suggestion(
2633 &self,
2634 err: &mut Diag<'_>,
2635 trait_pred: ty::PolyTraitClause<'tcx>,
2636 (stmt, expr, ty): (&hir::Stmt<'_>, &hir::Expr<'_>, Ty<'tcx>),
2637 applicability: Applicability,
2638 ) {
2639 err.span_label(
2640 expr.span,
2641 ::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!(
2642 "this expression has type `{}`, which implements `{}`",
2643 ty,
2644 trait_pred.print_modifiers_and_trait_path()
2645 ),
2646 );
2647 err.span_suggestion(
2648 self.tcx.sess.source_map().end_point(stmt.span),
2649 "remove this semicolon",
2650 "",
2651 applicability,
2652 );
2653 }
2654
2655 fn suggest_semicolon_removal_in_closure_arg(
2664 &self,
2665 obligation: &PredicateObligation<'tcx>,
2666 err: &mut Diag<'_>,
2667 trait_pred: ty::PolyTraitClause<'tcx>,
2668 ) -> bool {
2669 let &ObligationCauseCode::WhereClauseInExpr(callee_def_id, _, hir_id, idx) =
2670 obligation.cause.code().peel_derives()
2671 else {
2672 return false;
2673 };
2674 if !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(callee_def_id)
{
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(self.tcx.def_kind(callee_def_id), DefKind::Fn | DefKind::AssocFn) {
2677 return false;
2678 }
2679 let hir::Node::Expr(expr) = self.tcx.hir_node(hir_id) else {
2680 return false;
2681 };
2682 let Some(typeck_results) = &self.typeck_results else {
2683 return false;
2684 };
2685 let args: Vec<&hir::Expr<'_>> =
2686 match expr.kind {
2687 hir::ExprKind::MethodCall(_, receiver, args, _) => {
2688 iter::once(receiver).chain(args).collect()
2689 }
2690 _ => match self.tcx.parent_hir_node(expr.hir_id) {
2693 hir::Node::Expr(hir::Expr {
2694 kind: hir::ExprKind::Call(callee, args), ..
2695 }) if callee.hir_id == expr.hir_id => args.iter().collect(),
2696 _ => return false,
2697 },
2698 };
2699 let clauses = self.tcx.clauses_of(callee_def_id).instantiate_identity(self.tcx);
2702 let Some(ty::ClauseKind::Trait(failed)) = clauses
2703 .clauses
2704 .get(idx)
2705 .map(|clause| clause.as_ref().skip_norm_wip().kind().skip_binder())
2706 else {
2707 return false;
2708 };
2709 let sig =
2710 self.tcx.fn_sig(callee_def_id).instantiate_identity().skip_norm_wip().skip_binder();
2711 let mut candidates = args.into_iter().enumerate().filter_map(|(i, arg)| {
2712 let declared = sig.inputs().get(i)?.peel_refs();
2715 if !clauses.clauses.iter().any(|clause| {
2716 #[allow(non_exhaustive_omitted_patterns)] match clause.as_ref().skip_norm_wip().kind().skip_binder()
{
ty::ClauseKind::Projection(proj) if
self.tcx.is_lang_item(proj.def_id(), LangItem::FnOnceOutput) &&
proj.projection_term.self_ty() == declared &&
proj.term.as_type() == Some(failed.self_ty()) => true,
_ => false,
}matches!(
2717 clause.as_ref().skip_norm_wip().kind().skip_binder(),
2718 ty::ClauseKind::Projection(proj)
2719 if self.tcx.is_lang_item(proj.def_id(), LangItem::FnOnceOutput)
2720 && proj.projection_term.self_ty() == declared
2721 && proj.term.as_type() == Some(failed.self_ty())
2722 )
2723 }) {
2724 return None;
2725 }
2726 let closure_def_id = match arg.kind {
2730 hir::ExprKind::Closure(closure) => closure.def_id,
2731 _ => match typeck_results
2732 .expr_ty_adjusted_opt(arg)
2733 .map(|ty| *self.deeply_resolve_ignoring_regions(ty).peel_refs().kind())
2734 {
2735 Some(ty::Closure(def_id, _)) => def_id.as_local()?,
2736 _ => return None,
2737 },
2738 };
2739 let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
2740 self.tcx.hir_node_by_def_id(closure_def_id)
2741 else {
2742 return None;
2743 };
2744 let hir::ExprKind::Block(block, None) = self.tcx.hir_body(closure.body).value.kind
2745 else {
2746 return None;
2747 };
2748 self.removable_trailing_semicolon(block, obligation, trait_pred)
2749 });
2750 if let Some(candidate) = candidates.next()
2753 && candidates.next().is_none()
2754 {
2755 self.emit_semicolon_removal_suggestion(
2758 err,
2759 trait_pred,
2760 candidate,
2761 Applicability::MaybeIncorrect,
2762 );
2763 return true;
2764 }
2765 false
2766 }
2767
2768 pub(super) fn suggest_borrow_for_unsized_closure_return(
2769 &self,
2770 body_def_id: LocalDefId,
2771 err: &mut Diag<'_>,
2772 predicate: ty::Predicate<'tcx>,
2773 ) {
2774 let Some(pred) = predicate.as_trait_clause() else {
2775 return;
2776 };
2777 if !self.tcx.is_lang_item(pred.def_id(), LangItem::Sized) {
2778 return;
2779 }
2780
2781 let Some(span) = err.span.primary_span() else {
2782 return;
2783 };
2784 let Some(body_id) = self.tcx.hir_node_by_def_id(body_def_id).body_id() else {
2785 return;
2786 };
2787 let body = self.tcx.hir_body(body_id);
2788 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
2789 expr_finder.visit_expr(body.value);
2790 let Some(expr) = expr_finder.result else {
2791 return;
2792 };
2793
2794 let closure = match expr.kind {
2795 hir::ExprKind::Call(_, args) => args.iter().find_map(|arg| match arg.kind {
2796 hir::ExprKind::Closure(closure) => Some(closure),
2797 _ => None,
2798 }),
2799 hir::ExprKind::MethodCall(_, _, args, _) => {
2800 args.iter().find_map(|arg| match arg.kind {
2801 hir::ExprKind::Closure(closure) => Some(closure),
2802 _ => None,
2803 })
2804 }
2805 _ => None,
2806 };
2807 let Some(closure) = closure else {
2808 return;
2809 };
2810 if !#[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
hir::FnRetTy::DefaultReturn(_) => true,
_ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_)) {
2811 return;
2812 }
2813
2814 err.span_suggestion_verbose(
2815 self.tcx.hir_body(closure.body).value.span.shrink_to_lo(),
2816 "consider borrowing the value",
2817 "&",
2818 Applicability::MaybeIncorrect,
2819 );
2820 }
2821
2822 pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
2823 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
2824 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2825 else {
2826 return None;
2827 };
2828
2829 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
2830 }
2831
2832 pub(super) fn suggest_impl_trait(
2836 &self,
2837 err: &mut Diag<'_>,
2838 obligation: &PredicateObligation<'tcx>,
2839 trait_pred: ty::PolyTraitClause<'tcx>,
2840 ) -> bool {
2841 let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
2842 return false;
2843 };
2844 let ty::Dynamic(_, _) = trait_pred.self_ty().skip_binder().kind() else {
2845 return false;
2846 };
2847 if let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2848 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2849 | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, _), .. }) =
2850 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2851 && let hir::FnRetTy::Return(ty) = fn_sig.decl.output
2852 && let hir::TyKind::Path(qpath) = ty.kind
2853 && let hir::QPath::Resolved(None, path) = qpath
2854 && let Res::Def(DefKind::TyAlias, def_id) = path.res
2855 {
2856 err.span_note(self.tcx.def_span(def_id), "this type alias is unsized");
2860 err.multipart_suggestion(
2861 ::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!(
2862 "consider boxing the return type, and wrapping all of the returned values in \
2863 `Box::new`",
2864 ),
2865 ::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![
2866 (ty.span.shrink_to_lo(), "Box<".to_string()),
2867 (ty.span.shrink_to_hi(), ">".to_string()),
2868 ],
2869 Applicability::MaybeIncorrect,
2870 );
2871 return false;
2872 }
2873
2874 err.code(E0746);
2875 err.primary_message("return type cannot be a trait object without pointer indirection");
2876 err.children.clear();
2877
2878 let mut span = obligation.cause.span;
2879 let mut is_async_fn_return = false;
2880 if let DefKind::Closure = self.tcx.def_kind(obligation.cause.body_def_id)
2881 && let parent = self.tcx.local_parent(obligation.cause.body_def_id)
2882 && let DefKind::Fn | DefKind::AssocFn = self.tcx.def_kind(parent)
2883 && self.tcx.asyncness(parent).is_async()
2884 && let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
2885 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
2886 | Node::TraitItem(hir::TraitItem {
2887 kind: hir::TraitItemKind::Fn(fn_sig, _), ..
2888 }) = self.tcx.hir_node_by_def_id(parent)
2889 {
2890 span = fn_sig.decl.output.span();
2895 is_async_fn_return = true;
2896 err.span(span);
2897 }
2898 let body = self.tcx.hir_body_owned_by(obligation.cause.body_def_id);
2899
2900 if !is_async_fn_return
2901 && let Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) =
2902 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
2903 && #[allow(non_exhaustive_omitted_patterns)] match closure.fn_decl.output {
hir::FnRetTy::DefaultReturn(_) => true,
_ => false,
}matches!(closure.fn_decl.output, hir::FnRetTy::DefaultReturn(_))
2904 {
2905 return true;
2906 }
2907
2908 let mut visitor = ReturnsVisitor::default();
2909 visitor.visit_body(&body);
2910
2911 let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
2912 && snip.starts_with("dyn ")
2913 {
2914 ("", span.with_hi(span.lo() + BytePos(4)))
2915 } else {
2916 ("dyn ", span.shrink_to_lo())
2917 };
2918
2919 err.span_suggestion_verbose(
2920 impl_span,
2921 "consider returning an `impl Trait` instead of a `dyn Trait`",
2922 "impl ",
2923 Applicability::MaybeIncorrect,
2924 );
2925
2926 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![
2927 (span.shrink_to_lo(), format!("Box<{pre}")),
2928 (span.shrink_to_hi(), ">".to_string()),
2929 ];
2930 sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
2931 let span =
2932 expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
2933 if !span.can_be_used_for_suggestions() {
2934 ::alloc::vec::Vec::new()vec![]
2935 } else if let hir::ExprKind::Call(path, ..) = expr.kind
2936 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
2937 && method.ident.name == sym::new
2938 && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
2939 && box_path
2940 .res
2941 .opt_def_id()
2942 .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
2943 {
2944 ::alloc::vec::Vec::new()vec![]
2946 } else {
2947 ::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![
2948 (span.shrink_to_lo(), "Box::new(".to_string()),
2949 (span.shrink_to_hi(), ")".to_string()),
2950 ]
2951 }
2952 }));
2953
2954 err.multipart_suggestion(
2955 ::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!(
2956 "alternatively, box the return type, and wrap all of the returned values in \
2957 `Box::new`",
2958 ),
2959 sugg,
2960 Applicability::MaybeIncorrect,
2961 );
2962
2963 true
2964 }
2965
2966 pub(super) fn report_closure_arg_mismatch(
2967 &self,
2968 span: Span,
2969 found_span: Option<Span>,
2970 found: ty::TraitRef<'tcx>,
2971 expected: ty::TraitRef<'tcx>,
2972 cause: &ObligationCauseCode<'tcx>,
2973 found_node: Option<Node<'_>>,
2974 param_env: ty::ParamEnv<'tcx>,
2975 ) -> Diag<'a> {
2976 pub(crate) fn build_fn_sig_ty<'tcx>(
2977 infcx: &InferCtxt<'tcx>,
2978 trait_ref: ty::TraitRef<'tcx>,
2979 ) -> Ty<'tcx> {
2980 let inputs = trait_ref.args.type_at(1);
2981 let sig = match inputs.kind() {
2982 ty::Tuple(inputs) if infcx.tcx.is_callable_trait(trait_ref.def_id) => {
2983 infcx.tcx.mk_fn_sig_safe_rust_abi(*inputs, infcx.next_ty_var(DUMMY_SP))
2984 }
2985 _ => infcx.tcx.mk_fn_sig_safe_rust_abi([inputs], infcx.next_ty_var(DUMMY_SP)),
2986 };
2987
2988 Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
2989 }
2990
2991 let argument_kind = match expected.self_ty().kind() {
2992 ty::Closure(..) => "closure",
2993 ty::Coroutine(..) => "coroutine",
2994 _ => "function",
2995 };
2996 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!(
2997 self.dcx(),
2998 span,
2999 E0631,
3000 "type mismatch in {argument_kind} arguments",
3001 );
3002
3003 err.span_label(span, "expected due to this");
3004
3005 let found_span = found_span.unwrap_or(span);
3006 err.span_label(found_span, "found signature defined here");
3007
3008 let expected = build_fn_sig_ty(self, expected);
3009 let found = build_fn_sig_ty(self, found);
3010
3011 let (expected_str, found_str) = self.cmp(expected, found);
3012
3013 let signature_kind = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} signature", argument_kind))
})format!("{argument_kind} signature");
3014 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
3015
3016 self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
3017 self.note_conflicting_closure_bounds(cause, &mut err);
3018
3019 if let Some(found_node) = found_node {
3020 hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
3021 }
3022
3023 err
3024 }
3025
3026 fn note_conflicting_fn_args(
3027 &self,
3028 err: &mut Diag<'_>,
3029 cause: &ObligationCauseCode<'tcx>,
3030 expected: Ty<'tcx>,
3031 found: Ty<'tcx>,
3032 param_env: ty::ParamEnv<'tcx>,
3033 ) {
3034 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
3035 return;
3036 };
3037 let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
3038 return;
3039 };
3040 let expected = sig_tys.with(*hdr);
3041 let ty::FnPtr(sig_tys, hdr) = found.kind() else {
3042 return;
3043 };
3044 let found = sig_tys.with(*hdr);
3045 let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
3046 return;
3047 };
3048 let hir::ExprKind::Path(path) = arg.kind else {
3049 return;
3050 };
3051 let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
3052 let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
3053 let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
3054
3055 let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
3056 let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
3057 let (found_ty, found_refs) = get_deref_type_and_refs(found);
3058
3059 if infcx.can_eq(param_env, found_ty, expected_ty) {
3060 if found_refs.len() == expected_refs.len()
3061 && found_refs.iter().eq(expected_refs.iter())
3062 {
3063 name
3064 } else if found_refs.len() > expected_refs.len() {
3065 let refs = &found_refs[..found_refs.len() - expected_refs.len()];
3066 if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
3067 ::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!(
3068 "{}{name}",
3069 refs.iter()
3070 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3071 .collect::<Vec<_>>()
3072 .join(""),
3073 )
3074 } else {
3075 ::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!(
3077 "{}*{name}",
3078 refs.iter()
3079 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3080 .collect::<Vec<_>>()
3081 .join(""),
3082 )
3083 }
3084 } else if expected_refs.len() > found_refs.len() {
3085 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
(0..(expected_refs.len() -
found_refs.len())).map(|_|
"*").collect::<Vec<_>>().join(""), name))
})format!(
3086 "{}{name}",
3087 (0..(expected_refs.len() - found_refs.len()))
3088 .map(|_| "*")
3089 .collect::<Vec<_>>()
3090 .join(""),
3091 )
3092 } else {
3093 ::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!(
3094 "{}{name}",
3095 found_refs
3096 .iter()
3097 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
3098 .chain(found_refs.iter().map(|_| "*".to_string()))
3099 .collect::<Vec<_>>()
3100 .join(""),
3101 )
3102 }
3103 } else {
3104 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", found))
})format!("/* {found} */")
3105 }
3106 };
3107 let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
3108 let (expected_ty, _) = get_deref_type_and_refs(expected);
3109 let (found_ty, _) = get_deref_type_and_refs(found);
3110 self.can_eq(param_env, found_ty, expected_ty)
3111 });
3112 let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
3113 && !expected_inputs.is_empty()
3114 && expected_inputs.len() == found_inputs.len()
3115 && let Some(typeck) = &self.typeck_results
3116 && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
3117 && res_kind.is_fn_like()
3118 {
3119 let closure: Vec<_> = self
3120 .tcx
3121 .fn_arg_idents(fn_def_id)
3122 .iter()
3123 .enumerate()
3124 .map(|(i, ident)| {
3125 if let Some(ident) = ident
3126 && !#[allow(non_exhaustive_omitted_patterns)] match ident {
Ident { name: kw::Underscore | kw::SelfLower, .. } => true,
_ => false,
}matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
3127 {
3128 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}")
3129 } else {
3130 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}")
3131 }
3132 })
3133 .collect();
3134 let args = closure
3135 .iter()
3136 .zip(both_tys)
3137 .map(|(name, (expected, found))| {
3138 arg_expr(self.infcx, name.to_owned(), expected, found)
3139 })
3140 .collect();
3141 (closure, args)
3142 } else {
3143 let closure_args = expected_inputs
3144 .iter()
3145 .enumerate()
3146 .map(|(i, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"))
3147 .collect::<Vec<_>>();
3148 let call_args = both_tys
3149 .enumerate()
3150 .map(|(i, (expected, found))| {
3151 arg_expr(self.infcx, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"), expected, found)
3152 })
3153 .collect::<Vec<_>>();
3154 (closure_args, call_args)
3155 };
3156 let closure_names: Vec<_> = closure_names
3157 .into_iter()
3158 .zip(expected_inputs.iter())
3159 .map(|(name, ty)| {
3160 ::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!(
3161 "{name}{}",
3162 if ty.has_infer_types() {
3163 String::new()
3164 } else if ty.references_error() {
3165 ": /* type */".to_string()
3166 } else {
3167 format!(": {ty}")
3168 }
3169 )
3170 })
3171 .collect();
3172 err.multipart_suggestion(
3173 "consider wrapping the function in a closure",
3174 ::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![
3175 (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
3176 (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
3177 ],
3178 Applicability::MaybeIncorrect,
3179 );
3180 }
3181
3182 fn note_conflicting_closure_bounds(
3185 &self,
3186 cause: &ObligationCauseCode<'tcx>,
3187 err: &mut Diag<'_>,
3188 ) {
3189 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *cause
3193 && let gen_clauses = self.tcx.clauses_of(def_id).instantiate_identity(self.tcx)
3194 && let Some(clause) = gen_clauses.clauses.get(idx).map(|c| c.as_ref().skip_norm_wip())
3195 && let ty::ClauseKind::Trait(trait_pred) = clause.kind().skip_binder()
3196 && self.tcx.is_fn_trait(trait_pred.def_id())
3197 {
3198 let expected_self =
3199 self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.self_ty()));
3200 let expected_args =
3201 self.tcx.anonymize_bound_vars(clause.kind().rebind(trait_pred.trait_ref.args));
3202
3203 let other_clause =
3206 gen_clauses.into_iter().enumerate().find(|&(other_idx, (clause, _))| {
3207 let clause = clause.skip_norm_wip();
3208 match clause.kind().skip_binder() {
3209 ty::ClauseKind::Trait(trait_pred)
3210 if self.tcx.is_fn_trait(trait_pred.def_id())
3211 && other_idx != idx
3212 && expected_self
3215 == self.tcx.anonymize_bound_vars(
3216 clause.kind().rebind(trait_pred.self_ty()),
3217 )
3218 && expected_args
3220 != self.tcx.anonymize_bound_vars(
3221 clause.kind().rebind(trait_pred.trait_ref.args),
3222 ) =>
3223 {
3224 true
3225 }
3226 _ => false,
3227 }
3228 });
3229 if let Some((_, (_, other_clause_span))) = other_clause {
3231 err.span_note(
3232 other_clause_span,
3233 "closure inferred to have a different signature due to this bound",
3234 );
3235 }
3236 }
3237 }
3238
3239 pub(super) fn suggest_fully_qualified_path(
3240 &self,
3241 err: &mut Diag<'_>,
3242 item_def_id: DefId,
3243 span: Span,
3244 trait_ref: DefId,
3245 ) {
3246 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
3247 && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
3248 {
3249 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!(
3250 "{}s cannot be accessed directly on a `trait`, they can only be \
3251 accessed through a specific `impl`",
3252 self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
3253 ));
3254
3255 if !assoc_item.is_impl_trait_in_trait() {
3256 err.span_suggestion_verbose(
3257 span,
3258 "use the fully qualified path to an implementation",
3259 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
self.tcx.def_path_str(trait_ref), assoc_item.name()))
})format!(
3260 "<Type as {}>::{}",
3261 self.tcx.def_path_str(trait_ref),
3262 assoc_item.name()
3263 ),
3264 Applicability::HasPlaceholders,
3265 );
3266 }
3267 }
3268 }
3269
3270 {}
#[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("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3312u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligation.predicate")
}> =
::tracing::__macro_support::FieldName::new("obligation.predicate");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligation.cause.span")
}> =
::tracing::__macro_support::FieldName::new("obligation.cause.span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation.predicate)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation.cause.span)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: 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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3351",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3351u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("code")
}> =
::tracing::__macro_support::FieldName::new("code");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&code)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3358",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3358u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("parent_trait_ref");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self_ty.kind")
}> =
::tracing::__macro_support::FieldName::new("self_ty.kind");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ImplDerived")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause.derived.parent_trait_pred)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty.kind())
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3388",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3388u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("parent_trait_ref");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self_ty.kind")
}> =
::tracing::__macro_support::FieldName::new("self_ty.kind");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&derived_obligation.parent_trait_pred)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty.kind())
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3419",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3419u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("coroutine")
}> =
::tracing::__macro_support::FieldName::new("coroutine");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ref")
}> =
::tracing::__macro_support::FieldName::new("trait_ref");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("target_ty")
}> =
::tracing::__macro_support::FieldName::new("target_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_ty)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3429",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3429u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("coroutine_did")
}> =
::tracing::__macro_support::FieldName::new("coroutine_did");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("coroutine_did_root")
}> =
::tracing::__macro_support::FieldName::new("coroutine_did_root");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("typeck_results.hir_owner")
}> =
::tracing::__macro_support::FieldName::new("typeck_results.hir_owner");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_did)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_did_root)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.typeck_results.as_ref().map(|t|
t.hir_owner)) as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3442",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3442u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("awaits")
}> =
::tracing::__macro_support::FieldName::new("awaits");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&visitor.awaits)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3463",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3463u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty_erased")
}> =
::tracing::__macro_support::FieldName::new("ty_erased");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("target_ty_erased")
}> =
::tracing::__macro_support::FieldName::new("target_ty_erased");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("eq")
}> =
::tracing::__macro_support::FieldName::new("eq");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty_erased)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target_ty_erased)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&eq)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3487",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3487u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("from_awaited_ty")
}> =
::tracing::__macro_support::FieldName::new("from_awaited_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&from_awaited_ty)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3495",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3495u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("coroutine_info")
}> =
::tracing::__macro_support::FieldName::new("coroutine_info");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_info)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3499",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3499u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("variant")
}> =
::tracing::__macro_support::FieldName::new("variant");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3502",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3502u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("decl")
}> =
::tracing::__macro_support::FieldName::new("decl");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3523",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3523u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("interior_or_upvar_span")
}> =
::tracing::__macro_support::FieldName::new("interior_or_upvar_span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&interior_or_upvar_span)
as &dyn ::tracing::field::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))]
3313 pub fn maybe_note_obligation_cause_for_async_await(
3314 &self,
3315 err: &mut Diag<'_>,
3316 obligation: &PredicateObligation<'tcx>,
3317 ) -> bool {
3318 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
3341 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
3342 _ => (None, None),
3343 };
3344 let mut coroutine = None;
3345 let mut outer_coroutine = None;
3346 let mut next_code = Some(obligation.cause.code());
3347
3348 let mut seen_upvar_tys_infer_tuple = false;
3349
3350 while let Some(code) = next_code {
3351 debug!(?code);
3352 match code {
3353 ObligationCauseCode::FunctionArg { parent_code, .. } => {
3354 next_code = Some(parent_code);
3355 }
3356 ObligationCauseCode::ImplDerived(cause) => {
3357 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
3358 debug!(
3359 parent_trait_ref = ?cause.derived.parent_trait_pred,
3360 self_ty.kind = ?ty.kind(),
3361 "ImplDerived",
3362 );
3363
3364 match *ty.kind() {
3365 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
3366 coroutine = coroutine.or(Some(did));
3367 outer_coroutine = Some(did);
3368 }
3369 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3370 seen_upvar_tys_infer_tuple = true;
3375 }
3376 _ if coroutine.is_none() => {
3377 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
3378 target_ty = Some(ty);
3379 }
3380 _ => {}
3381 }
3382
3383 next_code = Some(&cause.derived.parent_code);
3384 }
3385 ObligationCauseCode::WellFormedDerived(derived_obligation)
3386 | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
3387 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
3388 debug!(
3389 parent_trait_ref = ?derived_obligation.parent_trait_pred,
3390 self_ty.kind = ?ty.kind(),
3391 );
3392
3393 match *ty.kind() {
3394 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
3395 coroutine = coroutine.or(Some(did));
3396 outer_coroutine = Some(did);
3397 }
3398 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
3399 seen_upvar_tys_infer_tuple = true;
3404 }
3405 _ if coroutine.is_none() => {
3406 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
3407 target_ty = Some(ty);
3408 }
3409 _ => {}
3410 }
3411
3412 next_code = Some(&derived_obligation.parent_code);
3413 }
3414 _ => break,
3415 }
3416 }
3417
3418 debug!(?coroutine, ?trait_ref, ?target_ty);
3420 let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
3421 (coroutine, trait_ref, target_ty)
3422 else {
3423 return false;
3424 };
3425
3426 let span = self.tcx.def_span(coroutine_did);
3427
3428 let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
3429 debug!(
3430 ?coroutine_did,
3431 ?coroutine_did_root,
3432 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
3433 ?span,
3434 );
3435
3436 let coroutine_body =
3437 coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
3438 let mut visitor = AwaitsVisitor::default();
3439 if let Some(body) = coroutine_body {
3440 visitor.visit_body(&body);
3441 }
3442 debug!(awaits = ?visitor.awaits);
3443
3444 let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
3447 let ty_matches = |ty| -> bool {
3448 let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
3461 let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
3462 let eq = ty_erased == target_ty_erased;
3463 debug!(?ty_erased, ?target_ty_erased, ?eq);
3464 eq
3465 };
3466
3467 let coroutine_data = match &self.typeck_results {
3472 Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
3473 _ if coroutine_did.is_local() => {
3474 CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
3475 }
3476 _ => return false,
3477 };
3478
3479 let coroutine_within_in_progress_typeck = match &self.typeck_results {
3480 Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
3481 _ => false,
3482 };
3483
3484 let mut interior_or_upvar_span = None;
3485
3486 let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
3487 debug!(?from_awaited_ty);
3488
3489 if coroutine_did.is_local()
3491 && !coroutine_within_in_progress_typeck
3493 && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
3494 {
3495 debug!(?coroutine_info);
3496 'find_source: for (variant, source_info) in
3497 coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
3498 {
3499 debug!(?variant);
3500 for &local in variant {
3501 let decl = &coroutine_info.field_tys[local];
3502 debug!(?decl);
3503 if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
3504 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
3505 decl.source_info.span,
3506 Some((source_info.span, from_awaited_ty)),
3507 ));
3508 break 'find_source;
3509 }
3510 }
3511 }
3512 }
3513
3514 if interior_or_upvar_span.is_none() {
3515 interior_or_upvar_span =
3516 coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
3517 }
3518
3519 if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
3520 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
3521 }
3522
3523 debug!(?interior_or_upvar_span);
3524 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
3525 let is_async = self.tcx.coroutine_is_async(coroutine_did);
3526 self.note_obligation_cause_for_async_await(
3527 err,
3528 interior_or_upvar_span,
3529 is_async,
3530 outer_coroutine,
3531 trait_ref,
3532 target_ty,
3533 obligation,
3534 next_code,
3535 );
3536 true
3537 } else {
3538 false
3539 }
3540 }
3541
3542 {}
#[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("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3544u32),
::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_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let 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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3767",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3767u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("next_code")
}> =
::tracing::__macro_support::FieldName::new("next_code");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&next_code)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
self.note_obligation_cause_code(obligation.cause.body_def_id, err,
obligation.predicate, obligation.param_env,
next_code.unwrap(), &mut Vec::new(), &mut Default::default());
}
}
}#[instrument(level = "debug", skip_all)]
3545 fn note_obligation_cause_for_async_await(
3546 &self,
3547 err: &mut Diag<'_>,
3548 interior_or_upvar_span: CoroutineInteriorOrUpvar,
3549 is_async: bool,
3550 outer_coroutine: Option<DefId>,
3551 trait_pred: ty::TraitClause<'tcx>,
3552 target_ty: Ty<'tcx>,
3553 obligation: &PredicateObligation<'tcx>,
3554 next_code: Option<&ObligationCauseCode<'tcx>>,
3555 ) {
3556 let source_map = self.tcx.sess.source_map();
3557
3558 let (await_or_yield, an_await_or_yield) =
3559 if is_async { ("await", "an await") } else { ("yield", "a yield") };
3560 let future_or_coroutine = if is_async { "future" } else { "coroutine" };
3561
3562 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
3565 self.tcx.get_diagnostic_name(trait_pred.def_id())
3566 {
3567 let (trait_name, trait_verb) =
3568 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
3569
3570 err.code = None;
3571 err.primary_message(format!(
3572 "{future_or_coroutine} cannot be {trait_verb} between threads safely"
3573 ));
3574
3575 let original_span = err.span.primary_span().unwrap();
3576 let mut span = MultiSpan::from_span(original_span);
3577
3578 let message = outer_coroutine
3579 .and_then(|coroutine_did| {
3580 Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
3581 CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
3582 CoroutineKind::Desugared(
3583 CoroutineDesugaring::Async,
3584 CoroutineSource::Fn,
3585 ) => self
3586 .tcx
3587 .parent(coroutine_did)
3588 .as_local()
3589 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3590 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3591 .map(|name| {
3592 format!("future returned by `{name}` is not {trait_name}")
3593 })?,
3594 CoroutineKind::Desugared(
3595 CoroutineDesugaring::Async,
3596 CoroutineSource::Block,
3597 ) => {
3598 format!("future created by async block is not {trait_name}")
3599 }
3600 CoroutineKind::Desugared(
3601 CoroutineDesugaring::Async,
3602 CoroutineSource::Closure,
3603 ) => {
3604 format!("future created by async closure is not {trait_name}")
3605 }
3606 CoroutineKind::Desugared(
3607 CoroutineDesugaring::AsyncGen,
3608 CoroutineSource::Fn,
3609 ) => self
3610 .tcx
3611 .parent(coroutine_did)
3612 .as_local()
3613 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3614 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3615 .map(|name| {
3616 format!("async iterator returned by `{name}` is not {trait_name}")
3617 })?,
3618 CoroutineKind::Desugared(
3619 CoroutineDesugaring::AsyncGen,
3620 CoroutineSource::Block,
3621 ) => {
3622 format!("async iterator created by async gen block is not {trait_name}")
3623 }
3624 CoroutineKind::Desugared(
3625 CoroutineDesugaring::AsyncGen,
3626 CoroutineSource::Closure,
3627 ) => {
3628 format!(
3629 "async iterator created by async gen closure is not {trait_name}"
3630 )
3631 }
3632 CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
3633 self.tcx
3634 .parent(coroutine_did)
3635 .as_local()
3636 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
3637 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
3638 .map(|name| {
3639 format!("iterator returned by `{name}` is not {trait_name}")
3640 })?
3641 }
3642 CoroutineKind::Desugared(
3643 CoroutineDesugaring::Gen,
3644 CoroutineSource::Block,
3645 ) => {
3646 format!("iterator created by gen block is not {trait_name}")
3647 }
3648 CoroutineKind::Desugared(
3649 CoroutineDesugaring::Gen,
3650 CoroutineSource::Closure,
3651 ) => {
3652 format!("iterator created by gen closure is not {trait_name}")
3653 }
3654 })
3655 })
3656 .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
3657
3658 span.push_span_label(original_span, message);
3659 err.span(span);
3660
3661 format!("is not {trait_name}")
3662 } else {
3663 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
3664 };
3665
3666 let mut explain_yield = |interior_span: Span, yield_span: Span| {
3667 let mut span = MultiSpan::from_span(yield_span);
3668 let snippet = match source_map.span_to_snippet(interior_span) {
3669 Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
3672 _ => "the value".to_string(),
3673 };
3674 span.push_span_label(
3691 yield_span,
3692 format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
3693 );
3694 span.push_span_label(
3695 interior_span,
3696 format!("has type `{target_ty}` which {trait_explanation}"),
3697 );
3698 err.span_note(
3699 span,
3700 format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
3701 );
3702 };
3703 match interior_or_upvar_span {
3704 CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
3705 if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
3706 if let Some(await_span) = from_awaited_ty {
3707 let mut span = MultiSpan::from_span(await_span);
3709 span.push_span_label(
3710 await_span,
3711 format!(
3712 "await occurs here on type `{target_ty}`, which {trait_explanation}"
3713 ),
3714 );
3715 err.span_note(
3716 span,
3717 format!(
3718 "future {trait_explanation} as it awaits another future which {trait_explanation}"
3719 ),
3720 );
3721 } else {
3722 explain_yield(interior_span, yield_span);
3724 }
3725 }
3726 }
3727 CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
3728 let non_send = match target_ty.kind() {
3730 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
3731 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
3732 _ => None,
3733 },
3734 _ => None,
3735 };
3736
3737 let (span_label, span_note) = match non_send {
3738 Some((ref_ty, is_mut)) => {
3742 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
3743 let ref_kind = if is_mut { "&mut" } else { "&" };
3744 (
3745 format!(
3746 "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
3747 ),
3748 format!(
3749 "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
3750 ),
3751 )
3752 }
3753 None => (
3754 format!("has type `{target_ty}` which {trait_explanation}"),
3755 format!("captured value {trait_explanation}"),
3756 ),
3757 };
3758
3759 let mut span = MultiSpan::from_span(upvar_span);
3760 span.push_span_label(upvar_span, span_label);
3761 err.span_note(span, span_note);
3762 }
3763 }
3764
3765 debug!(?next_code);
3768 self.note_obligation_cause_code(
3769 obligation.cause.body_def_id,
3770 err,
3771 obligation.predicate,
3772 obligation.param_env,
3773 next_code.unwrap(),
3774 &mut Vec::new(),
3775 &mut Default::default(),
3776 );
3777 }
3778
3779 fn note_closure_capture(
3780 &self,
3781 err: &mut Diag<'_>,
3782 closure_def_id: DefId,
3783 upvar_args: ty::UpvarArgs<'tcx>,
3784 capture_ty: Option<Ty<'tcx>>,
3785 ) -> bool {
3786 let Some(closure_def_id) = closure_def_id.as_local() else {
3787 return false;
3788 };
3789 let Some(capture_ty) = capture_ty else {
3790 return false;
3791 };
3792
3793 let Some(typeck_results) = &self.typeck_results else {
3798 return false;
3799 };
3800 let typeck_root = self.tcx.typeck_root_def_id(closure_def_id.to_def_id());
3801 if typeck_results.hir_owner.to_def_id() != typeck_root {
3802 return false;
3803 }
3804
3805 let upvar_tys = match upvar_args.tupled_upvars_ty().kind() {
3808 ty::Tuple(args) => args,
3809 ty::Error(_) => ty::List::empty(),
3810 ty::Infer(_) => return false,
3811 ty => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unexpected upvar types tuple: {0:?}", ty)));
}unreachable!("unexpected upvar types tuple: {ty:?}"),
3812 };
3813
3814 let captures: Vec<_> =
3815 typeck_results.closure_min_captures_flattened(closure_def_id).collect();
3816 if captures.len() != upvar_tys.len() {
3817 return false;
3818 }
3819
3820 let capture_ty =
3821 self.tcx.erase_and_anonymize_regions(self.deeply_resolve_ignoring_regions(capture_ty));
3822 let Some(capture) = captures.iter().zip(upvar_tys).find_map(|(&capture, upvar_ty)| {
3823 let upvar_ty = self
3824 .tcx
3825 .erase_and_anonymize_regions(self.deeply_resolve_ignoring_regions(upvar_ty));
3826 (upvar_ty == capture_ty).then_some(capture)
3827 }) else {
3828 return false;
3829 };
3830
3831 err.span_note(
3832 capture.get_path_span(self.tcx),
3833 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required because `{0}` is used within this closure",
capture.to_string(self.tcx)))
})format!(
3834 "required because `{}` is used within this closure",
3835 capture.to_string(self.tcx)
3836 ),
3837 );
3838 true
3839 }
3840
3841 pub(crate) fn note_obligation_cause_code<T>(
3842 &self,
3843 body_def_id: LocalDefId,
3844 err: &mut Diag<'_>,
3845 predicate: T,
3846 param_env: ty::ParamEnv<'tcx>,
3847 cause_code: &ObligationCauseCode<'tcx>,
3848 obligated_types: &mut Vec<Ty<'tcx>>,
3849 seen_requirements: &mut FxHashSet<DefId>,
3850 ) where
3851 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3852 {
3853 let predicate = predicate.upcast(self.tcx);
3854 let mut closure_capture_ty =
3857 predicate.as_trait_clause().map(|trait_pred| trait_pred.skip_binder().self_ty());
3858 self.note_obligation_cause_code_inner(
3859 body_def_id,
3860 err,
3861 predicate,
3862 param_env,
3863 cause_code,
3864 obligated_types,
3865 seen_requirements,
3866 &mut closure_capture_ty,
3867 );
3868 }
3869
3870 fn note_obligation_cause_code_inner<T>(
3871 &self,
3872 body_def_id: LocalDefId,
3873 err: &mut Diag<'_>,
3874 predicate: T,
3875 param_env: ty::ParamEnv<'tcx>,
3876 cause_code: &ObligationCauseCode<'tcx>,
3877 obligated_types: &mut Vec<Ty<'tcx>>,
3878 seen_requirements: &mut FxHashSet<DefId>,
3879 closure_capture_ty: &mut Option<Ty<'tcx>>,
3880 ) where
3881 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
3882 {
3883 let tcx = self.tcx;
3884 let predicate = predicate.upcast(tcx);
3885 let suggest_remove_deref = |err: &mut Diag<'_>, expr: &hir::Expr<'_>| {
3886 if let Some(pred) = predicate.as_trait_clause()
3887 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3888 && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
3889 {
3890 err.span_suggestion_verbose(
3891 expr.span.until(inner.span),
3892 "references are always `Sized`, even if they point to unsized data; consider \
3893 not dereferencing the expression",
3894 String::new(),
3895 Applicability::MaybeIncorrect,
3896 );
3897 }
3898 };
3899
3900 match *cause_code {
3901 ObligationCauseCode::ExprAssignable
3902 | ObligationCauseCode::MatchExpressionArm { .. }
3903 | ObligationCauseCode::Pattern { .. }
3904 | ObligationCauseCode::IfExpression { .. }
3905 | ObligationCauseCode::IfExpressionWithNoElse
3906 | ObligationCauseCode::MainFunctionType
3907 | ObligationCauseCode::LangFunctionType(_)
3908 | ObligationCauseCode::IntrinsicType
3909 | ObligationCauseCode::MethodReceiver
3910 | ObligationCauseCode::ReturnNoExpression
3911 | ObligationCauseCode::Misc
3912 | ObligationCauseCode::WellFormed(..)
3913 | ObligationCauseCode::ReturnValue(_)
3914 | ObligationCauseCode::BlockTailExpression(..)
3915 | ObligationCauseCode::AwaitableExpr(_)
3916 | ObligationCauseCode::ForLoopIterator(_)
3917 | ObligationCauseCode::QuestionMark
3918 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
3919 | ObligationCauseCode::LetElse
3920 | ObligationCauseCode::UnOp { .. }
3921 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
3922 | ObligationCauseCode::AlwaysApplicableImpl
3923 | ObligationCauseCode::ConstParam(_)
3924 | ObligationCauseCode::ConstItemTy(_)
3925 | ObligationCauseCode::ReturnType
3926 | ObligationCauseCode::ReferenceOutlivesReferent(..)
3927 | ObligationCauseCode::ObjectTypeBound(..) => {}
3928 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. } => {
3929 if let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
3930 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
3931 && tcx.sess.source_map().lookup_char_pos(lhs.span.lo()).line
3932 != tcx.sess.source_map().lookup_char_pos(rhs.span.hi()).line
3933 {
3934 err.span_label(lhs.span, "");
3935 err.span_label(rhs.span, "");
3936 }
3937 }
3938 ObligationCauseCode::RustCall => {
3939 if let Some(pred) = predicate.as_trait_clause()
3940 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3941 {
3942 err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
3943 }
3944 }
3945 ObligationCauseCode::SliceOrArrayElem => {
3946 err.note("slice and array elements must have `Sized` type");
3947 }
3948 ObligationCauseCode::ArrayLen(array_ty, _) => {
3949 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`"));
3950 }
3951 ObligationCauseCode::TupleElem => {
3952 err.note("only the last element of a tuple may have a dynamically sized type");
3953 }
3954 ObligationCauseCode::DynCompatible(span) => {
3955 err.multipart_suggestion(
3956 "you might have meant to use `Self` to refer to the implementing type",
3957 ::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())],
3958 Applicability::MachineApplicable,
3959 );
3960 }
3961 ObligationCauseCode::WhereClause(item_def_id, span)
3962 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
3963 | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
3964 if !span.is_dummy() =>
3965 {
3966 if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
3967 if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
3968 && let hir::ExprKind::Call(_, args) = expr.kind
3969 && let Some(expr) = args.get(*pos)
3970 {
3971 suggest_remove_deref(err, &expr);
3972 } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
3973 && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
3974 && let Some(expr) = args.get(*pos)
3975 {
3976 suggest_remove_deref(err, &expr);
3977 }
3978 }
3979 let item_name = tcx.def_path_str(item_def_id);
3980 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));
3981 let mut multispan = MultiSpan::from(span);
3982 let sm = tcx.sess.source_map();
3983 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy =
3984 tcx.def_kind(item_def_id)
3985 {
3986 let span = tcx.def_span(tcx.parent(item_def_id)).shrink_to_lo();
3987 multispan.push_span_context(span);
3988 }
3989 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
3990 multispan.push_span_context(ident.span);
3991 }
3992 let mut a = "a";
3993 let mut this = "this bound";
3994 let mut note = None;
3995 let mut help = None;
3996 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
3997 match clause {
3998 ty::ClauseKind::Trait(trait_pred) => {
3999 let def_id = trait_pred.def_id();
4000 let visible_item = if let Some(local) = def_id.as_local() {
4001 let ty = trait_pred.self_ty();
4002 if let ty::Adt(adt, _) = ty.kind() {
4006 let visibilities = &tcx.resolutions(()).effective_visibilities;
4007 visibilities.effective_vis(local).is_none_or(|v| {
4008 v.at_level(Level::Reexported)
4009 .is_accessible_from(adt.did(), tcx)
4010 })
4011 } else {
4012 true
4014 }
4015 } else {
4016 tcx.visible_parent_map(()).get(&def_id).is_some()
4018 };
4019 if tcx.is_lang_item(def_id, LangItem::Sized) {
4020 if tcx
4022 .generics_of(item_def_id)
4023 .own_params
4024 .iter()
4025 .any(|param| tcx.def_span(param.def_id) == span)
4026 {
4027 a = "an implicit `Sized`";
4028 this =
4029 "the implicit `Sized` requirement on this type parameter";
4030 }
4031 if let Some(hir::Node::TraitItem(hir::TraitItem {
4032 generics,
4033 kind: hir::TraitItemKind::Type(bounds, None),
4034 ..
4035 })) = tcx.hir_get_if_local(item_def_id)
4036 && !bounds.iter()
4038 .filter_map(|bound| bound.trait_ref())
4039 .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
4040 && !generics.predicates.iter().any(|pred| {
4045 pred.kind.in_where_clause() && pred.span.contains(span)
4046 })
4047 {
4048 let (span, separator) = if let [.., last] = bounds {
4049 (last.span().shrink_to_hi(), " +")
4050 } else {
4051 (generics.span.shrink_to_hi(), ":")
4052 };
4053 err.span_suggestion_verbose(
4054 span,
4055 "consider relaxing the implicit `Sized` restriction",
4056 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ?Sized", separator))
})format!("{separator} ?Sized"),
4057 Applicability::MachineApplicable,
4058 );
4059 }
4060 }
4061 if let DefKind::Trait = tcx.def_kind(item_def_id)
4062 && !visible_item
4063 {
4064 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!(
4065 "`{short_item_name}` is a \"sealed trait\", because to implement it \
4066 you also need to implement `{}`, which is not accessible; this is \
4067 usually done to force you to use one of the provided types that \
4068 already implement it",
4069 with_no_trimmed_paths!(tcx.def_path_str(def_id)),
4070 ));
4071 let mut types = tcx
4072 .all_impls(def_id)
4073 .map(|t| {
4074 {
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!(
4075 " {}",
4076 tcx.type_of(t).instantiate_identity().skip_norm_wip(),
4077 ))
4078 })
4079 .collect::<Vec<_>>();
4080 if !types.is_empty() {
4081 let len = types.len();
4082 let post = if len > 9 {
4083 types.truncate(8);
4084 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
})format!("\nand {} others", len - 8)
4085 } else {
4086 String::new()
4087 };
4088 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!(
4089 "the following type{} implement{} the trait:\n{}{post}",
4090 pluralize!(len),
4091 if len == 1 { "s" } else { "" },
4092 types.join("\n"),
4093 ));
4094 }
4095 }
4096 }
4097 ty::ClauseKind::ConstArgHasType(..) => {
4098 let descr =
4099 ::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}`");
4100 if span.is_visible(sm) {
4101 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
short_item_name))
})format!(
4102 "required by this const generic parameter in `{short_item_name}`"
4103 );
4104 multispan.push_span_label(span, msg);
4105 err.span_note(multispan, descr);
4106 } else {
4107 err.span_note(tcx.def_span(item_def_id), descr);
4108 }
4109 return;
4110 }
4111 _ => (),
4112 }
4113 }
4114
4115 let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
4118 #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
4119 } else {
4120 false
4121 };
4122 if !is_in_fmt_lit {
4123 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}`");
4124 if span.is_visible(sm) {
4125 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}`");
4126 multispan.push_span_label(span, msg);
4127 err.span_note(multispan, descr);
4128 } else {
4129 err.span_note(tcx.def_span(item_def_id), descr);
4130 }
4131 }
4132 if let Some(note) = note {
4133 err.note(note);
4134 }
4135 if let Some(help) = help {
4136 err.help(help);
4137 }
4138 }
4139 ObligationCauseCode::WhereClause(..)
4140 | ObligationCauseCode::WhereClauseInExpr(..)
4141 | ObligationCauseCode::HostEffectInExpr(..) => {
4142 }
4145 ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
4146 err.span_note(span, "required by a bound in an opaque type");
4147 if let Some(definition_def_id) = definition_def_id
4148 && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
4152 {
4153 err.span_note(
4156 tcx.def_span(definition_def_id),
4157 "this definition site has more where clauses than the opaque type",
4158 );
4159 }
4160 }
4161 ObligationCauseCode::Coercion { source, target } => {
4162 let source = tcx
4163 .short_string(self.deeply_resolve_ignoring_regions(source), err.long_ty_path());
4164 let target = tcx
4165 .short_string(self.deeply_resolve_ignoring_regions(target), err.long_ty_path());
4166 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!(
4167 "required for the cast from `{source}` to `{target}`",
4168 )));
4169 }
4170 ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
4171 err.note(
4172 "the `Copy` trait is required because this value will be copied for each element of the array",
4173 );
4174 let sm = tcx.sess.source_map();
4175 if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
IsConstable::Fn | IsConstable::Ctor => true,
_ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
4176 && let Ok(_) = sm.span_to_snippet(elt_span)
4177 {
4178 err.multipart_suggestion(
4179 "create an inline `const` block",
4180 ::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![
4181 (elt_span.shrink_to_lo(), "const { ".to_string()),
4182 (elt_span.shrink_to_hi(), " }".to_string()),
4183 ],
4184 Applicability::MachineApplicable,
4185 );
4186 } else {
4187 err.help("consider using `core::array::from_fn` to initialize the array");
4189 err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
4190 }
4191 }
4192 ObligationCauseCode::VariableType(hir_id) => {
4193 if let Some(typeck_results) = &self.typeck_results
4194 && let Some(ty) = typeck_results.node_type_opt(hir_id)
4195 && let ty::Error(_) = ty.kind()
4196 {
4197 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!(
4198 "`{predicate}` isn't satisfied, but the type of this pattern is \
4199 `{{type error}}`",
4200 ));
4201 err.downgrade_to_delayed_bug();
4202 }
4203 let mut local = true;
4204 match tcx.parent_hir_node(hir_id) {
4205 Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
4206 err.span_suggestion_verbose(
4207 ty.span.shrink_to_lo(),
4208 "consider borrowing here",
4209 "&",
4210 Applicability::MachineApplicable,
4211 );
4212 }
4213 Node::LetStmt(hir::LetStmt {
4214 init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
4215 ..
4216 }) => {
4217 err.span_suggestion_verbose(
4221 span.shrink_to_lo(),
4222 "consider borrowing here",
4223 "&",
4224 Applicability::MachineApplicable,
4225 );
4226 }
4227 Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
4228 suggest_remove_deref(err, &expr);
4231 }
4232 Node::Param(param) => {
4233 err.span_suggestion_verbose(
4234 param.ty_span.shrink_to_lo(),
4235 "function arguments must have a statically known size, borrowed types \
4236 always have a known size",
4237 "&",
4238 Applicability::MachineApplicable,
4239 );
4240 local = false;
4241 }
4242 _ => {}
4243 }
4244 if local {
4245 err.note("all local variables must have a statically known size");
4246 }
4247 }
4248 ObligationCauseCode::SizedArgumentType(hir_id) => {
4249 let mut ty = None;
4250 let borrowed_msg = "function arguments must have a statically known size, borrowed \
4251 types always have a known size";
4252 if let Some(hir_id) = hir_id
4253 && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
4254 && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
4255 && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
4256 {
4257 ty = Some(t);
4265 } else if let Some(hir_id) = hir_id
4266 && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
4267 {
4268 ty = Some(t);
4269 }
4270 if let Some(ty) = ty {
4271 match ty.kind {
4272 hir::TyKind::TraitObject(traits, _) => {
4273 let (span, kw) = match traits {
4274 [first, ..] if first.span.lo() == ty.span.lo() => {
4275 (ty.span.shrink_to_lo(), "dyn ")
4277 }
4278 [first, ..] => (ty.span.until(first.span), ""),
4279 [] => ::rustc_span::macros::bug_impl(Some(ty.span),
format_args!("trait object with no traits: {0:?}", ty),
Location::caller())span_bug!(ty.span, "trait object with no traits: {ty:?}"),
4280 };
4281 let needs_parens = traits.len() != 1;
4282 if let Some(hir_id) = hir_id
4284 && #[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!(
4285 self.tcx.parent_hir_node(hir_id),
4286 hir::Node::Item(hir::Item {
4287 kind: hir::ItemKind::Fn { .. },
4288 ..
4289 })
4290 )
4291 {
4292 err.span_suggestion_verbose(
4293 span,
4294 "you can use `impl Trait` as the argument type",
4295 "impl ",
4296 Applicability::MaybeIncorrect,
4297 );
4298 }
4299 let sugg = if !needs_parens {
4300 ::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}"))]
4301 } else {
4302 ::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![
4303 (span.shrink_to_lo(), format!("&({kw}")),
4304 (ty.span.shrink_to_hi(), ")".to_string()),
4305 ]
4306 };
4307 err.multipart_suggestion(
4308 borrowed_msg,
4309 sugg,
4310 Applicability::MachineApplicable,
4311 );
4312 }
4313 hir::TyKind::Slice(_ty) => {
4314 err.span_suggestion_verbose(
4315 ty.span.shrink_to_lo(),
4316 "function arguments must have a statically known size, borrowed \
4317 slices always have a known size",
4318 "&",
4319 Applicability::MachineApplicable,
4320 );
4321 }
4322 hir::TyKind::Path(_) => {
4323 err.span_suggestion_verbose(
4324 ty.span.shrink_to_lo(),
4325 borrowed_msg,
4326 "&",
4327 Applicability::MachineApplicable,
4328 );
4329 }
4330 _ => {}
4331 }
4332 } else {
4333 err.note("all function arguments must have a statically known size");
4334 }
4335 if tcx.sess.opts.unstable_features.is_nightly_build()
4336 && !tcx.features().unsized_fn_params()
4337 {
4338 err.help("unsized fn params are gated as an unstable feature");
4339 }
4340 }
4341 ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType(_) => {
4342 err.note("the return type of a function must have a statically known size");
4343 }
4344 ObligationCauseCode::SizedYieldType => {
4345 err.note("the yield type of a coroutine must have a statically known size");
4346 }
4347 ObligationCauseCode::AssignmentLhsSized => {
4348 err.note("the left-hand-side of an assignment must have a statically known size");
4349 }
4350 ObligationCauseCode::TupleInitializerSized => {
4351 err.note("tuples must have a statically known size to be initialized");
4352 }
4353 ObligationCauseCode::StructInitializerSized => {
4354 err.note("structs must have a statically known size to be initialized");
4355 }
4356 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
4357 match *item {
4358 AdtKind::Struct => {
4359 if last {
4360 err.note(
4361 "the last field of a packed struct may only have a \
4362 dynamically sized type if it does not need drop to be run",
4363 );
4364 } else {
4365 err.note(
4366 "only the last field of a struct may have a dynamically sized type",
4367 );
4368 }
4369 }
4370 AdtKind::Union => {
4371 err.note("no field of a union may have a dynamically sized type");
4372 }
4373 AdtKind::Enum => {
4374 err.note("no field of an enum variant may have a dynamically sized type");
4375 }
4376 }
4377 err.help("change the field's type to have a statically known size");
4378 err.span_suggestion_verbose(
4379 span.shrink_to_lo(),
4380 "borrowed types always have a statically known size",
4381 "&",
4382 Applicability::MachineApplicable,
4383 );
4384 err.multipart_suggestion(
4385 "the `Box` type always has a statically known size and allocates its contents \
4386 in the heap",
4387 ::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![
4388 (span.shrink_to_lo(), "Box<".to_string()),
4389 (span.shrink_to_hi(), ">".to_string()),
4390 ],
4391 Applicability::MachineApplicable,
4392 );
4393 }
4394 ObligationCauseCode::SizedConstOrStatic => {
4395 err.note("statics and constants must have a statically known size");
4396 }
4397 ObligationCauseCode::InlineAsmSized => {
4398 err.note("all inline asm arguments must have a statically known size");
4399 }
4400 ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
4401 err.note(
4402 "all values captured by value by a closure must have a statically known size",
4403 );
4404 let hir::ExprKind::Closure(closure) =
4405 tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
4406 else {
4407 ::rustc_span::macros::bug_impl(None,
format_args!("expected closure in SizedClosureCapture obligation"),
Location::caller());bug!("expected closure in SizedClosureCapture obligation");
4408 };
4409 if let hir::CaptureBy::Value { .. } = closure.capture_clause
4410 && let Some(span) = closure.fn_arg_span
4411 {
4412 err.span_label(span, "this closure captures all values by move");
4413 }
4414 }
4415 ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
4416 let what = match tcx.coroutine_kind(coroutine_def_id) {
4417 None
4418 | Some(hir::CoroutineKind::Coroutine(_))
4419 | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
4420 "yield"
4421 }
4422 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
4423 "await"
4424 }
4425 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
4426 "yield`/`await"
4427 }
4428 };
4429 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
what))
})format!(
4430 "all values live across `{what}` must have a statically known size"
4431 ));
4432 }
4433 ObligationCauseCode::SharedStatic => {
4434 err.note("shared static variables must have a type that implements `Sync`");
4435 }
4436 ObligationCauseCode::MatchImpl(ref cause, _) => {
4437 self.note_obligation_cause_code_inner(
4438 body_def_id,
4439 err,
4440 predicate,
4441 param_env,
4442 &cause.code(),
4443 obligated_types,
4444 seen_requirements,
4445 closure_capture_ty,
4446 );
4447 }
4448 ObligationCauseCode::BuiltinDerived(ref data) => {
4449 let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4450 let ty = parent_trait_ref.skip_binder().self_ty();
4451 if parent_trait_ref.references_error() {
4452 err.downgrade_to_delayed_bug();
4455 return;
4456 }
4457
4458 let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
4461 false
4462 } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
4463 let parent_trait_ref =
4464 self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4465 let nested_ty = parent_trait_ref.skip_binder().self_ty();
4466 #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Coroutine(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
4467 || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Closure(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
4468 || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::CoroutineClosure(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::CoroutineClosure(..))
4469 } else {
4470 false
4471 };
4472
4473 let is_builtin_async_fn_trait =
4474 tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
4475
4476 if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
4477 let mut msg = || {
4478 let ty_str = tcx.short_string(ty, err.long_ty_path());
4479 ::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}`")
4480 };
4481 match *ty.kind() {
4482 ty::Adt(def, args) => {
4483 let msg = msg();
4484 match tcx.opt_item_ident(def.did()) {
4485 Some(ident) => {
4486 let mut spans = MultiSpan::new();
4487 if def.did().is_local()
4488 && let Some(pred) = predicate.as_trait_clause()
4489 {
4490 let field_ty = self.deeply_resolve_ignoring_regions(
4491 pred.skip_binder().self_ty(),
4492 );
4493 for field in def.all_fields() {
4494 if field.ty(tcx, args).skip_norm_wip() == field_ty {
4495 let sp = tcx.def_span(field.did);
4496 spans.push_primary_span(sp);
4497 spans.push_span_label(sp, "required by this field");
4498 }
4499 }
4500 }
4501 if spans.has_primary_spans() {
4502 spans.push_span_context(ident.span);
4503 } else {
4504 spans.push_primary_span(ident.span);
4505 spans.push_span_label(ident.span, "");
4506 }
4507 err.span_note(spans, msg);
4508 }
4509 None => {
4510 err.note(msg);
4511 }
4512 }
4513 }
4514 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
4515 let is_future = tcx.ty_is_opaque_future(ty);
4518 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:4518",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(4518u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligated_types")
}> =
::tracing::__macro_support::FieldName::new("obligated_types");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("is_future")
}> =
::tracing::__macro_support::FieldName::new("is_future");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("note_obligation_cause_code: check for async fn")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligated_types)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&is_future)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
4519 ?obligated_types,
4520 ?is_future,
4521 "note_obligation_cause_code: check for async fn"
4522 );
4523 if is_future
4524 && obligated_types.last().is_some_and(|ty| match ty.kind() {
4525 ty::Coroutine(last_def_id, ..) => {
4526 tcx.coroutine_is_async(*last_def_id)
4527 }
4528 _ => false,
4529 })
4530 {
4531 } else {
4533 let msg = msg();
4534 err.span_note(tcx.def_span(def_id), msg);
4535 }
4536 }
4537 ty::Coroutine(def_id, _) => {
4538 let sp = tcx.def_span(def_id);
4539
4540 let kind = tcx.coroutine_kind(def_id).unwrap();
4542 err.span_note(
4543 sp,
4544 {
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!(
4545 "required because it's used within this {kind:#}",
4546 )),
4547 );
4548 }
4549 ty::CoroutineWitness(..) => {
4550 }
4553 ty::Closure(def_id, args) => {
4554 if !self.note_closure_capture(
4555 err,
4556 def_id,
4557 ty::UpvarArgs::Closure(args),
4558 *closure_capture_ty,
4559 ) {
4560 err.span_note(
4561 tcx.def_span(def_id),
4562 "required because it's used within this closure",
4563 );
4564 }
4565 }
4566 ty::CoroutineClosure(def_id, args) => {
4567 if !self.note_closure_capture(
4568 err,
4569 def_id,
4570 ty::UpvarArgs::CoroutineClosure(args),
4571 *closure_capture_ty,
4572 ) {
4573 err.span_note(
4574 tcx.def_span(def_id),
4575 "required because it's used within this closure",
4576 );
4577 }
4578 }
4579 ty::Str => {
4580 err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
4581 }
4582 _ => {
4583 let msg = msg();
4584 err.note(msg);
4585 }
4586 };
4587 }
4588
4589 if !is_upvar_tys_infer_tuple {
4590 *closure_capture_ty = Some(ty);
4591 }
4592
4593 obligated_types.push(ty);
4594
4595 let parent_predicate = parent_trait_ref;
4596 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
4597 self.note_obligation_cause_code_inner(
4598 body_def_id,
4599 err,
4600 parent_predicate,
4601 param_env,
4602 &data.parent_code,
4603 obligated_types,
4604 seen_requirements,
4605 closure_capture_ty,
4606 );
4607 } else {
4608 self.note_obligation_cause_code_inner(
4609 body_def_id,
4610 err,
4611 parent_predicate,
4612 param_env,
4613 cause_code.peel_derives(),
4614 obligated_types,
4615 seen_requirements,
4616 closure_capture_ty,
4617 );
4618 }
4619 }
4620 ObligationCauseCode::ImplDerived(ref data) => {
4621 let mut parent_trait_pred =
4622 self.deeply_resolve_ignoring_regions(data.derived.parent_trait_pred);
4623 let parent_def_id = parent_trait_pred.def_id();
4624 if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
4625 && !tcx.features().enabled(sym::try_trait_v2)
4626 {
4627 return;
4631 }
4632 if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
4633 let parent_predicate =
4634 self.deeply_resolve_ignoring_regions(data.derived.parent_trait_pred);
4635
4636 *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4639 self.note_obligation_cause_code_inner(
4640 body_def_id,
4641 err,
4642 parent_predicate,
4643 param_env,
4644 &data.derived.parent_code,
4645 obligated_types,
4646 seen_requirements,
4647 closure_capture_ty,
4648 );
4649 return;
4650 }
4651 let self_ty_str =
4652 tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
4653 let trait_name = tcx.short_string(
4654 parent_trait_pred.print_modifiers_and_trait_path(),
4655 err.long_ty_path(),
4656 );
4657 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}`");
4658 let mut is_auto_trait = false;
4659 match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
4660 Some(Node::Item(hir::Item {
4661 kind: hir::ItemKind::Trait { is_auto, ident, .. },
4662 ..
4663 })) => {
4664 is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
hir::IsAuto::Yes => true,
_ => false,
}matches!(is_auto, hir::IsAuto::Yes);
4667 err.span_note(ident.span, msg);
4668 }
4669 Some(Node::Item(hir::Item {
4670 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
4671 ..
4672 })) => {
4673 let mut spans = Vec::with_capacity(2);
4674 if let Some(of_trait) = of_trait
4675 && !of_trait.trait_ref.path.span.in_derive_expansion()
4676 {
4677 spans.push(of_trait.trait_ref.path.span);
4678 }
4679 spans.push(self_ty.span);
4680 let mut spans: MultiSpan = spans.into();
4681 let mut derived = false;
4682 if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
{
ExpnKind::Macro(MacroKind::Derive, _) => true,
_ => false,
}matches!(
4683 self_ty.span.ctxt().outer_expn_data().kind,
4684 ExpnKind::Macro(MacroKind::Derive, _)
4685 ) || #[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!(
4686 of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
4687 Some(ExpnKind::Macro(MacroKind::Derive, _))
4688 ) {
4689 derived = true;
4690 spans.push_span_label(
4691 data.span,
4692 if data.span.in_derive_expansion() {
4693 ::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}`")
4694 } else {
4695 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied trait bound"))
})format!("unsatisfied trait bound")
4696 },
4697 );
4698 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
4699 if let Some(pred) = predicate.as_trait_clause()
4702 && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
4703 && self
4704 .tcx
4705 .generics_of(data.impl_or_alias_def_id)
4706 .own_params
4707 .iter()
4708 .any(|param| self.tcx.def_span(param.def_id) == data.span)
4709 {
4710 spans.push_span_label(
4711 data.span,
4712 "unsatisfied trait bound implicitly introduced here",
4713 );
4714 } else {
4715 spans.push_span_label(
4716 data.span,
4717 "unsatisfied trait bound introduced here",
4718 );
4719 }
4720 }
4721 err.span_note(spans, msg);
4722 if derived
4723 && self.is_truly_imperfect_derive(
4724 parent_trait_pred,
4725 predicate,
4726 param_env,
4727 )
4728 {
4729 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider manually implementing `{0}` to avoid undesired bounds caused by \"imperfect derives\"",
trait_name))
})format!(
4730 "consider manually implementing `{trait_name}` to avoid undesired bounds caused by \"imperfect derives\"",
4731 ));
4732 err.note(
4733 "to learn more, visit <https://github.com/rust-lang/rust/issues/26925>",
4734 );
4735 }
4736 point_at_assoc_type_restriction(
4737 tcx,
4738 err,
4739 &self_ty_str,
4740 &trait_name,
4741 predicate,
4742 &generics,
4743 &data,
4744 );
4745 }
4746 _ => {
4747 if !tcx.is_lang_item(parent_trait_pred.def_id(), LangItem::CoerceUnsized) {
4751 err.note(msg);
4752 }
4753 }
4754 };
4755
4756 let mut parent_predicate = parent_trait_pred;
4757 let mut data = &data.derived;
4758 let mut count = 0;
4759 seen_requirements.insert(parent_def_id);
4760 if is_auto_trait {
4761 while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
4764 let child_trait_ref =
4765 self.deeply_resolve_ignoring_regions(derived.parent_trait_pred);
4766 let child_def_id = child_trait_ref.def_id();
4767 if seen_requirements.insert(child_def_id) {
4768 break;
4769 }
4770 data = derived;
4771 parent_predicate = child_trait_ref.upcast(tcx);
4772 parent_trait_pred = child_trait_ref;
4773 }
4774 }
4775 while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
4776 let child_trait_pred =
4778 self.deeply_resolve_ignoring_regions(child.derived.parent_trait_pred);
4779 let child_def_id = child_trait_pred.def_id();
4780 if seen_requirements.insert(child_def_id) {
4781 break;
4782 }
4783 count += 1;
4784 data = &child.derived;
4785 parent_predicate = child_trait_pred.upcast(tcx);
4786 parent_trait_pred = child_trait_pred;
4787 }
4788 if count > 0 {
4789 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
count, if count == 1 { "" } else { "s" }))
})format!(
4790 "{} redundant requirement{} hidden",
4791 count,
4792 pluralize!(count)
4793 ));
4794 let self_ty = tcx.short_string(
4795 parent_trait_pred.skip_binder().self_ty(),
4796 err.long_ty_path(),
4797 );
4798 let trait_path = tcx.short_string(
4799 parent_trait_pred.print_modifiers_and_trait_path(),
4800 err.long_ty_path(),
4801 );
4802 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}`"));
4803 }
4804 *closure_capture_ty = Some(parent_trait_pred.skip_binder().self_ty());
4805 self.note_obligation_cause_code_inner(
4806 body_def_id,
4807 err,
4808 parent_predicate,
4809 param_env,
4810 &data.parent_code,
4811 obligated_types,
4812 seen_requirements,
4813 closure_capture_ty,
4814 )
4815 }
4816 ObligationCauseCode::ImplDerivedHost(ref data) => {
4817 let self_ty = tcx.short_string(
4818 self.deeply_resolve_ignoring_regions(data.derived.parent_host_clause.self_ty()),
4819 err.long_ty_path(),
4820 );
4821 let trait_path = tcx.short_string(
4822 data.derived
4823 .parent_host_clause
4824 .map_bound(|clause| clause.trait_ref)
4825 .print_only_trait_path(),
4826 err.long_ty_path(),
4827 );
4828 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for `{1}` to implement `{0} {2}`",
data.derived.parent_host_clause.skip_binder().constness,
self_ty, trait_path))
})format!(
4829 "required for `{self_ty}` to implement `{} {trait_path}`",
4830 data.derived.parent_host_clause.skip_binder().constness,
4831 );
4832 match tcx.hir_get_if_local(data.impl_def_id) {
4833 Some(Node::Item(hir::Item {
4834 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
4835 ..
4836 })) => {
4837 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];
4838 spans.extend(of_trait.map(|t| t.trait_ref.path.span));
4839 let mut spans: MultiSpan = spans.into();
4840 spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
4841 err.span_note(spans, msg);
4842 }
4843 _ => {
4844 err.note(msg);
4845 }
4846 }
4847
4848 self.note_obligation_cause_code_inner(
4849 body_def_id,
4850 err,
4851 data.derived.parent_host_clause,
4852 param_env,
4853 &data.derived.parent_code,
4854 obligated_types,
4855 seen_requirements,
4856 closure_capture_ty,
4857 );
4858 }
4859 ObligationCauseCode::BuiltinDerivedHost(ref data) => {
4860 self.note_obligation_cause_code_inner(
4861 body_def_id,
4862 err,
4863 data.parent_host_clause,
4864 param_env,
4865 &data.parent_code,
4866 obligated_types,
4867 seen_requirements,
4868 closure_capture_ty,
4869 );
4870 }
4871 ObligationCauseCode::WellFormedDerived(ref data) => {
4872 let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
4873 let parent_predicate = parent_trait_ref;
4874
4875 *closure_capture_ty = Some(parent_trait_ref.skip_binder().self_ty());
4876 self.note_obligation_cause_code_inner(
4877 body_def_id,
4878 err,
4879 parent_predicate,
4880 param_env,
4881 &data.parent_code,
4882 obligated_types,
4883 seen_requirements,
4884 closure_capture_ty,
4885 );
4886 }
4887 ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
4888 self.note_obligation_cause_code_inner(
4889 body_def_id,
4890 err,
4891 predicate,
4892 param_env,
4893 nested,
4894 obligated_types,
4895 seen_requirements,
4896 closure_capture_ty,
4897 );
4898 let mut multispan = MultiSpan::from(span);
4899 multispan.push_span_label(span, "required by this bound");
4900 err.span_note(
4901 multispan,
4902 ::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)),
4903 );
4904 }
4905 ObligationCauseCode::FunctionArg {
4906 arg_hir_id, call_hir_id, ref parent_code, ..
4907 } => {
4908 self.note_function_argument_obligation(
4909 body_def_id,
4910 err,
4911 arg_hir_id,
4912 parent_code,
4913 param_env,
4914 predicate,
4915 call_hir_id,
4916 );
4917
4918 self.note_obligation_cause_code_inner(
4919 body_def_id,
4920 err,
4921 predicate,
4922 param_env,
4923 parent_code,
4924 obligated_types,
4925 seen_requirements,
4926 closure_capture_ty,
4927 );
4928 }
4929 ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
4932 if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
4933 ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
4934 let item_name = tcx.item_name(trait_item_def_id);
4935 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!(
4936 "the requirement `{predicate}` appears on the `impl`'s {kind} \
4937 `{item_name}` but not on the corresponding trait's {kind}",
4938 );
4939 let sp = tcx
4940 .opt_item_ident(trait_item_def_id)
4941 .map(|i| i.span)
4942 .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
4943 let mut assoc_span: MultiSpan = sp.into();
4944 assoc_span.push_span_label(
4945 sp,
4946 ::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}`"),
4947 );
4948 if let Some(ident) = tcx
4949 .opt_associated_item(trait_item_def_id)
4950 .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
4951 {
4952 assoc_span.push_span_label(ident.span, "in this trait");
4953 }
4954 err.span_note(assoc_span, msg);
4955 }
4956 ObligationCauseCode::TrivialBound => {
4957 tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
4958 }
4959 ObligationCauseCode::OpaqueReturnType(expr_info) => {
4960 if let Some(typeck_results) = self.typeck_results.as_deref() {
4964 let chain_expr = match expr_info {
4965 Some((_, hir_id)) => Some(tcx.hir_expect_expr(hir_id)),
4966 None => tcx.hir_node_by_def_id(body_def_id).body_id().and_then(|body_id| {
4967 match tcx.hir_body(body_id).value.kind {
4968 hir::ExprKind::Block(block, _) => block.expr,
4969 _ => None,
4970 }
4971 }),
4972 };
4973 if let Some(chain_expr) = chain_expr {
4974 self.point_at_chain_in_return_position(
4975 body_def_id,
4976 chain_expr,
4977 typeck_results,
4978 param_env,
4979 err,
4980 );
4981 }
4982 }
4983 let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
4984 let expr = tcx.hir_expect_expr(hir_id);
4985 (expr_ty, expr)
4986 } else if let Some(body_id) = tcx.hir_node_by_def_id(body_def_id).body_id()
4987 && let body = tcx.hir_body(body_id)
4988 && let hir::ExprKind::Block(block, _) = body.value.kind
4989 && let Some(expr) = block.expr
4990 && let Some(expr_ty) = self
4991 .typeck_results
4992 .as_ref()
4993 .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
4994 && let Some(pred) = predicate.as_clause()
4995 && let Some(pred) = pred.as_trait_clause()
4996 && self
4997 .infcx
4998 .enter_forall(pred, |pred| self.can_eq(param_env, pred.self_ty(), expr_ty))
4999 {
5000 (expr_ty, expr)
5001 } else {
5002 return;
5003 };
5004 let expr_ty_string = tcx.short_string(expr_ty, err.long_ty_path());
5005 if expr_ty.is_never()
5006 && let span = expr.span.source_callsite()
5007 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span)
5008 && span != expr.span
5009 {
5010 err.span_suggestion(
5011 span,
5012 "`!` can be coerced to any type; consider casting it to a concrete type that implements the trait",
5013 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} as /* Type */", snippet))
})format!("{snippet} as /* Type */"),
5014 Applicability::HasPlaceholders,
5015 );
5016 }
5017 err.span_label(
5018 expr.span,
5019 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("return type was inferred to be `{0}` here",
expr_ty_string))
})
}with_forced_trimmed_paths!(format!(
5020 "return type was inferred to be `{expr_ty_string}` here",
5021 )),
5022 );
5023 suggest_remove_deref(err, &expr);
5024 }
5025 ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
5026 err.span_note(
5027 span,
5028 "unsized values must be place expressions and cannot be put in temporaries",
5029 );
5030 }
5031 ObligationCauseCode::CompareEii { .. } => {
5032 {
::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
5033 }
5034 }
5035 }
5036
5037 {}
#[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("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5037u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligation")
}> =
::tracing::__macro_support::FieldName::new("obligation");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_pred")
}> =
::tracing::__macro_support::FieldName::new("trait_pred");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_pred.self_ty")
}> =
::tracing::__macro_support::FieldName::new("trait_pred.self_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred.self_ty())
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let future_trait =
self.tcx.require_lang_item(LangItem::Future, span);
let self_ty =
self.deeply_resolve_ignoring_regions(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, ty::IsRigid::No, 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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5074",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5074u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("normalized_projection_type")
}> =
::tracing::__macro_support::FieldName::new("normalized_projection_type");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.deeply_resolve_ignoring_regions(projection_ty))
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5081",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5081u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("try_trait_obligation")
}> =
::tracing::__macro_support::FieldName::new("try_trait_obligation");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&try_obligation)
as &dyn ::tracing::field::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_def_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_def_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(
5038 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
5039 )]
5040 pub(super) fn suggest_await_before_try(
5041 &self,
5042 err: &mut Diag<'_>,
5043 obligation: &PredicateObligation<'tcx>,
5044 trait_pred: ty::PolyTraitClause<'tcx>,
5045 span: Span,
5046 ) {
5047 let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
5048
5049 let self_ty = self.deeply_resolve_ignoring_regions(trait_pred.self_ty());
5050 let impls_future = self.type_implements_trait(
5051 future_trait,
5052 [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
5053 obligation.param_env,
5054 );
5055 if !impls_future.must_apply_modulo_regions() {
5056 return;
5057 }
5058
5059 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
5060 let projection_ty = trait_pred.map_bound(|trait_pred| {
5062 Ty::new_projection(
5063 self.tcx,
5064 ty::IsRigid::No,
5065 item_def_id,
5066 [trait_pred.self_ty()],
5068 )
5069 });
5070 let InferOk { value: projection_ty, .. } = self
5071 .at(&obligation.cause, obligation.param_env)
5072 .normalize(Unnormalized::new_wip(projection_ty));
5073
5074 debug!(
5075 normalized_projection_type = ?self.deeply_resolve_ignoring_regions(projection_ty)
5076 );
5077 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
5078 obligation.param_env,
5079 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
5080 );
5081 debug!(try_trait_obligation = ?try_obligation);
5082 if self.predicate_may_hold(&try_obligation)
5083 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
5084 && snippet.ends_with('?')
5085 {
5086 match self.tcx.coroutine_kind(obligation.cause.body_def_id) {
5087 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
5088 err.span_suggestion_verbose(
5089 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
5090 "consider `await`ing on the `Future`",
5091 ".await",
5092 Applicability::MaybeIncorrect,
5093 );
5094 }
5095 _ => {
5096 let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
5097 span.push_span_label(
5098 self.tcx.def_span(obligation.cause.body_def_id),
5099 "this is not `async`",
5100 );
5101 err.span_note(
5102 span,
5103 "this implements `Future` and its output type supports \
5104 `?`, but the future cannot be awaited in a synchronous function",
5105 );
5106 }
5107 }
5108 }
5109 }
5110
5111 pub(super) fn suggest_floating_point_literal(
5112 &self,
5113 obligation: &PredicateObligation<'tcx>,
5114 err: &mut Diag<'_>,
5115 trait_pred: ty::PolyTraitClause<'tcx>,
5116 ) {
5117 let rhs_span = match obligation.cause.code() {
5118 ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
5119 _ => return,
5120 };
5121 if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
5122 && let ty::Infer(InferTy::IntVar(_)) =
5123 trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5124 {
5125 err.span_suggestion_verbose(
5126 rhs_span.shrink_to_hi(),
5127 "consider using a floating-point literal by writing it with `.0`",
5128 ".0",
5129 Applicability::MaybeIncorrect,
5130 );
5131 }
5132 }
5133
5134 pub fn can_suggest_derive(
5135 &self,
5136 obligation: &PredicateObligation<'tcx>,
5137 trait_pred: ty::PolyTraitClause<'tcx>,
5138 ) -> bool {
5139 if trait_pred.polarity() == ty::ClausePolarity::Negative {
5140 return false;
5141 }
5142 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5143 return false;
5144 };
5145 let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
5146 ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
5147 _ => return false,
5148 };
5149 if !self.tcx.def_span(adt.did()).can_be_used_for_suggestions() {
5150 return false;
5151 }
5152 let is_derivable_trait = match diagnostic_name {
5153 sym::Copy | sym::Clone => true,
5154 _ if adt.is_union() => false,
5155 sym::PartialEq | sym::PartialOrd => {
5156 let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
5157 trait_pred.skip_binder().self_ty() == rhs_ty
5158 }
5159 sym::Eq | sym::Ord | sym::Hash | sym::Debug | sym::Default => true,
5160 _ => false,
5161 };
5162 is_derivable_trait &&
5163 adt.all_fields().all(|field| {
5165 let field_ty = ty::GenericArg::from(field.ty(self.tcx, *args).skip_norm_wip());
5166 let trait_args = match diagnostic_name {
5167 sym::PartialEq | sym::PartialOrd => {
5168 Some(field_ty)
5169 }
5170 _ => None,
5171 };
5172 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitClause {
5173 trait_ref: ty::TraitRef::new(self.tcx,
5174 trait_pred.def_id(),
5175 [field_ty].into_iter().chain(trait_args),
5176 ),
5177 ..*tr
5178 });
5179 let field_obl = Obligation::new(
5180 self.tcx,
5181 obligation.cause.clone(),
5182 obligation.param_env,
5183 trait_pred,
5184 );
5185 self.predicate_must_hold_modulo_regions(&field_obl)
5186 })
5187 }
5188
5189 pub fn suggest_derive(
5190 &self,
5191 obligation: &PredicateObligation<'tcx>,
5192 err: &mut Diag<'_>,
5193 trait_pred: ty::PolyTraitClause<'tcx>,
5194 ) {
5195 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
5196 return;
5197 };
5198 let adt = match trait_pred.skip_binder().self_ty().kind() {
5199 ty::Adt(adt, _) if adt.did().is_local() => adt,
5200 _ => return,
5201 };
5202 if self.can_suggest_derive(obligation, trait_pred) {
5203 err.span_suggestion_verbose(
5204 self.tcx.def_span(adt.did()).shrink_to_lo(),
5205 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
trait_pred.skip_binder().self_ty(), diagnostic_name))
})format!(
5206 "consider annotating `{}` with `#[derive({})]`",
5207 trait_pred.skip_binder().self_ty(),
5208 diagnostic_name,
5209 ),
5210 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
diagnostic_name))
})format!("#[derive({diagnostic_name})]\n"),
5212 Applicability::MaybeIncorrect,
5213 );
5214 }
5215 }
5216
5217 pub(super) fn suggest_dereferencing_index(
5218 &self,
5219 obligation: &PredicateObligation<'tcx>,
5220 err: &mut Diag<'_>,
5221 trait_pred: ty::PolyTraitClause<'tcx>,
5222 ) {
5223 if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
5224 && self
5225 .tcx
5226 .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
5227 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5228 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
5229 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
5230 {
5231 let span = obligation.cause.span;
5234 if !span.from_expansion()
5235 && let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id)
5236 && let Some(expr) = {
5237 let mut finder = FindExprBySpan::new(span, self.tcx);
5238 finder.visit_expr(body.value);
5239 finder.result
5240 }
5241 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, borrowed) =
5242 expr.kind
5243 && let Some(amp_span) = borrowed
5244 .span
5245 .find_ancestor_inside_same_ctxt(expr.span)
5246 .map(|borrowed_span| expr.span.until(borrowed_span))
5247 && self
5248 .tcx
5249 .sess
5250 .source_map()
5251 .span_to_snippet(amp_span)
5252 .is_ok_and(|snippet| snippet.starts_with('&'))
5253 {
5254 err.span_suggestion_verbose(
5255 amp_span,
5256 "remove this reference",
5257 "",
5258 Applicability::MachineApplicable,
5259 );
5260 return;
5261 }
5262
5263 err.span_suggestion_verbose(
5264 obligation.cause.span.shrink_to_lo(),
5265 "dereference this index",
5266 '*',
5267 Applicability::MachineApplicable,
5268 );
5269 }
5270 }
5271
5272 fn note_function_argument_obligation(
5273 &self,
5274 body_def_id: LocalDefId,
5275 err: &mut Diag<'_>,
5276 arg_hir_id: HirId,
5277 parent_code: &ObligationCauseCode<'tcx>,
5278 param_env: ty::ParamEnv<'tcx>,
5279 failed_pred: ty::Predicate<'tcx>,
5280 call_hir_id: HirId,
5281 ) {
5282 let tcx = self.tcx;
5283 if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
5284 && let Some(typeck_results) = &self.typeck_results
5285 {
5286 if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
5287 && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
5288 && let Some(failed_pred) = failed_pred.as_trait_clause()
5289 && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
5290 && self.predicate_must_hold_modulo_regions(&Obligation::misc(
5291 tcx,
5292 expr.span,
5293 body_def_id,
5294 param_env,
5295 pred,
5296 ))
5297 && expr.span.hi() != rcvr.span.hi()
5298 {
5299 let should_sugg = match tcx.hir_node(call_hir_id) {
5300 Node::Expr(hir::Expr {
5301 kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
5302 ..
5303 }) if let Some((DefKind::AssocFn, did)) =
5304 typeck_results.type_dependent_def(call_hir_id)
5305 && call_receiver.hir_id == arg_hir_id =>
5306 {
5307 if tcx.inherent_impl_of_assoc(did).is_some() {
5311 Some(ty) == typeck_results.node_type_opt(arg_hir_id)
5313 } else {
5314 let trait_id = tcx
5316 .trait_of_assoc(did)
5317 .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
5318 let args = typeck_results.node_args(call_hir_id);
5319 let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
5320 .with_replaced_self_ty(tcx, ty);
5321 self.type_implements_trait(tr.def_id, tr.args, param_env)
5322 .must_apply_modulo_regions()
5323 }
5324 }
5325 _ => true,
5326 };
5327
5328 if should_sugg {
5329 err.span_suggestion_verbose(
5330 expr.span.with_lo(rcvr.span.hi()),
5331 ::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!(
5332 "consider removing this method call, as the receiver has type `{ty}` and \
5333 `{pred}` trivially holds",
5334 ),
5335 "",
5336 Applicability::MaybeIncorrect,
5337 );
5338 }
5339 }
5340 if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
5341 let inner_expr = expr.peel_blocks();
5342 let ty = typeck_results
5343 .expr_ty_adjusted_opt(inner_expr)
5344 .unwrap_or(Ty::new_misc_error(tcx));
5345 let span = inner_expr.span;
5346 if Some(span) != err.span.primary_span()
5347 && !span.in_external_macro(tcx.sess.source_map())
5348 {
5349 err.span_label(
5350 span,
5351 if ty.references_error() {
5352 String::new()
5353 } else {
5354 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5355 ::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}`")
5356 },
5357 );
5358 if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
5359 && let ty::ClauseKind::Trait(pred) = clause
5360 && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
5361 {
5362 if let [stmt, ..] = block.stmts
5363 && let hir::StmtKind::Semi(value) = stmt.kind
5364 && let hir::ExprKind::Closure(hir::Closure {
5365 body, fn_decl_span, ..
5366 }) = value.kind
5367 && let body = tcx.hir_body(*body)
5368 && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
5369 {
5370 err.multipart_suggestion(
5373 "you might have meant to open the closure body instead of placing \
5374 a closure within a block",
5375 ::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![
5376 (expr.span.with_hi(value.span.lo()), String::new()),
5377 (fn_decl_span.shrink_to_hi(), " {".to_string()),
5378 ],
5379 Applicability::MaybeIncorrect,
5380 );
5381 } else {
5382 err.span_suggestion_verbose(
5384 expr.span.shrink_to_lo(),
5385 "you might have meant to create the closure instead of a block",
5386 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}| ",
(0..pred.trait_ref.args.len() -
1).map(|_| "_").collect::<Vec<_>>().join(", ")))
})format!(
5387 "|{}| ",
5388 (0..pred.trait_ref.args.len() - 1)
5389 .map(|_| "_")
5390 .collect::<Vec<_>>()
5391 .join(", ")
5392 ),
5393 Applicability::MaybeIncorrect,
5394 );
5395 }
5396 }
5397 }
5398 }
5399
5400 let mut type_diffs = ::alloc::vec::Vec::new()vec![];
5405 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = *parent_code
5406 && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
5407 && let where_clauses = self.tcx.clauses_of(def_id).instantiate(self.tcx, node_args)
5408 && let Some(where_pred) = where_clauses.clauses.get(idx)
5409 {
5410 let where_pred = where_pred.as_ref().skip_norm_wip();
5411 if let Some(where_pred) = where_pred.as_trait_clause()
5412 && let Some(failed_pred) = failed_pred.as_trait_clause()
5413 && where_pred.def_id() == failed_pred.def_id()
5414 {
5415 self.enter_forall(where_pred, |where_pred| {
5416 let failed_pred = self.instantiate_binder_with_fresh_vars(
5417 expr.span,
5418 BoundRegionConversionTime::FnCall,
5419 failed_pred,
5420 );
5421
5422 let zipped =
5423 iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
5424 for (expected, actual) in zipped {
5425 self.probe(|_| {
5426 match self
5427 .eq_raw(
5430 &ObligationCause::misc(expr.span, body_def_id),
5431 param_env,
5432 DefineOpaqueTypes::Yes,
5433 expected,
5434 actual,
5435 ) {
5436 Ok(_) => (), Err(err) => type_diffs.push(err),
5438 }
5439 })
5440 }
5441 })
5442 } else if let Some(where_pred) = where_pred.as_projection_clause()
5443 && let Some(failed_pred) = failed_pred.as_projection_clause()
5444 && let Some(found) =
5445 failed_pred.map_bound(|pred| pred.term.as_type()).transpose().map(|term| {
5446 self.instantiate_binder_with_fresh_vars(
5447 expr.span,
5448 BoundRegionConversionTime::FnCall,
5449 term,
5450 )
5451 })
5452 {
5453 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: self.instantiate_binder_with_fresh_vars(expr.span,
BoundRegionConversionTime::FnCall,
where_pred.map_bound(|pred|
pred.projection_term)).expect_ty().to_ty(self.tcx,
ty::IsRigid::No),
found,
})]))vec![TypeError::Sorts(ty::error::ExpectedFound {
5454 expected: self
5455 .instantiate_binder_with_fresh_vars(
5456 expr.span,
5457 BoundRegionConversionTime::FnCall,
5458 where_pred.map_bound(|pred| pred.projection_term),
5459 )
5460 .expect_ty()
5461 .to_ty(self.tcx, ty::IsRigid::No),
5462 found,
5463 })];
5464 }
5465 }
5466 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5467 && let hir::Path { res: Res::Local(hir_id), .. } = path
5468 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5469 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
5470 && let Some(binding_expr) = local.init
5471 {
5472 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
5476 } else {
5477 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
5478 }
5479 }
5480 let call_node = tcx.hir_node(call_hir_id);
5481 if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
5482 call_node
5483 {
5484 if Some(rcvr.span) == err.span.primary_span() {
5485 err.replace_span_with(path.ident.span, true);
5486 }
5487 }
5488
5489 if let Node::Expr(expr) = call_node {
5490 if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
5491 | hir::ExprKind::MethodCall(
5492 hir::PathSegment { ident: Ident { span, .. }, .. },
5493 ..,
5494 ) = expr.kind
5495 {
5496 if Some(*span) != err.span.primary_span() {
5497 let msg = if span.is_desugaring(DesugaringKind::FormatLiteral {
5498 is_source_literal_for_diagnostics_only: true,
5499 }) {
5500 "required by this formatting parameter"
5501 } else if span.is_desugaring(DesugaringKind::FormatLiteral {
5502 is_source_literal_for_diagnostics_only: false,
5503 }) {
5504 "required by a formatting parameter in this expression"
5505 } else {
5506 "required by a bound introduced by this call"
5507 };
5508 err.span_label(*span, msg);
5509 }
5510 }
5511
5512 if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
5513 self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
5514 }
5515 }
5516 }
5517
5518 fn suggest_option_method_if_applicable(
5519 &self,
5520 failed_pred: ty::Predicate<'tcx>,
5521 param_env: ty::ParamEnv<'tcx>,
5522 err: &mut Diag<'_>,
5523 expr: &hir::Expr<'_>,
5524 ) {
5525 let tcx = self.tcx;
5526 let infcx = self.infcx;
5527 let Some(typeck_results) = self.typeck_results.as_ref() else { return };
5528
5529 let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
5531 return;
5532 };
5533 if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
5534 return;
5535 }
5536
5537 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause { trait_ref, .. }))
5540 = failed_pred.kind().skip_binder()
5541 && tcx.is_fn_trait(trait_ref.def_id)
5542 && let [self_ty, found_ty] = trait_ref.args.as_slice()
5543 && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
5544 && let fn_sig = fn_ty.fn_sig(tcx).skip_binder()
5545 && fn_sig.is_fn_trait_compatible()
5547
5548 && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
5550 && !target_ty.has_escaping_bound_vars()
5551
5552 && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
5554 && let &[found_ty] = tys.as_slice()
5555 && !found_ty.has_escaping_bound_vars()
5556
5557 && let Some(deref_target_did) = tcx.lang_items().deref_target()
5559 && let projection = Ty::new_projection_from_args(tcx,ty::IsRigid::No, deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
5560 && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(projection))
5561 && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
5562 && infcx.can_eq(param_env, deref_target, target_ty)
5563 {
5564 let help = if let hir::Mutability::Mut = needs_mut
5565 && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
5566 && infcx
5567 .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
5568 .must_apply_modulo_regions()
5569 {
5570 Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
5571 } else if let hir::Mutability::Not = needs_mut {
5572 Some(("call `Option::as_deref()` first", ".as_deref()"))
5573 } else {
5574 None
5575 };
5576
5577 if let Some((msg, sugg)) = help {
5578 err.span_suggestion_with_style(
5579 expr.span.shrink_to_hi(),
5580 msg,
5581 sugg,
5582 Applicability::MaybeIncorrect,
5583 SuggestionStyle::ShowAlways,
5584 );
5585 }
5586 }
5587 }
5588
5589 fn look_for_iterator_item_mistakes(
5590 &self,
5591 assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
5592 typeck_results: &TypeckResults<'tcx>,
5593 type_diffs: &[TypeError<'tcx>],
5594 param_env: ty::ParamEnv<'tcx>,
5595 path_segment: &hir::PathSegment<'_>,
5596 args: &[hir::Expr<'_>],
5597 prev_ty: Ty<'_>,
5598 err: &mut Diag<'_>,
5599 ) {
5600 let tcx = self.tcx;
5601 for entry in assocs_in_this_method {
5604 let Some((_span, (def_id, ty))) = entry else {
5605 continue;
5606 };
5607 for diff in type_diffs {
5608 let TypeError::Sorts(expected_found) = diff else {
5609 continue;
5610 };
5611 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5612 && path_segment.ident.name == sym::iter
5613 && self.can_eq(
5614 param_env,
5615 Ty::new_ref(
5616 tcx,
5617 tcx.lifetimes.re_erased,
5618 expected_found.found,
5619 ty::Mutability::Not,
5620 ),
5621 *ty,
5622 )
5623 && let [] = args
5624 {
5625 err.span_suggestion_verbose(
5627 path_segment.ident.span,
5628 ::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`"),
5629 "into_iter".to_string(),
5630 Applicability::MachineApplicable,
5631 );
5632 }
5633 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
5634 && path_segment.ident.name == sym::into_iter
5635 && self.can_eq(
5636 param_env,
5637 expected_found.found,
5638 Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
5639 )
5640 && let [] = args
5641 {
5642 err.span_suggestion_verbose(
5644 path_segment.ident.span,
5645 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
prev_ty))
})format!(
5646 "consider not consuming the `{prev_ty}` to construct the `Iterator`"
5647 ),
5648 "iter".to_string(),
5649 Applicability::MachineApplicable,
5650 );
5651 }
5652 if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
5653 && path_segment.ident.name == sym::map
5654 && self.can_eq(param_env, expected_found.found, *ty)
5655 && let [arg] = args
5656 && let hir::ExprKind::Closure(closure) = arg.kind
5657 {
5658 let body = tcx.hir_body(closure.body);
5659 if let hir::ExprKind::Block(block, None) = body.value.kind
5660 && let None = block.expr
5661 && let [.., stmt] = block.stmts
5662 && let hir::StmtKind::Semi(expr) = stmt.kind
5663 && expected_found.found.is_unit()
5667 && expr.span.hi() != stmt.span.hi()
5672 {
5673 err.span_suggestion_verbose(
5674 expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
5675 "consider removing this semicolon",
5676 String::new(),
5677 Applicability::MachineApplicable,
5678 );
5679 }
5680 let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
5681 && let Some(expr) = block.expr
5682 {
5683 expr
5684 } else {
5685 body.value
5686 };
5687 if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
5688 && path_segment.ident.name == sym::clone
5689 && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
5690 && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
5691 && self.can_eq(param_env, expr_ty, rcvr_ty)
5692 && let ty::Ref(_, ty, _) = expr_ty.kind()
5693 {
5694 err.span_label(
5695 span,
5696 ::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!(
5697 "this method call is cloning the reference `{expr_ty}`, not \
5698 `{ty}` which doesn't implement `Clone`",
5699 ),
5700 );
5701 let ty::Param(..) = ty.kind() else {
5702 continue;
5703 };
5704 let node =
5705 tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
5706
5707 let pred = ty::Binder::dummy(ty::TraitClause {
5708 trait_ref: ty::TraitRef::new(
5709 tcx,
5710 tcx.require_lang_item(LangItem::Clone, span),
5711 [*ty],
5712 ),
5713 polarity: ty::ClausePolarity::Positive,
5714 });
5715 let Some(generics) = node.generics() else {
5716 continue;
5717 };
5718 let Some(body_id) = node.body_id() else {
5719 continue;
5720 };
5721 suggest_restriction(
5722 tcx,
5723 tcx.hir_body_owner_def_id(body_id),
5724 generics,
5725 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
})format!("type parameter `{ty}`"),
5726 err,
5727 node.fn_sig(),
5728 None,
5729 pred,
5730 None,
5731 );
5732 }
5733 }
5734 }
5735 }
5736 }
5737
5738 fn point_at_chain(
5739 &self,
5740 expr: &hir::Expr<'_>,
5741 typeck_results: &TypeckResults<'tcx>,
5742 type_diffs: Vec<TypeError<'tcx>>,
5743 param_env: ty::ParamEnv<'tcx>,
5744 err: &mut Diag<'_>,
5745 ) {
5746 let mut primary_spans = ::alloc::vec::Vec::new()vec![];
5747 let mut span_labels = ::alloc::vec::Vec::new()vec![];
5748
5749 let tcx = self.tcx;
5750
5751 let mut print_root_expr = true;
5752 let mut assocs = ::alloc::vec::Vec::new()vec![];
5753 let mut expr = expr;
5754 let mut prev_ty = self.deeply_resolve_ignoring_regions(
5755 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5756 );
5757 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
5758 expr = rcvr_expr;
5762 let assocs_in_this_method =
5763 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
5764 prev_ty = self.deeply_resolve_ignoring_regions(
5765 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
5766 );
5767 self.look_for_iterator_item_mistakes(
5768 &assocs_in_this_method,
5769 typeck_results,
5770 &type_diffs,
5771 param_env,
5772 path_segment,
5773 args,
5774 prev_ty,
5775 err,
5776 );
5777 assocs.push(assocs_in_this_method);
5778
5779 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
5780 && let hir::Path { res: Res::Local(hir_id), .. } = path
5781 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
5782 {
5783 let parent = self.tcx.parent_hir_node(binding.hir_id);
5784 if let hir::Node::LetStmt(local) = parent
5786 && let Some(binding_expr) = local.init
5787 {
5788 expr = binding_expr;
5790 }
5791 if let hir::Node::Param(param) = parent {
5792 let prev_ty = self.deeply_resolve_ignoring_regions(
5794 typeck_results
5795 .node_type_opt(param.hir_id)
5796 .unwrap_or(Ty::new_misc_error(tcx)),
5797 );
5798 let assocs_in_this_method = self.probe_assoc_types_at_expr(
5799 &type_diffs,
5800 param.ty_span,
5801 prev_ty,
5802 param.hir_id,
5803 param_env,
5804 );
5805 if assocs_in_this_method.iter().any(|a| a.is_some()) {
5806 assocs.push(assocs_in_this_method);
5807 print_root_expr = false;
5808 }
5809 break;
5810 }
5811 }
5812 }
5813 if let Some(ty) = typeck_results.expr_ty_opt(expr)
5816 && print_root_expr
5817 {
5818 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5819 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}`")));
5823 };
5824 let mut assocs = assocs.into_iter().peekable();
5827 while let Some(assocs_in_method) = assocs.next() {
5828 let Some(prev_assoc_in_method) = assocs.peek() else {
5829 for entry in assocs_in_method {
5830 let Some((span, (assoc, ty))) = entry else {
5831 continue;
5832 };
5833 if primary_spans.is_empty()
5834 || type_diffs.iter().any(|diff| {
5835 let TypeError::Sorts(expected_found) = diff else {
5836 return false;
5837 };
5838 self.can_eq(param_env, expected_found.found, ty)
5839 })
5840 {
5841 primary_spans.push(span);
5847 }
5848 span_labels.push((
5849 span,
5850 {
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!(
5851 "`{}` is `{ty}` here",
5852 self.tcx.def_path_str(assoc),
5853 )),
5854 ));
5855 }
5856 break;
5857 };
5858 for (entry, prev_entry) in
5859 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
5860 {
5861 match (entry, prev_entry) {
5862 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
5863 let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
5864
5865 let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
5866 if !self.can_eq(param_env, ty, *prev_ty) {
5867 if type_diffs.iter().any(|diff| {
5868 let TypeError::Sorts(expected_found) = diff else {
5869 return false;
5870 };
5871 self.can_eq(param_env, expected_found.found, ty)
5872 }) {
5873 primary_spans.push(span);
5874 }
5875 span_labels
5876 .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")));
5877 } else {
5878 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")));
5879 }
5880 }
5881 (Some((span, (assoc, ty))), None) => {
5882 span_labels.push((
5883 span,
5884 {
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!(
5885 "`{}` is `{}` here",
5886 self.tcx.def_path_str(assoc),
5887 self.ty_to_string(ty),
5888 )),
5889 ));
5890 }
5891 (None, Some(_)) | (None, None) => {}
5892 }
5893 }
5894 }
5895 if !primary_spans.is_empty() {
5896 let mut multi_span: MultiSpan = primary_spans.into();
5897 for (span, label) in span_labels {
5898 multi_span.push_span_label(span, label);
5899 }
5900 err.span_note(
5901 multi_span,
5902 "the method call chain might not have had the expected associated types",
5903 );
5904 }
5905 }
5906
5907 fn probe_assoc_types_at_expr(
5908 &self,
5909 type_diffs: &[TypeError<'tcx>],
5910 span: Span,
5911 prev_ty: Ty<'tcx>,
5912 body_id: HirId,
5913 param_env: ty::ParamEnv<'tcx>,
5914 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
5915 let ocx = ObligationCtxt::new(self.infcx);
5916 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
5917 for diff in type_diffs {
5918 let TypeError::Sorts(expected_found) = diff else {
5919 continue;
5920 };
5921 let &ty::Alias(_, ty::AliasTy { kind: kind @ ty::Projection { def_id }, .. }) =
5922 expected_found.expected.kind()
5923 else {
5924 continue;
5925 };
5926
5927 let args = GenericArgs::for_item(self.tcx, def_id, |param, _| {
5931 if param.index == 0 {
5932 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 { .. });
5933 return prev_ty.into();
5934 }
5935 self.var_for_def(span, param)
5936 });
5937 let ty = self.infcx.next_ty_var(span);
5941 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
5943 ty::ClauseKind::Projection(ty::ProjectionClause {
5944 projection_term: ty::AliasTerm::new_from_args(self.tcx, kind.into(), args),
5945 term: ty.into(),
5946 }),
5947 ));
5948 let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
5949 ocx.register_obligation(Obligation::misc(
5951 self.tcx,
5952 span,
5953 body_def_id,
5954 param_env,
5955 projection,
5956 ));
5957 if ocx.try_evaluate_obligations().no_errors()
5958 && let ty = self.deeply_resolve_ignoring_regions(ty)
5959 && !ty.is_ty_var()
5960 {
5961 assocs_in_this_method.push(Some((span, (def_id, ty))));
5962 } else {
5963 assocs_in_this_method.push(None);
5968 }
5969 }
5970 assocs_in_this_method
5971 }
5972
5973 pub fn point_at_chain_in_return_position(
5988 &self,
5989 body_def_id: LocalDefId,
5990 expr: &hir::Expr<'_>,
5991 typeck_results: &TypeckResults<'tcx>,
5992 param_env: ty::ParamEnv<'tcx>,
5993 err: &mut Diag<'_>,
5994 ) {
5995 let tcx = self.tcx;
5996 if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(body_def_id) {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(tcx.def_kind(body_def_id), DefKind::Fn | DefKind::AssocFn) {
5997 return;
5998 }
5999
6000 let binder = tcx.fn_sig(body_def_id).instantiate_identity().skip_norm_wip().output();
6001 self.enter_forall(binder, |output| {
6002 let &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: opaque_def_id }, args, .. }) =
6003 output.kind()
6004 else {
6005 return;
6006 };
6007
6008 let mut probe_diffs = ::alloc::vec::Vec::new()vec![];
6013 for clause in tcx.item_bounds(opaque_def_id).instantiate(tcx, args).skip_norm_wip() {
6014 let Some(proj) = clause.as_projection_clause() else { continue };
6015 let proj = self.instantiate_binder_with_fresh_vars(
6016 expr.span,
6017 BoundRegionConversionTime::FnCall,
6018 proj,
6019 );
6020 let Some(expected_term) = proj.term.as_type() else { continue };
6021 probe_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
6025 expected: proj.projection_term.expect_ty().to_ty(tcx, ty::IsRigid::No),
6026 found: expected_term,
6027 }));
6028 }
6029 if probe_diffs.is_empty() {
6030 return;
6031 }
6032
6033 let expr = if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
6035 && let hir::Path { res: Res::Local(hir_id), .. } = path
6036 && let hir::Node::Pat(binding) = tcx.hir_node(*hir_id)
6037 && let hir::Node::LetStmt(local) = tcx.parent_hir_node(binding.hir_id)
6038 && let Some(binding_expr) = local.init
6039 {
6040 binding_expr
6041 } else {
6042 expr
6043 };
6044
6045 let expr_ty = self.deeply_resolve_ignoring_regions(
6048 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
6049 );
6050 let assocs = self.probe_assoc_types_at_expr(
6051 &probe_diffs,
6052 expr.span,
6053 expr_ty,
6054 expr.hir_id,
6055 param_env,
6056 );
6057 let mut type_diffs = ::alloc::vec::Vec::new()vec![];
6058 for (probe_diff, assoc) in iter::zip(probe_diffs, assocs) {
6059 let TypeError::Sorts(ty::error::ExpectedFound { expected, found: expected_term }) =
6060 probe_diff
6061 else {
6062 continue;
6063 };
6064 let Some((_, (_, actual_ty))) = assoc else { continue };
6065 if !self.can_eq(param_env, expected_term, actual_ty) {
6066 type_diffs.push(TypeError::Sorts(ty::error::ExpectedFound {
6067 expected,
6068 found: actual_ty,
6069 }));
6070 }
6071 }
6072 if !type_diffs.is_empty() {
6073 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
6074 }
6075 });
6076 }
6077
6078 pub(super) fn suggest_convert_to_slice(
6082 &self,
6083 err: &mut Diag<'_>,
6084 obligation: &PredicateObligation<'tcx>,
6085 trait_pred: ty::PolyTraitClause<'tcx>,
6086 candidate_impls: &[ImplCandidate<'tcx>],
6087 span: Span,
6088 ) {
6089 if span.in_external_macro(self.tcx.sess.source_map()) {
6090 return;
6091 }
6092 let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
6095 obligation.cause.code()
6096 else {
6097 return;
6098 };
6099
6100 let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
6105 ty::Array(element_ty, _) => (element_ty, None),
6106
6107 ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
6108 ty::Array(element_ty, _) => (element_ty, Some(mutability)),
6109 _ => return,
6110 },
6111
6112 _ => return,
6113 };
6114
6115 let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
6118 ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
6119 if let ty::Slice(e) = *t.kind()
6120 && e == element_ty
6121 && m == mutability.unwrap_or(m)
6122 {
6123 mutability = Some(m);
6125 true
6126 } else {
6127 false
6128 }
6129 }
6130 _ => false,
6131 };
6132
6133 if let Some(slice_ty) = candidate_impls
6135 .iter()
6136 .map(|trait_ref| trait_ref.trait_ref.self_ty())
6137 .find(|t| is_slice(*t))
6138 {
6139 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");
6140
6141 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
6142 let mut suggestions = ::alloc::vec::Vec::new()vec![];
6143 if snippet.starts_with('&') {
6144 } else if let Some(hir::Mutability::Mut) = mutability {
6145 suggestions.push((span.shrink_to_lo(), "&mut ".into()));
6146 } else {
6147 suggestions.push((span.shrink_to_lo(), "&".into()));
6148 }
6149 suggestions.push((span.shrink_to_hi(), "[..]".into()));
6150 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
6151 } else {
6152 err.span_help(span, msg);
6153 }
6154 }
6155 }
6156
6157 pub(super) fn suggest_tuple_wrapping(
6162 &self,
6163 err: &mut Diag<'_>,
6164 root_obligation: &PredicateObligation<'tcx>,
6165 obligation: &PredicateObligation<'tcx>,
6166 ) {
6167 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
6168 return;
6169 };
6170
6171 let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
6172
6173 let trait_ref = root_pred.map_bound(|root_pred| {
6174 root_pred.trait_ref.with_replaced_self_ty(
6175 self.tcx,
6176 Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
6177 )
6178 });
6179
6180 let obligation =
6181 Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
6182
6183 if self.predicate_must_hold_modulo_regions(&obligation) {
6184 let arg_span = self.tcx.hir_span(*arg_hir_id);
6185 err.multipart_suggestion(
6186 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use a unary tuple instead"))
})format!("use a unary tuple instead"),
6187 ::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())],
6188 Applicability::MaybeIncorrect,
6189 );
6190 }
6191 }
6192
6193 pub(super) fn suggest_shadowed_inherent_method(
6194 &self,
6195 err: &mut Diag<'_>,
6196 obligation: &PredicateObligation<'tcx>,
6197 trait_predicate: ty::PolyTraitClause<'tcx>,
6198 ) {
6199 let ObligationCauseCode::FunctionArg { call_hir_id, .. } = obligation.cause.code() else {
6200 return;
6201 };
6202 let Node::Expr(call) = self.tcx.hir_node(*call_hir_id) else { return };
6203 let hir::ExprKind::MethodCall(segment, rcvr, args, ..) = call.kind else { return };
6204 let Some(typeck) = &self.typeck_results else { return };
6205 let Some(rcvr_ty) = typeck.expr_ty_adjusted_opt(rcvr) else { return };
6206 let rcvr_ty = self.deeply_resolve_ignoring_regions(rcvr_ty);
6207 let autoderef = (self.autoderef_steps)(rcvr_ty);
6208 for (ty, def_id) in autoderef.iter().filter_map(|(ty, obligations)| {
6209 if let ty::Adt(def, _) = ty.kind()
6210 && *ty != rcvr_ty.peel_refs()
6211 && obligations.iter().all(|obligation| self.predicate_may_hold(obligation))
6212 {
6213 Some((ty, def.did()))
6214 } else {
6215 None
6216 }
6217 }) {
6218 for impl_def_id in self.tcx.inherent_impls(def_id) {
6219 if *impl_def_id == trait_predicate.def_id() {
6220 continue;
6221 }
6222 for m in self
6223 .tcx
6224 .provided_trait_methods(*impl_def_id)
6225 .filter(|m| m.name() == segment.ident.name)
6226 {
6227 let fn_sig = self.tcx.fn_sig(m.def_id);
6228 if fn_sig.skip_binder().inputs().skip_binder().len() != args.len() + 1 {
6229 continue;
6230 }
6231 let rcvr_ty = fn_sig.skip_binder().input(0).skip_binder();
6232 let (mutability, _ty) = match rcvr_ty.kind() {
6233 ty::Ref(_, ty, hir::Mutability::Mut) => ("&mut ", ty),
6234 ty::Ref(_, ty, _) => ("&", ty),
6235 _ => ("", &rcvr_ty),
6236 };
6237 let path = self.tcx.def_path_str(def_id);
6238 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!(
6239 "there's an inherent method on `{ty}` of the same name, which can be \
6240 auto-dereferenced from `{rcvr_ty}`"
6241 ));
6242 err.multipart_suggestion(
6243 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to access the inherent method on `{0}`, use the fully-qualified path",
ty))
})format!(
6244 "to access the inherent method on `{ty}`, use the fully-qualified path",
6245 ),
6246 ::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![
6247 (
6248 call.span.until(rcvr.span),
6249 format!("{path}::{}({}", m.name(), mutability),
6250 ),
6251 match &args {
6252 [] => (
6253 rcvr.span.shrink_to_hi().with_hi(call.span.hi()),
6254 ")".to_string(),
6255 ),
6256 [first, ..] => (rcvr.span.between(first.span), ", ".to_string()),
6257 },
6258 ],
6259 Applicability::MaybeIncorrect,
6260 );
6261 }
6262 }
6263 }
6264 }
6265
6266 pub(super) fn explain_hrtb_projection(
6267 &self,
6268 diag: &mut Diag<'_>,
6269 pred: ty::PolyTraitClause<'tcx>,
6270 param_env: ty::ParamEnv<'tcx>,
6271 cause: &ObligationCause<'tcx>,
6272 ) {
6273 if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
6274 {
6275 self.probe(|_| {
6276 let ocx = ObligationCtxt::new(self);
6277 ocx.register_obligation(Obligation::new(
6278 self.tcx,
6279 ObligationCause::dummy(),
6280 param_env,
6281 pred,
6282 ));
6283 if !ocx.try_evaluate_obligations().no_errors() {
6284 return;
6286 }
6287
6288 if let ObligationCauseCode::FunctionArg {
6289 call_hir_id,
6290 arg_hir_id,
6291 parent_code: _,
6292 } = cause.code()
6293 {
6294 let arg_span = self.tcx.hir_span(*arg_hir_id);
6295 let mut sp: MultiSpan = arg_span.into();
6296
6297 sp.push_span_label(
6298 arg_span,
6299 "the trait solver is unable to infer the \
6300 generic types that should be inferred from this argument",
6301 );
6302 sp.push_span_label(
6303 self.tcx.hir_span(*call_hir_id),
6304 "add turbofish arguments to this call to \
6305 specify the types manually, even if it's redundant",
6306 );
6307 diag.span_note(
6308 sp,
6309 "this is a known limitation of the trait solver that \
6310 will be lifted in the future",
6311 );
6312 } else {
6313 let mut sp: MultiSpan = cause.span.into();
6314 sp.push_span_label(
6315 cause.span,
6316 "try adding turbofish arguments to this expression to \
6317 specify the types manually, even if it's redundant",
6318 );
6319 diag.span_note(
6320 sp,
6321 "this is a known limitation of the trait solver that \
6322 will be lifted in the future",
6323 );
6324 }
6325 });
6326 }
6327 }
6328
6329 pub(super) fn suggest_desugaring_async_fn_in_trait(
6330 &self,
6331 err: &mut Diag<'_>,
6332 trait_pred: ty::PolyTraitClause<'tcx>,
6333 ) {
6334 if self.tcx.features().return_type_notation() {
6336 return;
6337 }
6338
6339 let trait_def_id = trait_pred.def_id();
6340
6341 if !self.tcx.trait_is_auto(trait_def_id) {
6343 return;
6344 }
6345
6346 let ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, .. }) =
6348 trait_pred.self_ty().skip_binder().kind()
6349 else {
6350 return;
6351 };
6352 let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
6353 self.tcx.opt_rpitit_info(*def_id)
6354 else {
6355 return;
6356 };
6357
6358 let auto_trait = self.tcx.def_path_str(trait_def_id);
6359 let Some(fn_def_id) = fn_def_id.as_local() else {
6361 if self.tcx.asyncness(fn_def_id).is_async() {
6363 let mut span: MultiSpan = self.tcx.def_span(fn_def_id).into();
6364 span.push_span_context(self.tcx.def_span(self.tcx.parent(fn_def_id)));
6365 err.span_note(
6366 span,
6367 ::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!(
6368 "`{}::{}` is an `async fn` in trait, which does not \
6369 automatically imply that its future is `{auto_trait}`",
6370 alias_ty.trait_ref(self.tcx),
6371 self.tcx.item_name(fn_def_id)
6372 ),
6373 );
6374 }
6375 return;
6376 };
6377 let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
6378 return;
6379 };
6380
6381 let (sig, body) = item.expect_fn();
6383 let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
6384 sig.decl.output
6385 else {
6386 return;
6388 };
6389
6390 if opaq_def.def_id.to_def_id() != opaque_def_id {
6393 return;
6394 }
6395
6396 let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
6397 self.tcx,
6398 *sig,
6399 *body,
6400 opaque_def_id.expect_local(),
6401 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}", auto_trait))
})format!(" + {auto_trait}"),
6402 ) else {
6403 return;
6404 };
6405
6406 let function_name = self.tcx.def_path_str(fn_def_id);
6407 err.multipart_suggestion(
6408 ::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!(
6409 "`{auto_trait}` can be made part of the associated future's \
6410 guarantees for all implementations of `{function_name}`"
6411 ),
6412 sugg,
6413 Applicability::MachineApplicable,
6414 );
6415 }
6416
6417 pub fn ty_kind_suggestion(
6418 &self,
6419 param_env: ty::ParamEnv<'tcx>,
6420 ty: Ty<'tcx>,
6421 ) -> Option<String> {
6422 let tcx = self.infcx.tcx;
6423 let implements_default = |ty| {
6424 let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
6425 return false;
6426 };
6427 self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
6428 };
6429
6430 Some(match *ty.kind() {
6431 ty::Never | ty::Error(_) => return None,
6432 ty::Bool => "false".to_string(),
6433 ty::Char => "\'x\'".to_string(),
6434 ty::Int(_) | ty::Uint(_) => "42".into(),
6435 ty::Float(_) => "3.14159".into(),
6436 ty::Slice(_) => "[]".to_string(),
6437 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
6438 "vec![]".to_string()
6439 }
6440 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => {
6441 "String::new()".to_string()
6442 }
6443 ty::Adt(def, args) if def.is_box() => {
6444 ::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())?)
6445 }
6446 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
6447 "None".to_string()
6448 }
6449 ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
6450 ::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())?)
6451 }
6452 ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
6453 ty::Ref(_, ty, mutability) => {
6454 if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
6455 "\"\"".to_string()
6456 } else {
6457 let ty = self.ty_kind_suggestion(param_env, ty)?;
6458 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
ty))
})format!("&{}{ty}", mutability.prefix_str())
6459 }
6460 }
6461 ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
6462 if len == 0 {
6463 "[]".to_string()
6464 } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
6465 ::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)
6467 } else {
6468 "/* value */".to_string()
6469 }
6470 }
6471 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!(
6472 "({}{})",
6473 tys.iter()
6474 .map(|ty| self.ty_kind_suggestion(param_env, ty))
6475 .collect::<Option<Vec<String>>>()?
6476 .join(", "),
6477 if tys.len() == 1 { "," } else { "" }
6478 ),
6479 _ => "/* value */".to_string(),
6480 })
6481 }
6482
6483 pub(super) fn suggest_add_result_as_return_type(
6487 &self,
6488 obligation: &PredicateObligation<'tcx>,
6489 err: &mut Diag<'_>,
6490 trait_pred: ty::PolyTraitClause<'tcx>,
6491 ) {
6492 if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
6493 return;
6494 }
6495
6496 fn choose_suggest_items<'tcx, 'hir>(
6503 tcx: TyCtxt<'tcx>,
6504 node: hir::Node<'hir>,
6505 ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
6506 match node {
6507 hir::Node::Item(item)
6508 if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
6509 {
6510 Some((sig.decl, body_id))
6511 }
6512 hir::Node::ImplItem(item)
6513 if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
6514 {
6515 let parent = tcx.parent_hir_node(item.hir_id());
6516 if let hir::Node::Item(item) = parent
6517 && let hir::ItemKind::Impl(imp) = item.kind
6518 && imp.of_trait.is_none()
6519 {
6520 return Some((sig.decl, body_id));
6521 }
6522 None
6523 }
6524 _ => None,
6525 }
6526 }
6527
6528 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_def_id);
6529 if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
6530 && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
6531 && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
6532 && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
6533 && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
6534 && self.tcx.is_diagnostic_item(sym::Result, def.did())
6535 {
6536 let mut sugg_spans =
6537 ::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())];
6538 let body = self.tcx.hir_body(body_id);
6539 if let hir::ExprKind::Block(b, _) = body.value.kind
6540 && b.expr.is_none()
6541 {
6542 let span = self.tcx.sess.source_map().end_point(b.span);
6544 sugg_spans.push((
6545 span.shrink_to_lo(),
6546 ::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!(
6547 "{}{}",
6548 " Ok(())\n",
6549 self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
6550 ),
6551 ));
6552 }
6553 err.multipart_suggestion(
6554 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding return type"))
})format!("consider adding return type"),
6555 sugg_spans,
6556 Applicability::MaybeIncorrect,
6557 );
6558 }
6559 }
6560
6561 {}
#[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("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6561u32),
::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_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let 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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6581",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6581u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pred")
}> =
::tracing::__macro_support::FieldName::new("pred");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_def_id")
}> =
::tracing::__macro_support::FieldName::new("item_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pred)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6594",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6594u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("generics.params")
}> =
::tracing::__macro_support::FieldName::new("generics.params");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics.params)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6595",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6595u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("generics.predicates")
}> =
::tracing::__macro_support::FieldName::new("generics.predicates");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics.predicates)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let Some(param) =
generics.params.iter().find(|param|
param.span == span) 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 /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:6608",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(6608u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param")
}> =
::tracing::__macro_support::FieldName::new("param");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m)
as &dyn ::tracing::field::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)]
6562 pub(super) fn suggest_unsized_bound_if_applicable(
6563 &self,
6564 err: &mut Diag<'_>,
6565 obligation: &PredicateObligation<'tcx>,
6566 ) {
6567 let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
6568 obligation.predicate.kind().skip_binder()
6569 else {
6570 return;
6571 };
6572 let (ObligationCauseCode::WhereClause(item_def_id, span)
6573 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
6574 *obligation.cause.code().peel_derives()
6575 else {
6576 return;
6577 };
6578 if span.is_dummy() {
6579 return;
6580 }
6581 debug!(?pred, ?item_def_id, ?span);
6582
6583 let (Some(node), true) = (
6584 self.tcx.hir_get_if_local(item_def_id),
6585 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
6586 ) else {
6587 return;
6588 };
6589
6590 let Some(generics) = node.generics() else {
6591 return;
6592 };
6593 let sized_trait = self.tcx.lang_items().sized_trait();
6594 debug!(?generics.params);
6595 debug!(?generics.predicates);
6596 let Some(param) = generics.params.iter().find(|param| param.span == span) else {
6597 return;
6598 };
6599 let explicitly_sized = generics
6602 .bounds_for_param(param.def_id)
6603 .flat_map(|bp| bp.bounds)
6604 .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
6605 if explicitly_sized {
6606 return;
6607 }
6608 debug!(?param);
6609 match node {
6610 hir::Node::Item(
6611 item @ hir::Item {
6612 kind:
6614 hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
6615 ..
6616 },
6617 ) => {
6618 if self.suggest_indirection_for_unsized(err, item, param) {
6619 return;
6620 }
6621 }
6622 _ => {}
6623 };
6624
6625 let (span, separator, open_paren_sp) =
6627 if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
6628 (s, " +", open_paren_sp)
6629 } else {
6630 (param.name.ident().span.shrink_to_hi(), ":", None)
6631 };
6632
6633 let mut suggs = vec![];
6634 let suggestion = format!("{separator} ?Sized");
6635
6636 if let Some(open_paren_sp) = open_paren_sp {
6637 suggs.push((open_paren_sp, "(".to_string()));
6638 suggs.push((span, format!("){suggestion}")));
6639 } else {
6640 suggs.push((span, suggestion));
6641 }
6642
6643 err.multipart_suggestion(
6644 "consider relaxing the implicit `Sized` restriction",
6645 suggs,
6646 Applicability::MachineApplicable,
6647 );
6648 }
6649
6650 fn suggest_indirection_for_unsized(
6651 &self,
6652 err: &mut Diag<'_>,
6653 item: &hir::Item<'tcx>,
6654 param: &hir::GenericParam<'tcx>,
6655 ) -> bool {
6656 let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
6660 visitor.visit_item(item);
6661 if visitor.invalid_spans.is_empty() {
6662 return false;
6663 }
6664 let mut multispan: MultiSpan = param.span.into();
6665 multispan.push_span_label(
6666 param.span,
6667 ::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()),
6668 );
6669 for sp in visitor.invalid_spans {
6670 multispan.push_span_label(
6671 sp,
6672 ::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()),
6673 );
6674 }
6675 err.span_help(
6676 multispan,
6677 ::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!(
6678 "you could relax the implicit `Sized` bound on `{T}` if it were \
6679 used through indirection like `&{T}` or `Box<{T}>`",
6680 T = param.name.ident(),
6681 ),
6682 );
6683 true
6684 }
6685 pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
6686 &self,
6687 err: &mut Diag<'_>,
6688 predicate: T,
6689 param_env: ty::ParamEnv<'tcx>,
6690 cause_code: &ObligationCauseCode<'tcx>,
6691 ) where
6692 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
6693 {
6694 let tcx = self.tcx;
6695 let predicate = predicate.upcast(tcx);
6696 match *cause_code {
6697 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
6698 if let Some(typeck_results) = &self.typeck_results
6699 && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
6700 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
6701 && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
6702 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
6703 {
6704 if let Some(pred) = predicate.as_trait_clause()
6705 && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
6706 && self
6707 .infcx
6708 .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
6709 .must_apply_modulo_regions()
6710 {
6711 let lhs_span = tcx.hir_span(lhs_hir_id);
6712 let sm = tcx.sess.source_map();
6713 if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
6714 && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
6715 {
6716 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}>`"));
6717 err.multipart_suggestion(
6718 "consider swapping the equality",
6719 ::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)],
6720 Applicability::MaybeIncorrect,
6721 );
6722 }
6723 }
6724 }
6725 _ => {}
6726 }
6727 }
6728
6729 fn is_truly_imperfect_derive(
6732 &self,
6733 parent_trait_pred: ty::PolyTraitClause<'tcx>,
6734 predicate: ty::Predicate<'tcx>,
6735 param_env: ty::ParamEnv<'tcx>,
6736 ) -> bool {
6737 let tcx = self.tcx;
6738 let ty::Adt(adt_def, parent_args) = parent_trait_pred.skip_binder().self_ty().kind() else {
6739 return false;
6740 };
6741 let Some(trait_clause) = predicate.as_trait_clause() else {
6742 return false;
6743 };
6744 let failing_ty = trait_clause.skip_binder().self_ty();
6745 let trait_def_id = parent_trait_pred.def_id();
6746
6747 let failing_adt_param_indices: FxHashSet<u32> = parent_args
6748 .iter()
6749 .enumerate()
6750 .filter_map(|(idx, arg)| {
6751 if let Some(t) = arg.as_type()
6752 && t == failing_ty
6753 {
6754 Some(idx as u32)
6755 } else {
6756 None
6757 }
6758 })
6759 .collect();
6760
6761 if failing_adt_param_indices.is_empty() {
6762 return false;
6763 }
6764
6765 adt_def.all_fields().all(|field| {
6766 let raw_field_ty = tcx.type_of(field.did).skip_binder();
6767 if let ty::Param(p) = raw_field_ty.kind()
6769 && failing_adt_param_indices.contains(&p.index)
6770 {
6771 return false;
6772 }
6773 if !raw_field_ty.walk().any(|arg| {
6775 #[allow(non_exhaustive_omitted_patterns)] match arg.as_type().map(|t|
t.kind()) {
Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index) =>
true,
_ => false,
}matches!(arg.as_type().map(|t| t.kind()), Some(ty::Param(p)) if failing_adt_param_indices.contains(&p.index))
6776 }) {
6777 return true;
6778 }
6779
6780 self.probe(|_| {
6781 let fresh_args = ty::GenericArgs::for_item(tcx, adt_def.did(), |param, _| {
6784 if failing_adt_param_indices.contains(¶m.index) {
6785 self.var_for_def(DUMMY_SP, param)
6786 } else {
6787 parent_args[param.index as usize]
6788 }
6789 });
6790
6791 let field_ty = field.ty(tcx, fresh_args).skip_norm_wip();
6792 let parent_trait_args = parent_trait_pred.skip_binder().trait_ref.args;
6795 let trait_args = parent_trait_args.iter().map(|arg| {
6796 if arg.as_type() == Some(parent_trait_pred.skip_binder().self_ty()) {
6797 field_ty.into()
6798 } else {
6799 arg
6800 }
6801 });
6802 let obligation = Obligation::new(
6803 tcx,
6804 ObligationCause::dummy(),
6805 param_env,
6806 parent_trait_pred.rebind(ty::TraitRef::new(tcx, trait_def_id, trait_args)),
6807 );
6808 self.predicate_may_hold(&obligation)
6809 })
6810 })
6811 }
6812}
6813
6814fn hint_missing_borrow<'tcx>(
6816 infcx: &InferCtxt<'tcx>,
6817 param_env: ty::ParamEnv<'tcx>,
6818 span: Span,
6819 found: Ty<'tcx>,
6820 expected: Ty<'tcx>,
6821 found_node: Node<'_>,
6822 err: &mut Diag<'_>,
6823) {
6824 if #[allow(non_exhaustive_omitted_patterns)] match found_node {
Node::TraitItem(..) => true,
_ => false,
}matches!(found_node, Node::TraitItem(..)) {
6825 return;
6826 }
6827
6828 let found_args = match found.kind() {
6829 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6830 kind => {
6831 ::rustc_span::macros::bug_impl(Some(span),
format_args!("found was converted to a FnPtr above but is now {0:?}",
kind), Location::caller())span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
6832 }
6833 };
6834 let expected_args = match expected.kind() {
6835 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
6836 kind => {
6837 ::rustc_span::macros::bug_impl(Some(span),
format_args!("expected was converted to a FnPtr above but is now {0:?}",
kind), Location::caller())span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
6838 }
6839 };
6840
6841 let Some(fn_decl) = found_node.fn_decl() else {
6843 return;
6844 };
6845
6846 let args = fn_decl.inputs.iter();
6847
6848 let mut to_borrow = Vec::new();
6849 let mut remove_borrow = Vec::new();
6850
6851 for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
6852 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
6853 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
6854
6855 if infcx.can_eq(param_env, found_ty, expected_ty) {
6856 if found_refs.len() < expected_refs.len()
6858 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
6859 {
6860 to_borrow.push((
6861 arg.span.shrink_to_lo(),
6862 expected_refs[..expected_refs.len() - found_refs.len()]
6863 .iter()
6864 .map(|mutbl| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()))
6865 .collect::<Vec<_>>()
6866 .join(""),
6867 ));
6868 } else if found_refs.len() > expected_refs.len() {
6869 let mut span = arg.span.shrink_to_lo();
6870 let mut left = found_refs.len() - expected_refs.len();
6871 let mut ty = arg;
6872 while let hir::TyKind::Ref(_, inner_ty, _) = &ty.kind
6873 && left > 0
6874 {
6875 span = span.with_hi(inner_ty.span.lo());
6876 ty = inner_ty;
6877 left -= 1;
6878 }
6879 if left == 0 {
6880 remove_borrow.push((span, String::new()));
6881 }
6882 }
6883 }
6884 }
6885
6886 if !to_borrow.is_empty() {
6887 err.subdiagnostic(diagnostics::AdjustSignatureBorrow::Borrow { to_borrow });
6888 }
6889
6890 if !remove_borrow.is_empty() {
6891 err.subdiagnostic(diagnostics::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
6892 }
6893}
6894
6895#[derive(#[automatically_derived]impl<'v> ::core::fmt::Debug for SelfVisitor<'v> {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SelfVisitor paths name", &self.paths, &&self.name)
}
}Debug)]
6898pub struct SelfVisitor<'v> {
6899 pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
6900 pub name: Option<Symbol>,
6901}
6902
6903impl<'v> Visitor<'v> for SelfVisitor<'v> {
6904 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
6905 if let hir::TyKind::Path(path) = ty.kind
6906 && let hir::QPath::TypeRelative(inner_ty, segment) = path
6907 && (Some(segment.ident.name) == self.name || self.name.is_none())
6908 && let hir::TyKind::Path(inner_path) = inner_ty.kind
6909 && let hir::QPath::Resolved(None, inner_path) = inner_path
6910 && let Res::SelfTyAlias { .. } = inner_path.res
6911 {
6912 self.paths.push(ty.as_unambig_ty());
6913 }
6914 hir::intravisit::walk_ty(self, ty);
6915 }
6916}
6917
6918#[derive(#[automatically_derived]impl<'v> ::core::default::Default for
ReturnsVisitor<'v> {
#[inline]
fn default() -> Self {
ReturnsVisitor {
returns: ::core::default::Default::default(),
break_targets_in_tail_position: ::core::default::Default::default(),
}
}
}Default)]
6921pub struct ReturnsVisitor<'v> {
6922 pub returns: Vec<&'v hir::Expr<'v>>,
6923 break_targets_in_tail_position: FxHashSet<HirId>,
6926}
6927
6928impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
6929 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
6930 match ex.kind {
6931 hir::ExprKind::Ret(Some(val)) => self.returns.push(val),
6932 hir::ExprKind::Break(dest, Some(val)) if let Ok(id) = dest.target_id => {
6933 if self.break_targets_in_tail_position.contains(&id) {
6935 self.returns.push(val)
6936 }
6937 }
6938 hir::ExprKind::Become(_) => {
6939 }
6942 _ => {}
6943 }
6944
6945 hir::intravisit::walk_expr(self, ex);
6947 }
6948
6949 fn visit_body(&mut self, body: &hir::Body<'v>) {
6950 self.visit_tail(body.value);
6951 }
6952}
6953
6954impl<'v> ReturnsVisitor<'v> {
6955 fn visit_tail(&mut self, ex: &'v hir::Expr<'v>) {
6956 match ex.kind {
6957 hir::ExprKind::Block(block, _) => {
6958 if block.targeted_by_break {
6959 self.break_targets_in_tail_position.insert(block.hir_id);
6960 }
6961 for stmt in block.stmts {
6962 hir::intravisit::walk_stmt(self, stmt);
6963 }
6964 if let Some(tail) = block.expr {
6965 self.visit_tail(tail);
6966 }
6967 }
6968 hir::ExprKind::If(cond, then, els) => {
6969 self.visit_expr(cond);
6970 self.visit_tail(then);
6971 if let Some(els) = els {
6972 self.visit_tail(els);
6973 }
6974 }
6975 hir::ExprKind::Match(scrutinee, arms, _) => {
6976 self.visit_expr(scrutinee);
6977 for arm in arms {
6978 if let Some(guard) = arm.guard {
6979 self.visit_expr(guard);
6980 }
6981 self.visit_tail(arm.body);
6982 }
6983 }
6984 hir::ExprKind::Loop(block, ..) => {
6985 self.break_targets_in_tail_position.insert(ex.hir_id);
6986 self.visit_block(block);
6987 }
6988 hir::ExprKind::Ret(_) | hir::ExprKind::Become(_) | hir::ExprKind::Break(..) => {
6989 self.visit_expr(ex);
6990 }
6991 _ => {
6992 self.returns.push(ex);
6993 self.visit_expr(ex);
6994 }
6995 }
6996 }
6997}
6998
6999#[derive(#[automatically_derived]impl ::core::default::Default for AwaitsVisitor {
#[inline]
fn default() -> Self {
AwaitsVisitor { awaits: ::core::default::Default::default() }
}
}Default)]
7001struct AwaitsVisitor {
7002 awaits: Vec<HirId>,
7003}
7004
7005impl<'v> Visitor<'v> for AwaitsVisitor {
7006 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
7007 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
7008 self.awaits.push(id)
7009 }
7010 hir::intravisit::walk_expr(self, ex)
7011 }
7012}
7013
7014pub trait NextTypeParamName {
7018 fn next_type_param_name(&self, name: Option<&str>) -> String;
7019}
7020
7021impl NextTypeParamName for &[hir::GenericParam<'_>] {
7022 fn next_type_param_name(&self, name: Option<&str>) -> String {
7023 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
7025 let name = name.as_deref();
7026
7027 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
7029
7030 let used_names: Vec<Symbol> = self
7032 .iter()
7033 .filter_map(|param| match param.name {
7034 hir::ParamName::Plain(ident) => Some(ident.name),
7035 _ => None,
7036 })
7037 .collect();
7038
7039 possible_names
7041 .iter()
7042 .find(|n| !used_names.contains(&Symbol::intern(n)))
7043 .unwrap_or(&"ParamName")
7044 .to_string()
7045 }
7046}
7047
7048struct ReplaceImplTraitVisitor<'a> {
7050 ty_spans: &'a mut Vec<Span>,
7051 param_did: DefId,
7052}
7053
7054impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
7055 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
7056 if let hir::TyKind::Path(hir::QPath::Resolved(
7057 None,
7058 hir::Path { res: Res::Def(_, segment_did), .. },
7059 )) = t.kind
7060 {
7061 if self.param_did == *segment_did {
7062 self.ty_spans.push(t.span);
7067 return;
7068 }
7069 }
7070
7071 hir::intravisit::walk_ty(self, t);
7072 }
7073}
7074
7075pub(super) fn get_explanation_based_on_obligation<'tcx>(
7076 tcx: TyCtxt<'tcx>,
7077 obligation: &PredicateObligation<'tcx>,
7078 trait_predicate: ty::PolyTraitClause<'tcx>,
7079 pre_message: String,
7080 long_ty_path: &mut Option<PathBuf>,
7081) -> String {
7082 if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
7083 "consider using `()`, or a `Result`".to_owned()
7084 } else {
7085 let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
7086 ty::FnDef(_, _) => Some("fn item"),
7087 ty::Closure(_, _) => Some("closure"),
7088 _ => None,
7089 };
7090
7091 let desc = match ty_desc {
7092 Some(desc) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", desc))
})format!(" {desc}"),
7093 None => String::new(),
7094 };
7095 if let ty::ClausePolarity::Positive = trait_predicate.polarity() {
7096 let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
7101 && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
7102 == Some(false);
7103 let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
7104
7105 ::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!(
7106 "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
7107 trait_predicate.print_modifiers_and_trait_path(),
7108 tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
7109 )
7110 } else {
7111 ::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")
7115 }
7116 }
7117}
7118
7119struct ReplaceImplTraitFolder<'tcx> {
7121 tcx: TyCtxt<'tcx>,
7122 param: &'tcx ty::GenericParamDef,
7123 replace_ty: Ty<'tcx>,
7124}
7125
7126impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
7127 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
7128 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
7129 if self.param.index == *index {
7130 return self.replace_ty;
7131 }
7132 }
7133 t.super_fold_with(self)
7134 }
7135
7136 fn cx(&self) -> TyCtxt<'tcx> {
7137 self.tcx
7138 }
7139}
7140
7141pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
7142 tcx: TyCtxt<'tcx>,
7143 sig: hir::FnSig<'tcx>,
7144 body: hir::TraitFn<'tcx>,
7145 opaque_def_id: LocalDefId,
7146 add_bounds: &str,
7147) -> Option<Vec<(Span, String)>> {
7148 let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
7149 return None;
7150 };
7151 let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
7152
7153 let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
7154 let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
7155 return None;
7157 };
7158 let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
7159 else {
7160 return None;
7162 };
7163 let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
7164 else {
7165 return None;
7167 };
7168
7169 let mut sugg = if future_output_ty.span.is_empty() {
7170 ::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![
7171 (async_span, String::new()),
7172 (
7173 future_output_ty.span,
7174 format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
7175 ),
7176 ]
7177 } else {
7178 ::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![
7179 (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
7180 (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
7181 (async_span, String::new()),
7182 ]
7183 };
7184
7185 if let hir::TraitFn::Provided(body) = body {
7187 let body = tcx.hir_body(body);
7188 let body_span = body.value.span;
7189 let body_span_without_braces =
7190 body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
7191 if body_span_without_braces.is_empty() {
7192 sugg.push((body_span_without_braces, " async {} ".to_owned()));
7193 } else {
7194 sugg.extend([
7195 (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
7196 (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
7197 ]);
7198 }
7199 }
7200
7201 Some(sugg)
7202}
7203
7204fn point_at_assoc_type_restriction(
7207 tcx: TyCtxt<'_>,
7208 err: &mut Diag<'_>,
7209 self_ty_str: &str,
7210 trait_name: &str,
7211 predicate: ty::Predicate<'_>,
7212 generics: &hir::Generics<'_>,
7213 data: &ImplDerivedCause<'_>,
7214) {
7215 let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
7216 return;
7217 };
7218 let ty::ClauseKind::Projection(proj) = clause else {
7219 return;
7220 };
7221 let Some(name) = tcx
7222 .opt_rpitit_info(proj.def_id())
7223 .and_then(|data| match data {
7224 ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => Some(tcx.item_name(fn_def_id)),
7225 ty::ImplTraitInTraitData::Impl { .. } => None,
7226 })
7227 .or_else(|| tcx.opt_item_name(proj.def_id()))
7228 else {
7229 return;
7230 };
7231 let mut predicates = generics.predicates.iter().peekable();
7232 let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
7233 while let Some(pred) = predicates.next() {
7234 let curr_span = pred.span;
7235 let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
7236 continue;
7237 };
7238 let mut bounds = pred.bounds.iter();
7239 while let Some(bound) = bounds.next() {
7240 let Some(trait_ref) = bound.trait_ref() else {
7241 continue;
7242 };
7243 if bound.span() != data.span {
7244 continue;
7245 }
7246 if let hir::TyKind::Path(path) = pred.bounded_ty.kind
7247 && let hir::QPath::TypeRelative(ty, segment) = path
7248 && segment.ident.name == name
7249 && let hir::TyKind::Path(inner_path) = ty.kind
7250 && let hir::QPath::Resolved(None, inner_path) = inner_path
7251 && let Res::SelfTyAlias { .. } = inner_path.res
7252 {
7253 let span = if pred.origin == hir::PredicateOrigin::WhereClause
7256 && generics
7257 .predicates
7258 .iter()
7259 .filter(|p| {
7260 #[allow(non_exhaustive_omitted_patterns)] match p.kind {
hir::WherePredicateKind::BoundPredicate(p) if
hir::PredicateOrigin::WhereClause == p.origin => true,
_ => false,
}matches!(
7261 p.kind,
7262 hir::WherePredicateKind::BoundPredicate(p)
7263 if hir::PredicateOrigin::WhereClause == p.origin
7264 )
7265 })
7266 .count()
7267 == 1
7268 {
7269 generics.where_clause_span
7272 } else if let Some(next_pred) = predicates.peek()
7273 && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
7274 && pred.origin == next.origin
7275 {
7276 curr_span.until(next_pred.span)
7278 } else if let Some((prev, prev_span)) = prev
7279 && pred.origin == prev.origin
7280 {
7281 prev_span.shrink_to_hi().to(curr_span)
7283 } else if pred.origin == hir::PredicateOrigin::WhereClause {
7284 curr_span.with_hi(generics.where_clause_span.hi())
7285 } else {
7286 curr_span
7287 };
7288
7289 err.span_suggestion_verbose(
7290 span,
7291 "associated type for the current `impl` cannot be restricted in `where` \
7292 clauses, remove this bound",
7293 "",
7294 Applicability::MaybeIncorrect,
7295 );
7296 }
7297 if let Some(new) =
7298 tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
7299 tcx,
7300 Ident::with_dummy_span(name),
7301 ty::AssocTag::Type,
7302 data.impl_or_alias_def_id,
7303 )
7304 {
7305 let span = tcx.def_span(new.def_id);
7308 err.span_label(
7309 span,
7310 ::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!(
7311 "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
7312 here",
7313 ),
7314 );
7315 let mut visitor = SelfVisitor { name: Some(name), .. };
7318 visitor.visit_trait_ref(trait_ref);
7319 for path in visitor.paths {
7320 err.span_suggestion_verbose(
7321 path.span,
7322 "replace the associated type with the type specified in this `impl`",
7323 tcx.type_of(new.def_id).skip_binder(),
7324 Applicability::MachineApplicable,
7325 );
7326 }
7327 } else {
7328 let mut visitor = SelfVisitor { name: None, .. };
7329 visitor.visit_trait_ref(trait_ref);
7330 let span: MultiSpan =
7331 visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
7332 err.span_note(
7333 span,
7334 "associated types for the current `impl` cannot be restricted in `where` \
7335 clauses",
7336 );
7337 }
7338 }
7339 prev = Some((pred, curr_span));
7340 }
7341}
7342
7343fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
7344 let mut refs = ::alloc::vec::Vec::new()vec![];
7345
7346 while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
7347 ty = *new_ty;
7348 refs.push(*mutbl);
7349 }
7350
7351 (ty, refs)
7352}
7353
7354struct FindTypeParam {
7357 param: rustc_span::Symbol,
7358 invalid_spans: Vec<Span> = Vec::new(),
7359 nested: bool = false,
7360}
7361
7362impl<'v> Visitor<'v> for FindTypeParam {
7363 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
7364 }
7366
7367 fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
7368 match ty.kind {
7375 hir::TyKind::Ptr(..) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
7376 hir::TyKind::Path(hir::QPath::Resolved(None, path))
7377 if let [segment] = path.segments
7378 && segment.ident.name == self.param =>
7379 {
7380 if !self.nested {
7381 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:7381",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(7381u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("FindTypeParam::visit_ty")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?ty, "FindTypeParam::visit_ty");
7382 self.invalid_spans.push(ty.span);
7383 }
7384 }
7385 hir::TyKind::Path(_) => {
7386 let prev = self.nested;
7387 self.nested = true;
7388 hir::intravisit::walk_ty(self, ty);
7389 self.nested = prev;
7390 }
7391 _ => {
7392 hir::intravisit::walk_ty(self, ty);
7393 }
7394 }
7395 }
7396}
7397
7398struct ParamFinder {
7401 params: Vec<Symbol> = Vec::new(),
7402}
7403
7404impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
7405 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
7406 match t.kind() {
7407 ty::Param(p) => self.params.push(p.name),
7408 _ => {}
7409 }
7410 t.super_visit_with(self)
7411 }
7412}
7413
7414impl ParamFinder {
7415 fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
7418 if self.params.is_empty() {
7419 return true;
7422 }
7423 generics.params.iter().any(|p| match p.name {
7424 hir::ParamName::Plain(p_name) => {
7425 self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
7427 }
7428 _ => true,
7429 })
7430 }
7431}