1use std::assert_matches::debug_assert_matches;
4use std::borrow::Cow;
5use std::iter;
6
7use itertools::{EitherOrBoth, Itertools};
8use rustc_abi::ExternAbi;
9use rustc_data_structures::fx::FxHashSet;
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_errors::codes::*;
12use rustc_errors::{
13 Applicability, Diag, EmissionGuarantee, MultiSpan, Style, SuggestionStyle, pluralize,
14 struct_span_code_err,
15};
16use rustc_hir::def::{CtorOf, DefKind, Res};
17use rustc_hir::def_id::DefId;
18use rustc_hir::intravisit::{Visitor, VisitorExt};
19use rustc_hir::lang_items::LangItem;
20use rustc_hir::{
21 self as hir, AmbigArg, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node,
22 expr_needs_parens, is_range_literal,
23};
24use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
25use rustc_middle::hir::map;
26use rustc_middle::traits::IsConstable;
27use rustc_middle::ty::error::TypeError;
28use rustc_middle::ty::print::{
29 PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _,
30 with_forced_trimmed_paths, with_no_trimmed_paths,
31};
32use rustc_middle::ty::{
33 self, AdtKind, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder,
34 TypeSuperFoldable, TypeVisitableExt, TypeckResults, Upcast, suggest_arbitrary_trait_bound,
35 suggest_constraining_type_param,
36};
37use rustc_middle::{bug, span_bug};
38use rustc_span::def_id::LocalDefId;
39use rustc_span::{
40 BytePos, DUMMY_SP, DesugaringKind, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym,
41};
42use tracing::{debug, instrument};
43
44use super::{
45 DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode,
46 PredicateObligation,
47};
48use crate::error_reporting::TypeErrCtxt;
49use crate::errors;
50use crate::infer::InferCtxtExt as _;
51use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
52use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt};
53
54#[derive(Debug)]
55pub enum CoroutineInteriorOrUpvar {
56 Interior(Span, Option<(Span, Option<Span>)>),
58 Upvar(Span),
60}
61
62#[derive(Debug)]
65struct CoroutineData<'a, 'tcx>(&'a TypeckResults<'tcx>);
66
67impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
68 fn try_get_upvar_span<F>(
72 &self,
73 infer_context: &InferCtxt<'tcx>,
74 coroutine_did: DefId,
75 ty_matches: F,
76 ) -> Option<CoroutineInteriorOrUpvar>
77 where
78 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
79 {
80 infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| {
81 upvars.iter().find_map(|(upvar_id, upvar)| {
82 let upvar_ty = self.0.node_type(*upvar_id);
83 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
84 ty_matches(ty::Binder::dummy(upvar_ty))
85 .then(|| CoroutineInteriorOrUpvar::Upvar(upvar.span))
86 })
87 })
88 }
89
90 fn get_from_await_ty<F>(
94 &self,
95 visitor: AwaitsVisitor,
96 hir: map::Map<'tcx>,
97 ty_matches: F,
98 ) -> Option<Span>
99 where
100 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
101 {
102 visitor
103 .awaits
104 .into_iter()
105 .map(|id| hir.expect_expr(id))
106 .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
107 .map(|expr| expr.span)
108 }
109}
110
111fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
112 (
113 generics.tail_span_for_predicate_suggestion(),
114 format!("{} {}", generics.add_where_or_trailing_comma(), pred),
115 )
116}
117
118pub fn suggest_restriction<'tcx, G: EmissionGuarantee>(
122 tcx: TyCtxt<'tcx>,
123 item_id: LocalDefId,
124 hir_generics: &hir::Generics<'tcx>,
125 msg: &str,
126 err: &mut Diag<'_, G>,
127 fn_sig: Option<&hir::FnSig<'_>>,
128 projection: Option<ty::AliasTy<'_>>,
129 trait_pred: ty::PolyTraitPredicate<'tcx>,
130 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
136) {
137 if hir_generics.where_clause_span.from_expansion()
138 || hir_generics.where_clause_span.desugaring_kind().is_some()
139 || projection.is_some_and(|projection| tcx.is_impl_trait_in_trait(projection.def_id))
140 {
141 return;
142 }
143 let generics = tcx.generics_of(item_id);
144 if let Some((param, bound_str, fn_sig)) =
146 fn_sig.zip(projection).and_then(|(sig, p)| match *p.self_ty().kind() {
147 ty::Param(param) => {
149 let param_def = generics.type_param(param, tcx);
150 if param_def.kind.is_synthetic() {
151 let bound_str =
152 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
153 return Some((param_def, bound_str, sig));
154 }
155 None
156 }
157 _ => None,
158 })
159 {
160 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
161 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
162 tcx,
163 param,
164 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
165 .to_ty(tcx),
166 });
167 if !trait_pred.is_suggestable(tcx, false) {
168 return;
169 }
170 let mut ty_spans = vec![];
178 for input in fn_sig.decl.inputs {
179 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
180 .visit_ty_unambig(input);
181 }
182 let type_param = format!("{type_param_name}: {bound_str}");
184
185 let mut sugg = vec![
186 if let Some(span) = hir_generics.span_for_param_suggestion() {
187 (span, format!(", {type_param}"))
188 } else {
189 (hir_generics.span, format!("<{type_param}>"))
190 },
191 predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
194 ];
195 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
196
197 err.multipart_suggestion(
200 "introduce a type parameter with a trait bound instead of using `impl Trait`",
201 sugg,
202 Applicability::MaybeIncorrect,
203 );
204 } else {
205 if !trait_pred.is_suggestable(tcx, false) {
206 return;
207 }
208 let (sp, suggestion) = match (
210 hir_generics
211 .params
212 .iter()
213 .find(|p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
214 super_traits,
215 ) {
216 (_, None) => predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
217 (None, Some((ident, []))) => (
218 ident.span.shrink_to_hi(),
219 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
220 ),
221 (_, Some((_, [.., bounds]))) => (
222 bounds.span().shrink_to_hi(),
223 format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
224 ),
225 (Some(_), Some((_, []))) => (
226 hir_generics.span.shrink_to_hi(),
227 format!(": {}", trait_pred.print_modifiers_and_trait_path()),
228 ),
229 };
230
231 err.span_suggestion_verbose(
232 sp,
233 format!("consider further restricting {msg}"),
234 suggestion,
235 Applicability::MachineApplicable,
236 );
237 }
238}
239
240impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
241 pub fn suggest_restricting_param_bound(
242 &self,
243 err: &mut Diag<'_>,
244 trait_pred: ty::PolyTraitPredicate<'tcx>,
245 associated_ty: Option<(&'static str, Ty<'tcx>)>,
246 mut body_id: LocalDefId,
247 ) {
248 if trait_pred.skip_binder().polarity != ty::PredicatePolarity::Positive {
249 return;
250 }
251
252 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
253
254 let self_ty = trait_pred.skip_binder().self_ty();
255 let (param_ty, projection) = match *self_ty.kind() {
256 ty::Param(_) => (true, None),
257 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
258 _ => (false, None),
259 };
260
261 loop {
264 let node = self.tcx.hir_node_by_def_id(body_id);
265 match node {
266 hir::Node::Item(hir::Item {
267 ident,
268 kind: hir::ItemKind::Trait(_, _, generics, bounds, _),
269 ..
270 }) if self_ty == self.tcx.types.self_param => {
271 assert!(param_ty);
272 suggest_restriction(
274 self.tcx,
275 body_id,
276 generics,
277 "`Self`",
278 err,
279 None,
280 projection,
281 trait_pred,
282 Some((ident, bounds)),
283 );
284 return;
285 }
286
287 hir::Node::TraitItem(hir::TraitItem {
288 generics,
289 kind: hir::TraitItemKind::Fn(..),
290 ..
291 }) if self_ty == self.tcx.types.self_param => {
292 assert!(param_ty);
293 suggest_restriction(
295 self.tcx, body_id, generics, "`Self`", err, None, projection, trait_pred,
296 None,
297 );
298 return;
299 }
300
301 hir::Node::TraitItem(hir::TraitItem {
302 generics,
303 kind: hir::TraitItemKind::Fn(fn_sig, ..),
304 ..
305 })
306 | hir::Node::ImplItem(hir::ImplItem {
307 generics,
308 kind: hir::ImplItemKind::Fn(fn_sig, ..),
309 ..
310 })
311 | hir::Node::Item(hir::Item {
312 kind: hir::ItemKind::Fn { sig: fn_sig, generics, .. },
313 ..
314 }) if projection.is_some() => {
315 suggest_restriction(
317 self.tcx,
318 body_id,
319 generics,
320 "the associated type",
321 err,
322 Some(fn_sig),
323 projection,
324 trait_pred,
325 None,
326 );
327 return;
328 }
329 hir::Node::Item(hir::Item {
330 kind:
331 hir::ItemKind::Trait(_, _, generics, ..)
332 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
333 ..
334 }) if projection.is_some() => {
335 suggest_restriction(
337 self.tcx,
338 body_id,
339 generics,
340 "the associated type",
341 err,
342 None,
343 projection,
344 trait_pred,
345 None,
346 );
347 return;
348 }
349
350 hir::Node::Item(hir::Item {
351 kind:
352 hir::ItemKind::Struct(_, generics)
353 | hir::ItemKind::Enum(_, generics)
354 | hir::ItemKind::Union(_, generics)
355 | hir::ItemKind::Trait(_, _, generics, ..)
356 | hir::ItemKind::Impl(hir::Impl { generics, .. })
357 | hir::ItemKind::Fn { generics, .. }
358 | hir::ItemKind::TyAlias(_, generics)
359 | hir::ItemKind::Const(_, generics, _)
360 | hir::ItemKind::TraitAlias(generics, _),
361 ..
362 })
363 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
364 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
365 if param_ty =>
366 {
367 if !trait_pred.skip_binder().trait_ref.args[1..]
376 .iter()
377 .all(|g| g.is_suggestable(self.tcx, false))
378 {
379 return;
380 }
381 let param_name = self_ty.to_string();
383 let mut constraint = with_no_trimmed_paths!(
384 trait_pred.print_modifiers_and_trait_path().to_string()
385 );
386
387 if let Some((name, term)) = associated_ty {
388 if constraint.ends_with('>') {
391 constraint = format!(
392 "{}, {} = {}>",
393 &constraint[..constraint.len() - 1],
394 name,
395 term
396 );
397 } else {
398 constraint.push_str(&format!("<{name} = {term}>"));
399 }
400 }
401
402 if suggest_constraining_type_param(
403 self.tcx,
404 generics,
405 err,
406 ¶m_name,
407 &constraint,
408 Some(trait_pred.def_id()),
409 None,
410 ) {
411 return;
412 }
413 }
414
415 hir::Node::Item(hir::Item {
416 kind:
417 hir::ItemKind::Struct(_, generics)
418 | hir::ItemKind::Enum(_, generics)
419 | hir::ItemKind::Union(_, generics)
420 | hir::ItemKind::Trait(_, _, generics, ..)
421 | hir::ItemKind::Impl(hir::Impl { generics, .. })
422 | hir::ItemKind::Fn { generics, .. }
423 | hir::ItemKind::TyAlias(_, generics)
424 | hir::ItemKind::Const(_, generics, _)
425 | hir::ItemKind::TraitAlias(generics, _),
426 ..
427 }) if !param_ty => {
428 if suggest_arbitrary_trait_bound(
430 self.tcx,
431 generics,
432 err,
433 trait_pred,
434 associated_ty,
435 ) {
436 return;
437 }
438 }
439 hir::Node::Crate(..) => return,
440
441 _ => {}
442 }
443 body_id = self.tcx.local_parent(body_id);
444 }
445 }
446
447 pub(super) fn suggest_dereferences(
450 &self,
451 obligation: &PredicateObligation<'tcx>,
452 err: &mut Diag<'_>,
453 trait_pred: ty::PolyTraitPredicate<'tcx>,
454 ) -> bool {
455 let mut code = obligation.cause.code();
456 if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
457 && let Some(typeck_results) = &self.typeck_results
458 && let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
459 && let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
460 {
461 let mut real_trait_pred = trait_pred;
465 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
466 code = parent_code;
467 if let Some(parent_trait_pred) = parent_trait_pred {
468 real_trait_pred = parent_trait_pred;
469 }
470 }
471
472 let real_ty = self.tcx.instantiate_bound_regions_with_erased(real_trait_pred.self_ty());
475 if !self.can_eq(obligation.param_env, real_ty, arg_ty) {
476 return false;
477 }
478
479 let (is_under_ref, base_ty, span) = match expr.kind {
486 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, subexpr)
487 if let &ty::Ref(region, base_ty, hir::Mutability::Not) = real_ty.kind() =>
488 {
489 (Some(region), base_ty, subexpr.span)
490 }
491 hir::ExprKind::AddrOf(..) => return false,
493 _ => (None, real_ty, obligation.cause.span),
494 };
495
496 let autoderef = (self.autoderef_steps)(base_ty);
497 let mut is_boxed = base_ty.is_box();
498 if let Some(steps) = autoderef.into_iter().position(|(mut ty, obligations)| {
499 let can_deref = is_under_ref.is_some()
502 || self.type_is_copy_modulo_regions(obligation.param_env, ty)
503 || ty.is_numeric() || is_boxed && self.type_is_sized_modulo_regions(obligation.param_env, ty);
505 is_boxed &= ty.is_box();
506
507 if let Some(region) = is_under_ref {
509 ty = Ty::new_ref(self.tcx, region, ty, hir::Mutability::Not);
510 }
511
512 let real_trait_pred_and_ty =
514 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
515 let obligation = self.mk_trait_obligation_with_new_self_ty(
516 obligation.param_env,
517 real_trait_pred_and_ty,
518 );
519
520 can_deref
521 && obligations
522 .iter()
523 .chain([&obligation])
524 .all(|obligation| self.predicate_may_hold(obligation))
525 }) && steps > 0
526 {
527 let derefs = "*".repeat(steps);
528 let msg = "consider dereferencing here";
529 let call_node = self.tcx.hir_node(*call_hir_id);
530 let is_receiver = matches!(
531 call_node,
532 Node::Expr(hir::Expr {
533 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
534 ..
535 })
536 if receiver_expr.hir_id == *arg_hir_id
537 );
538 if is_receiver {
539 err.multipart_suggestion_verbose(
540 msg,
541 vec![
542 (span.shrink_to_lo(), format!("({derefs}")),
543 (span.shrink_to_hi(), ")".to_string()),
544 ],
545 Applicability::MachineApplicable,
546 )
547 } else {
548 err.span_suggestion_verbose(
549 span.shrink_to_lo(),
550 msg,
551 derefs,
552 Applicability::MachineApplicable,
553 )
554 };
555 return true;
556 }
557 } else if let (
558 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id: Some(rhs_hir_id), .. },
559 predicate,
560 ) = code.peel_derives_with_predicate()
561 && let Some(typeck_results) = &self.typeck_results
562 && let hir::Node::Expr(lhs) = self.tcx.hir_node(*lhs_hir_id)
563 && let hir::Node::Expr(rhs) = self.tcx.hir_node(*rhs_hir_id)
564 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs)
565 && let trait_pred = predicate.unwrap_or(trait_pred)
566 && hir::lang_items::BINARY_OPERATORS
568 .iter()
569 .filter_map(|&op| self.tcx.lang_items().get(op))
570 .any(|op| {
571 op == trait_pred.skip_binder().trait_ref.def_id
572 })
573 {
574 let trait_pred = predicate.unwrap_or(trait_pred);
577 let lhs_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
578 let lhs_autoderef = (self.autoderef_steps)(lhs_ty);
579 let rhs_autoderef = (self.autoderef_steps)(rhs_ty);
580 let first_lhs = lhs_autoderef.first().unwrap().clone();
581 let first_rhs = rhs_autoderef.first().unwrap().clone();
582 let mut autoderefs = lhs_autoderef
583 .into_iter()
584 .enumerate()
585 .rev()
586 .zip_longest(rhs_autoderef.into_iter().enumerate().rev())
587 .map(|t| match t {
588 EitherOrBoth::Both(a, b) => (a, b),
589 EitherOrBoth::Left(a) => (a, (0, first_rhs.clone())),
590 EitherOrBoth::Right(b) => ((0, first_lhs.clone()), b),
591 })
592 .rev();
593 if let Some((lsteps, rsteps)) =
594 autoderefs.find_map(|((lsteps, (l_ty, _)), (rsteps, (r_ty, _)))| {
595 let trait_pred_and_ty = trait_pred.map_bound(|inner| {
599 (
600 ty::TraitPredicate {
601 trait_ref: ty::TraitRef::new_from_args(
602 self.tcx,
603 inner.trait_ref.def_id,
604 self.tcx.mk_args(
605 &[&[l_ty.into(), r_ty.into()], &inner.trait_ref.args[2..]]
606 .concat(),
607 ),
608 ),
609 ..inner
610 },
611 l_ty,
612 )
613 });
614 let obligation = self.mk_trait_obligation_with_new_self_ty(
615 obligation.param_env,
616 trait_pred_and_ty,
617 );
618 self.predicate_may_hold(&obligation).then_some(match (lsteps, rsteps) {
619 (_, 0) => (Some(lsteps), None),
620 (0, _) => (None, Some(rsteps)),
621 _ => (Some(lsteps), Some(rsteps)),
622 })
623 })
624 {
625 let make_sugg = |mut expr: &Expr<'_>, mut steps| {
626 let mut prefix_span = expr.span.shrink_to_lo();
627 let mut msg = "consider dereferencing here";
628 if let hir::ExprKind::AddrOf(_, _, inner) = expr.kind {
629 msg = "consider removing the borrow and dereferencing instead";
630 if let hir::ExprKind::AddrOf(..) = inner.kind {
631 msg = "consider removing the borrows and dereferencing instead";
632 }
633 }
634 while let hir::ExprKind::AddrOf(_, _, inner) = expr.kind
635 && steps > 0
636 {
637 prefix_span = prefix_span.with_hi(inner.span.lo());
638 expr = inner;
639 steps -= 1;
640 }
641 if steps == 0 {
643 return (
644 msg.trim_end_matches(" and dereferencing instead"),
645 vec![(prefix_span, String::new())],
646 );
647 }
648 let derefs = "*".repeat(steps);
649 let needs_parens = steps > 0
650 && match expr.kind {
651 hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true,
652 _ if is_range_literal(expr) => true,
653 _ => false,
654 };
655 let mut suggestion = if needs_parens {
656 vec![
657 (
658 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
659 format!("{derefs}("),
660 ),
661 (expr.span.shrink_to_hi(), ")".to_string()),
662 ]
663 } else {
664 vec![(
665 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
666 format!("{derefs}"),
667 )]
668 };
669 if !prefix_span.is_empty() {
671 suggestion.push((prefix_span, String::new()));
672 }
673 (msg, suggestion)
674 };
675
676 if let Some(lsteps) = lsteps
677 && let Some(rsteps) = rsteps
678 && lsteps > 0
679 && rsteps > 0
680 {
681 let mut suggestion = make_sugg(lhs, lsteps).1;
682 suggestion.append(&mut make_sugg(rhs, rsteps).1);
683 err.multipart_suggestion_verbose(
684 "consider dereferencing both sides of the expression",
685 suggestion,
686 Applicability::MachineApplicable,
687 );
688 return true;
689 } else if let Some(lsteps) = lsteps
690 && lsteps > 0
691 {
692 let (msg, suggestion) = make_sugg(lhs, lsteps);
693 err.multipart_suggestion_verbose(
694 msg,
695 suggestion,
696 Applicability::MachineApplicable,
697 );
698 return true;
699 } else if let Some(rsteps) = rsteps
700 && rsteps > 0
701 {
702 let (msg, suggestion) = make_sugg(rhs, rsteps);
703 err.multipart_suggestion_verbose(
704 msg,
705 suggestion,
706 Applicability::MachineApplicable,
707 );
708 return true;
709 }
710 }
711 }
712 false
713 }
714
715 fn get_closure_name(
719 &self,
720 def_id: DefId,
721 err: &mut Diag<'_>,
722 msg: Cow<'static, str>,
723 ) -> Option<Symbol> {
724 let get_name = |err: &mut Diag<'_>, kind: &hir::PatKind<'_>| -> Option<Symbol> {
725 match &kind {
728 hir::PatKind::Binding(hir::BindingMode::NONE, _, ident, None) => Some(ident.name),
729 _ => {
730 err.note(msg);
731 None
732 }
733 }
734 };
735
736 let hir_id = self.tcx.local_def_id_to_hir_id(def_id.as_local()?);
737 match self.tcx.parent_hir_node(hir_id) {
738 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(local), .. }) => {
739 get_name(err, &local.pat.kind)
740 }
741 hir::Node::LetStmt(local) => get_name(err, &local.pat.kind),
744 _ => None,
745 }
746 }
747
748 pub(super) fn suggest_fn_call(
752 &self,
753 obligation: &PredicateObligation<'tcx>,
754 err: &mut Diag<'_>,
755 trait_pred: ty::PolyTraitPredicate<'tcx>,
756 ) -> bool {
757 if self.typeck_results.is_none() {
760 return false;
761 }
762
763 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
764 obligation.predicate.kind().skip_binder()
765 && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
766 {
767 return false;
769 }
770
771 let self_ty = self.instantiate_binder_with_fresh_vars(
772 DUMMY_SP,
773 BoundRegionConversionTime::FnCall,
774 trait_pred.self_ty(),
775 );
776
777 let Some((def_id_or_name, output, inputs)) =
778 self.extract_callable_info(obligation.cause.body_id, obligation.param_env, self_ty)
779 else {
780 return false;
781 };
782
783 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
785
786 let new_obligation =
787 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
788 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
789 return false;
790 }
791
792 let hir = self.tcx.hir();
794
795 let msg = match def_id_or_name {
796 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
797 DefKind::Ctor(CtorOf::Struct, _) => {
798 Cow::from("use parentheses to construct this tuple struct")
799 }
800 DefKind::Ctor(CtorOf::Variant, _) => {
801 Cow::from("use parentheses to construct this tuple variant")
802 }
803 kind => Cow::from(format!(
804 "use parentheses to call this {}",
805 self.tcx.def_kind_descr(kind, def_id)
806 )),
807 },
808 DefIdOrName::Name(name) => Cow::from(format!("use parentheses to call this {name}")),
809 };
810
811 let args = inputs
812 .into_iter()
813 .map(|ty| {
814 if ty.is_suggestable(self.tcx, false) {
815 format!("/* {ty} */")
816 } else {
817 "/* value */".to_string()
818 }
819 })
820 .collect::<Vec<_>>()
821 .join(", ");
822
823 if matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. })
824 && obligation.cause.span.can_be_used_for_suggestions()
825 {
826 err.span_suggestion_verbose(
831 obligation.cause.span.shrink_to_hi(),
832 msg,
833 format!("({args})"),
834 Applicability::HasPlaceholders,
835 );
836 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
837 let name = match hir.get_if_local(def_id) {
838 Some(hir::Node::Expr(hir::Expr {
839 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
840 ..
841 })) => {
842 err.span_label(*fn_decl_span, "consider calling this closure");
843 let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
844 return false;
845 };
846 name.to_string()
847 }
848 Some(hir::Node::Item(hir::Item {
849 ident, kind: hir::ItemKind::Fn { .. }, ..
850 })) => {
851 err.span_label(ident.span, "consider calling this function");
852 ident.to_string()
853 }
854 Some(hir::Node::Ctor(..)) => {
855 let name = self.tcx.def_path_str(def_id);
856 err.span_label(
857 self.tcx.def_span(def_id),
858 format!("consider calling the constructor for `{name}`"),
859 );
860 name
861 }
862 _ => return false,
863 };
864 err.help(format!("{msg}: `{name}({args})`"));
865 }
866 true
867 }
868
869 pub(super) fn check_for_binding_assigned_block_without_tail_expression(
870 &self,
871 obligation: &PredicateObligation<'tcx>,
872 err: &mut Diag<'_>,
873 trait_pred: ty::PolyTraitPredicate<'tcx>,
874 ) {
875 let mut span = obligation.cause.span;
876 while span.from_expansion() {
877 span.remove_mark();
879 }
880 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
881 let Some(body) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else {
882 return;
883 };
884 expr_finder.visit_expr(body.value);
885 let Some(expr) = expr_finder.result else {
886 return;
887 };
888 let Some(typeck) = &self.typeck_results else {
889 return;
890 };
891 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
892 return;
893 };
894 if !ty.is_unit() {
895 return;
896 };
897 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
898 return;
899 };
900 let Res::Local(hir_id) = path.res else {
901 return;
902 };
903 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
904 return;
905 };
906 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
907 self.tcx.parent_hir_node(pat.hir_id)
908 else {
909 return;
910 };
911 let hir::ExprKind::Block(block, None) = init.kind else {
912 return;
913 };
914 if block.expr.is_some() {
915 return;
916 }
917 let [.., stmt] = block.stmts else {
918 err.span_label(block.span, "this empty block is missing a tail expression");
919 return;
920 };
921 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
922 return;
923 };
924 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
925 err.span_label(block.span, "this block is missing a tail expression");
926 return;
927 };
928 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
929 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
930
931 let new_obligation =
932 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
933 if self.predicate_must_hold_modulo_regions(&new_obligation) {
934 err.span_suggestion_short(
935 stmt.span.with_lo(tail_expr.span.hi()),
936 "remove this semicolon",
937 "",
938 Applicability::MachineApplicable,
939 );
940 } else {
941 err.span_label(block.span, "this block is missing a tail expression");
942 }
943 }
944
945 pub(super) fn suggest_add_clone_to_arg(
946 &self,
947 obligation: &PredicateObligation<'tcx>,
948 err: &mut Diag<'_>,
949 trait_pred: ty::PolyTraitPredicate<'tcx>,
950 ) -> bool {
951 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
952 self.enter_forall(self_ty, |ty: Ty<'_>| {
953 let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else {
954 return false;
955 };
956 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
957 let ty::Param(param) = inner_ty.kind() else { return false };
958 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
959 else {
960 return false;
961 };
962
963 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None);
964 let has_clone = |ty| {
965 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
966 .must_apply_modulo_regions()
967 };
968
969 let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
970 Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
972 Node::Expr(Expr {
975 kind:
976 hir::ExprKind::MethodCall(
977 hir::PathSegment { ident, .. },
978 _receiver,
979 &[],
980 call_span,
981 ),
982 hir_id,
983 ..
984 }) if ident.name == sym::clone
985 && !call_span.from_expansion()
986 && !has_clone(*inner_ty) =>
987 {
988 let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
990 let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
991 else {
992 return false;
993 };
994 if self.tcx.trait_of_item(did) != Some(clone_trait) {
995 return false;
996 }
997 Some(ident.span)
998 }
999 _ => return false,
1000 };
1001
1002 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1003 obligation.param_env,
1004 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1005 );
1006
1007 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1008 if !has_clone(param.to_ty(self.tcx)) {
1009 suggest_constraining_type_param(
1010 self.tcx,
1011 generics,
1012 err,
1013 param.name.as_str(),
1014 "Clone",
1015 Some(clone_trait),
1016 None,
1017 );
1018 }
1019 if let Some(existing_clone_call) = existing_clone_call {
1020 err.span_note(
1021 existing_clone_call,
1022 format!(
1023 "this `clone()` copies the reference, \
1024 which does not do anything, \
1025 because `{inner_ty}` does not implement `Clone`"
1026 ),
1027 );
1028 } else {
1029 err.span_suggestion_verbose(
1030 obligation.cause.span.shrink_to_hi(),
1031 "consider using clone here",
1032 ".clone()".to_string(),
1033 Applicability::MaybeIncorrect,
1034 );
1035 }
1036 return true;
1037 }
1038 false
1039 })
1040 }
1041
1042 pub fn extract_callable_info(
1046 &self,
1047 body_id: LocalDefId,
1048 param_env: ty::ParamEnv<'tcx>,
1049 found: Ty<'tcx>,
1050 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1051 let Some((def_id_or_name, output, inputs)) =
1053 (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1054 ty::FnPtr(sig_tys, _) => Some((
1055 DefIdOrName::Name("function pointer"),
1056 sig_tys.output(),
1057 sig_tys.inputs(),
1058 )),
1059 ty::FnDef(def_id, _) => {
1060 let fn_sig = found.fn_sig(self.tcx);
1061 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1062 }
1063 ty::Closure(def_id, args) => {
1064 let fn_sig = args.as_closure().sig();
1065 Some((
1066 DefIdOrName::DefId(def_id),
1067 fn_sig.output(),
1068 fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1069 ))
1070 }
1071 ty::CoroutineClosure(def_id, args) => {
1072 let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1073 Some((
1074 DefIdOrName::DefId(def_id),
1075 sig_parts.map_bound(|sig| {
1076 sig.to_coroutine(
1077 self.tcx,
1078 args.as_coroutine_closure().parent_args(),
1079 self.next_ty_var(DUMMY_SP),
1082 self.tcx.coroutine_for_closure(def_id),
1083 self.next_ty_var(DUMMY_SP),
1084 )
1085 }),
1086 sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1087 ))
1088 }
1089 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
1090 self.tcx.item_self_bounds(def_id).instantiate(self.tcx, args).iter().find_map(
1091 |pred| {
1092 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1093 && self
1094 .tcx
1095 .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1096 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1098 {
1099 Some((
1100 DefIdOrName::DefId(def_id),
1101 pred.kind().rebind(proj.term.expect_type()),
1102 pred.kind().rebind(args.as_slice()),
1103 ))
1104 } else {
1105 None
1106 }
1107 },
1108 )
1109 }
1110 ty::Dynamic(data, _, ty::Dyn) => data.iter().find_map(|pred| {
1111 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1112 && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1113 && let ty::Tuple(args) = proj.args.type_at(0).kind()
1115 {
1116 Some((
1117 DefIdOrName::Name("trait object"),
1118 pred.rebind(proj.term.expect_type()),
1119 pred.rebind(args.as_slice()),
1120 ))
1121 } else {
1122 None
1123 }
1124 }),
1125 ty::Param(param) => {
1126 let generics = self.tcx.generics_of(body_id);
1127 let name = if generics.count() > param.index as usize
1128 && let def = generics.param_at(param.index as usize, self.tcx)
1129 && matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1130 && def.name == param.name
1131 {
1132 DefIdOrName::DefId(def.def_id)
1133 } else {
1134 DefIdOrName::Name("type parameter")
1135 };
1136 param_env.caller_bounds().iter().find_map(|pred| {
1137 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1138 && self
1139 .tcx
1140 .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1141 && proj.projection_term.self_ty() == found
1142 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1144 {
1145 Some((
1146 name,
1147 pred.kind().rebind(proj.term.expect_type()),
1148 pred.kind().rebind(args.as_slice()),
1149 ))
1150 } else {
1151 None
1152 }
1153 })
1154 }
1155 _ => None,
1156 })
1157 else {
1158 return None;
1159 };
1160
1161 let output = self.instantiate_binder_with_fresh_vars(
1162 DUMMY_SP,
1163 BoundRegionConversionTime::FnCall,
1164 output,
1165 );
1166 let inputs = inputs
1167 .skip_binder()
1168 .iter()
1169 .map(|ty| {
1170 self.instantiate_binder_with_fresh_vars(
1171 DUMMY_SP,
1172 BoundRegionConversionTime::FnCall,
1173 inputs.rebind(*ty),
1174 )
1175 })
1176 .collect();
1177
1178 let InferOk { value: output, obligations: _ } =
1182 self.at(&ObligationCause::dummy(), param_env).normalize(output);
1183
1184 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1185 }
1186
1187 pub(super) fn suggest_add_reference_to_arg(
1188 &self,
1189 obligation: &PredicateObligation<'tcx>,
1190 err: &mut Diag<'_>,
1191 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1192 has_custom_message: bool,
1193 ) -> bool {
1194 let span = obligation.cause.span;
1195
1196 let code = match obligation.cause.code() {
1197 ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1198 c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
1201 if self.tcx.hir().span(*hir_id).lo() == span.lo() =>
1202 {
1203 c
1204 }
1205 c if matches!(
1206 span.ctxt().outer_expn_data().kind,
1207 ExpnKind::Desugaring(DesugaringKind::ForLoop)
1208 ) =>
1209 {
1210 c
1211 }
1212 _ => return false,
1213 };
1214
1215 let mut never_suggest_borrow: Vec<_> =
1219 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1220 .iter()
1221 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1222 .collect();
1223
1224 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1225 never_suggest_borrow.push(def_id);
1226 }
1227
1228 let param_env = obligation.param_env;
1229
1230 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1232 blacklist: &[DefId]|
1233 -> bool {
1234 if blacklist.contains(&old_pred.def_id()) {
1235 return false;
1236 }
1237 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1239 (
1240 trait_pred,
1241 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1242 )
1243 });
1244 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1245 (
1246 trait_pred,
1247 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1248 )
1249 });
1250
1251 let mk_result = |trait_pred_and_new_ty| {
1252 let obligation =
1253 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1254 self.predicate_must_hold_modulo_regions(&obligation)
1255 };
1256 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1257 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1258
1259 let (ref_inner_ty_satisfies_pred, ref_inner_ty_mut) =
1260 if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1261 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1262 {
1263 (
1264 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1265 mutability.is_mut(),
1266 )
1267 } else {
1268 (false, false)
1269 };
1270
1271 if imm_ref_self_ty_satisfies_pred
1272 || mut_ref_self_ty_satisfies_pred
1273 || ref_inner_ty_satisfies_pred
1274 {
1275 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1276 if !matches!(
1283 span.ctxt().outer_expn_data().kind,
1284 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1285 ) {
1286 return false;
1287 }
1288 if snippet.starts_with('&') {
1289 return false;
1292 }
1293 let msg = format!(
1300 "the trait bound `{}` is not satisfied",
1301 self.tcx.short_string(old_pred, err.long_ty_path()),
1302 );
1303 let self_ty_str =
1304 self.tcx.short_string(old_pred.self_ty().skip_binder(), err.long_ty_path());
1305 if has_custom_message {
1306 err.note(msg);
1307 } else {
1308 err.messages = vec![(rustc_errors::DiagMessage::from(msg), Style::NoStyle)];
1309 }
1310 err.span_label(
1311 span,
1312 format!(
1313 "the trait `{}` is not implemented for `{self_ty_str}`",
1314 old_pred.print_modifiers_and_trait_path()
1315 ),
1316 );
1317
1318 if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
1319 err.span_suggestions(
1320 span.shrink_to_lo(),
1321 "consider borrowing here",
1322 ["&".to_string(), "&mut ".to_string()],
1323 Applicability::MaybeIncorrect,
1324 );
1325 } else {
1326 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_mut;
1327 let sugg_prefix = format!("&{}", if is_mut { "mut " } else { "" });
1328 let sugg_msg = format!(
1329 "consider{} borrowing here",
1330 if is_mut { " mutably" } else { "" }
1331 );
1332
1333 if let Some(_) =
1336 self.tcx.sess.source_map().span_look_ahead(span, ".", Some(50))
1337 {
1338 err.multipart_suggestion_verbose(
1339 sugg_msg,
1340 vec![
1341 (span.shrink_to_lo(), format!("({sugg_prefix}")),
1342 (span.shrink_to_hi(), ")".to_string()),
1343 ],
1344 Applicability::MaybeIncorrect,
1345 );
1346 return true;
1347 }
1348
1349 let Some(body) =
1353 self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id)
1354 else {
1355 return false;
1356 };
1357 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1358 expr_finder.visit_expr(body.value);
1359 let Some(expr) = expr_finder.result else {
1360 return false;
1361 };
1362 let needs_parens = expr_needs_parens(expr);
1363
1364 let span = if needs_parens { span } else { span.shrink_to_lo() };
1365 let suggestions = if !needs_parens {
1366 vec![(span.shrink_to_lo(), sugg_prefix)]
1367 } else {
1368 vec![
1369 (span.shrink_to_lo(), format!("{sugg_prefix}(")),
1370 (span.shrink_to_hi(), ")".to_string()),
1371 ]
1372 };
1373 err.multipart_suggestion_verbose(
1374 sugg_msg,
1375 suggestions,
1376 Applicability::MaybeIncorrect,
1377 );
1378 }
1379 return true;
1380 }
1381 }
1382 return false;
1383 };
1384
1385 if let ObligationCauseCode::ImplDerived(cause) = &*code {
1386 try_borrowing(cause.derived.parent_trait_pred, &[])
1387 } else if let ObligationCauseCode::WhereClause(..)
1388 | ObligationCauseCode::WhereClauseInExpr(..) = code
1389 {
1390 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1391 } else {
1392 false
1393 }
1394 }
1395
1396 pub(super) fn suggest_borrowing_for_object_cast(
1398 &self,
1399 err: &mut Diag<'_>,
1400 obligation: &PredicateObligation<'tcx>,
1401 self_ty: Ty<'tcx>,
1402 target_ty: Ty<'tcx>,
1403 ) {
1404 let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
1405 return;
1406 };
1407 let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else {
1408 return;
1409 };
1410 let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
1411
1412 for predicate in predicates.iter() {
1413 if !self.predicate_must_hold_modulo_regions(
1414 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1415 ) {
1416 return;
1417 }
1418 }
1419
1420 err.span_suggestion(
1421 obligation.cause.span.shrink_to_lo(),
1422 format!(
1423 "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
1424 ),
1425 "&",
1426 Applicability::MaybeIncorrect,
1427 );
1428 }
1429
1430 pub(super) fn suggest_remove_reference(
1433 &self,
1434 obligation: &PredicateObligation<'tcx>,
1435 err: &mut Diag<'_>,
1436 trait_pred: ty::PolyTraitPredicate<'tcx>,
1437 ) -> bool {
1438 let mut span = obligation.cause.span;
1439 let mut trait_pred = trait_pred;
1440 let mut code = obligation.cause.code();
1441 while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
1442 code = c;
1445 trait_pred = parent_trait_pred;
1446 }
1447 while span.desugaring_kind().is_some() {
1448 span.remove_mark();
1450 }
1451 let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
1452 let Some(body) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else {
1453 return false;
1454 };
1455 expr_finder.visit_expr(body.value);
1456 let mut maybe_suggest = |suggested_ty, count, suggestions| {
1457 let trait_pred_and_suggested_ty =
1459 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1460
1461 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1462 obligation.param_env,
1463 trait_pred_and_suggested_ty,
1464 );
1465
1466 if self.predicate_may_hold(&new_obligation) {
1467 let msg = if count == 1 {
1468 "consider removing the leading `&`-reference".to_string()
1469 } else {
1470 format!("consider removing {count} leading `&`-references")
1471 };
1472
1473 err.multipart_suggestion_verbose(
1474 msg,
1475 suggestions,
1476 Applicability::MachineApplicable,
1477 );
1478 true
1479 } else {
1480 false
1481 }
1482 };
1483
1484 let mut count = 0;
1487 let mut suggestions = vec![];
1488 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1490 if let Some(mut hir_ty) = expr_finder.ty_result {
1491 while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
1492 count += 1;
1493 let span = hir_ty.span.until(mut_ty.ty.span);
1494 suggestions.push((span, String::new()));
1495
1496 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1497 break;
1498 };
1499 suggested_ty = *inner_ty;
1500
1501 hir_ty = mut_ty.ty;
1502
1503 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1504 return true;
1505 }
1506 }
1507 }
1508
1509 let Some(mut expr) = expr_finder.result else {
1511 return false;
1512 };
1513 let mut count = 0;
1514 let mut suggestions = vec![];
1515 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1517 'outer: loop {
1518 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1519 count += 1;
1520 let span = if expr.span.eq_ctxt(borrowed.span) {
1521 expr.span.until(borrowed.span)
1522 } else {
1523 expr.span.with_hi(expr.span.lo() + BytePos(1))
1524 };
1525 suggestions.push((span, String::new()));
1526
1527 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1528 break 'outer;
1529 };
1530 suggested_ty = *inner_ty;
1531
1532 expr = borrowed;
1533
1534 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1535 return true;
1536 }
1537 }
1538 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1539 && let Res::Local(hir_id) = path.res
1540 && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
1541 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
1542 && let None = local.ty
1543 && let Some(binding_expr) = local.init
1544 {
1545 expr = binding_expr;
1546 } else {
1547 break 'outer;
1548 }
1549 }
1550 false
1551 }
1552
1553 pub(super) fn suggest_remove_await(
1554 &self,
1555 obligation: &PredicateObligation<'tcx>,
1556 err: &mut Diag<'_>,
1557 ) {
1558 let hir = self.tcx.hir();
1559 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
1560 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1561 {
1562 if let Some((_, hir::Node::Expr(await_expr))) = hir.parent_iter(*hir_id).nth(1)
1569 && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
1570 {
1571 let removal_span = self
1572 .tcx
1573 .sess
1574 .source_map()
1575 .span_extend_while_whitespace(expr_span)
1576 .shrink_to_hi()
1577 .to(await_expr.span.shrink_to_hi());
1578 err.span_suggestion(
1579 removal_span,
1580 "remove the `.await`",
1581 "",
1582 Applicability::MachineApplicable,
1583 );
1584 } else {
1585 err.span_label(obligation.cause.span, "remove the `.await`");
1586 }
1587 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1589 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1590 obligation.predicate.kind().skip_binder()
1591 {
1592 err.span_label(*span, format!("this call returns `{}`", pred.self_ty()));
1593 }
1594 if let Some(typeck_results) = &self.typeck_results
1595 && let ty = typeck_results.expr_ty_adjusted(base)
1596 && let ty::FnDef(def_id, _args) = ty.kind()
1597 && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) =
1598 hir.get_if_local(*def_id)
1599 {
1600 let msg = format!("alternatively, consider making `fn {ident}` asynchronous");
1601 if vis_span.is_empty() {
1602 err.span_suggestion_verbose(
1603 span.shrink_to_lo(),
1604 msg,
1605 "async ",
1606 Applicability::MaybeIncorrect,
1607 );
1608 } else {
1609 err.span_suggestion_verbose(
1610 vis_span.shrink_to_hi(),
1611 msg,
1612 " async",
1613 Applicability::MaybeIncorrect,
1614 );
1615 }
1616 }
1617 }
1618 }
1619 }
1620
1621 pub(super) fn suggest_change_mut(
1624 &self,
1625 obligation: &PredicateObligation<'tcx>,
1626 err: &mut Diag<'_>,
1627 trait_pred: ty::PolyTraitPredicate<'tcx>,
1628 ) {
1629 let points_at_arg =
1630 matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
1631
1632 let span = obligation.cause.span;
1633 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1634 let refs_number =
1635 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1636 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1637 return;
1639 }
1640 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1641 if trait_pred.has_non_region_infer() {
1642 return;
1645 }
1646
1647 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1649 {
1650 let suggested_ty = match mutability {
1651 hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
1652 hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
1653 };
1654
1655 let trait_pred_and_suggested_ty =
1657 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1658
1659 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1660 obligation.param_env,
1661 trait_pred_and_suggested_ty,
1662 );
1663 let suggested_ty_would_satisfy_obligation = self
1664 .evaluate_obligation_no_overflow(&new_obligation)
1665 .must_apply_modulo_regions();
1666 if suggested_ty_would_satisfy_obligation {
1667 let sp = self
1668 .tcx
1669 .sess
1670 .source_map()
1671 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1672 if points_at_arg && mutability.is_not() && refs_number > 0 {
1673 if snippet
1675 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1676 .starts_with("mut")
1677 {
1678 return;
1679 }
1680 err.span_suggestion_verbose(
1681 sp,
1682 "consider changing this borrow's mutability",
1683 "&mut ",
1684 Applicability::MachineApplicable,
1685 );
1686 } else {
1687 err.note(format!(
1688 "`{}` is implemented for `{}`, but not for `{}`",
1689 trait_pred.print_modifiers_and_trait_path(),
1690 suggested_ty,
1691 trait_pred.skip_binder().self_ty(),
1692 ));
1693 }
1694 }
1695 }
1696 }
1697 }
1698
1699 pub(super) fn suggest_semicolon_removal(
1700 &self,
1701 obligation: &PredicateObligation<'tcx>,
1702 err: &mut Diag<'_>,
1703 span: Span,
1704 trait_pred: ty::PolyTraitPredicate<'tcx>,
1705 ) -> bool {
1706 let hir = self.tcx.hir();
1707 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
1708 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn {sig, body: body_id, .. }, .. }) = node
1709 && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind
1710 && sig.decl.output.span().overlaps(span)
1711 && blk.expr.is_none()
1712 && trait_pred.self_ty().skip_binder().is_unit()
1713 && let Some(stmt) = blk.stmts.last()
1714 && let hir::StmtKind::Semi(expr) = stmt.kind
1715 && let Some(typeck_results) = &self.typeck_results
1717 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1718 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1719 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1720 ))
1721 {
1722 err.span_label(
1723 expr.span,
1724 format!(
1725 "this expression has type `{}`, which implements `{}`",
1726 ty,
1727 trait_pred.print_modifiers_and_trait_path()
1728 ),
1729 );
1730 err.span_suggestion(
1731 self.tcx.sess.source_map().end_point(stmt.span),
1732 "remove this semicolon",
1733 "",
1734 Applicability::MachineApplicable,
1735 );
1736 return true;
1737 }
1738 false
1739 }
1740
1741 pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1742 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
1743 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
1744 else {
1745 return None;
1746 };
1747
1748 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1749 }
1750
1751 pub(super) fn suggest_impl_trait(
1755 &self,
1756 err: &mut Diag<'_>,
1757 obligation: &PredicateObligation<'tcx>,
1758 trait_pred: ty::PolyTraitPredicate<'tcx>,
1759 ) -> bool {
1760 let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
1761 return false;
1762 };
1763 let ty::Dynamic(_, _, ty::Dyn) = trait_pred.self_ty().skip_binder().kind() else {
1764 return false;
1765 };
1766
1767 err.code(E0746);
1768 err.primary_message("return type cannot be a trait object without pointer indirection");
1769 err.children.clear();
1770
1771 let span = obligation.cause.span;
1772 let body = self.tcx.hir().body_owned_by(obligation.cause.body_id);
1773
1774 let mut visitor = ReturnsVisitor::default();
1775 visitor.visit_body(&body);
1776
1777 let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
1778 && snip.starts_with("dyn ")
1779 {
1780 ("", span.with_hi(span.lo() + BytePos(4)))
1781 } else {
1782 ("dyn ", span.shrink_to_lo())
1783 };
1784
1785 err.span_suggestion_verbose(
1786 impl_span,
1787 "consider returning an `impl Trait` instead of a `dyn Trait`",
1788 "impl ",
1789 Applicability::MaybeIncorrect,
1790 );
1791
1792 let mut sugg = vec![
1793 (span.shrink_to_lo(), format!("Box<{pre}")),
1794 (span.shrink_to_hi(), ">".to_string()),
1795 ];
1796 sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
1797 let span =
1798 expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
1799 if !span.can_be_used_for_suggestions() {
1800 vec![]
1801 } else if let hir::ExprKind::Call(path, ..) = expr.kind
1802 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
1803 && method.ident.name == sym::new
1804 && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
1805 && box_path
1806 .res
1807 .opt_def_id()
1808 .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
1809 {
1810 vec![]
1812 } else {
1813 vec![
1814 (span.shrink_to_lo(), "Box::new(".to_string()),
1815 (span.shrink_to_hi(), ")".to_string()),
1816 ]
1817 }
1818 }));
1819
1820 err.multipart_suggestion(
1821 format!(
1822 "alternatively, box the return type, and wrap all of the returned values in \
1823 `Box::new`",
1824 ),
1825 sugg,
1826 Applicability::MaybeIncorrect,
1827 );
1828
1829 true
1830 }
1831
1832 pub(super) fn report_closure_arg_mismatch(
1833 &self,
1834 span: Span,
1835 found_span: Option<Span>,
1836 found: ty::TraitRef<'tcx>,
1837 expected: ty::TraitRef<'tcx>,
1838 cause: &ObligationCauseCode<'tcx>,
1839 found_node: Option<Node<'_>>,
1840 param_env: ty::ParamEnv<'tcx>,
1841 ) -> Diag<'a> {
1842 pub(crate) fn build_fn_sig_ty<'tcx>(
1843 infcx: &InferCtxt<'tcx>,
1844 trait_ref: ty::TraitRef<'tcx>,
1845 ) -> Ty<'tcx> {
1846 let inputs = trait_ref.args.type_at(1);
1847 let sig = match inputs.kind() {
1848 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id) => {
1849 infcx.tcx.mk_fn_sig(
1850 *inputs,
1851 infcx.next_ty_var(DUMMY_SP),
1852 false,
1853 hir::Safety::Safe,
1854 ExternAbi::Rust,
1855 )
1856 }
1857 _ => infcx.tcx.mk_fn_sig(
1858 [inputs],
1859 infcx.next_ty_var(DUMMY_SP),
1860 false,
1861 hir::Safety::Safe,
1862 ExternAbi::Rust,
1863 ),
1864 };
1865
1866 Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
1867 }
1868
1869 let argument_kind = match expected.self_ty().kind() {
1870 ty::Closure(..) => "closure",
1871 ty::Coroutine(..) => "coroutine",
1872 _ => "function",
1873 };
1874 let mut err = struct_span_code_err!(
1875 self.dcx(),
1876 span,
1877 E0631,
1878 "type mismatch in {argument_kind} arguments",
1879 );
1880
1881 err.span_label(span, "expected due to this");
1882
1883 let found_span = found_span.unwrap_or(span);
1884 err.span_label(found_span, "found signature defined here");
1885
1886 let expected = build_fn_sig_ty(self, expected);
1887 let found = build_fn_sig_ty(self, found);
1888
1889 let (expected_str, found_str) = self.cmp(expected, found);
1890
1891 let signature_kind = format!("{argument_kind} signature");
1892 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
1893
1894 self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
1895 self.note_conflicting_closure_bounds(cause, &mut err);
1896
1897 if let Some(found_node) = found_node {
1898 hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
1899 }
1900
1901 err
1902 }
1903
1904 fn note_conflicting_fn_args(
1905 &self,
1906 err: &mut Diag<'_>,
1907 cause: &ObligationCauseCode<'tcx>,
1908 expected: Ty<'tcx>,
1909 found: Ty<'tcx>,
1910 param_env: ty::ParamEnv<'tcx>,
1911 ) {
1912 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
1913 return;
1914 };
1915 let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
1916 return;
1917 };
1918 let expected = sig_tys.with(*hdr);
1919 let ty::FnPtr(sig_tys, hdr) = found.kind() else {
1920 return;
1921 };
1922 let found = sig_tys.with(*hdr);
1923 let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
1924 return;
1925 };
1926 let hir::ExprKind::Path(path) = arg.kind else {
1927 return;
1928 };
1929 let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
1930 let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
1931 let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
1932
1933 let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
1934 let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
1935 let (found_ty, found_refs) = get_deref_type_and_refs(found);
1936
1937 if infcx.can_eq(param_env, found_ty, expected_ty) {
1938 if found_refs.len() == expected_refs.len()
1939 && found_refs.iter().eq(expected_refs.iter())
1940 {
1941 name
1942 } else if found_refs.len() > expected_refs.len() {
1943 let refs = &found_refs[..found_refs.len() - expected_refs.len()];
1944 if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
1945 format!(
1946 "{}{name}",
1947 refs.iter()
1948 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
1949 .collect::<Vec<_>>()
1950 .join(""),
1951 )
1952 } else {
1953 format!(
1955 "{}*{name}",
1956 refs.iter()
1957 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
1958 .collect::<Vec<_>>()
1959 .join(""),
1960 )
1961 }
1962 } else if expected_refs.len() > found_refs.len() {
1963 format!(
1964 "{}{name}",
1965 (0..(expected_refs.len() - found_refs.len()))
1966 .map(|_| "*")
1967 .collect::<Vec<_>>()
1968 .join(""),
1969 )
1970 } else {
1971 format!(
1972 "{}{name}",
1973 found_refs
1974 .iter()
1975 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
1976 .chain(found_refs.iter().map(|_| "*".to_string()))
1977 .collect::<Vec<_>>()
1978 .join(""),
1979 )
1980 }
1981 } else {
1982 format!("/* {found} */")
1983 }
1984 };
1985 let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
1986 let (expected_ty, _) = get_deref_type_and_refs(expected);
1987 let (found_ty, _) = get_deref_type_and_refs(found);
1988 self.can_eq(param_env, found_ty, expected_ty)
1989 });
1990 let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
1991 && !expected_inputs.is_empty()
1992 && expected_inputs.len() == found_inputs.len()
1993 && let Some(typeck) = &self.typeck_results
1994 && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
1995 && res_kind.is_fn_like()
1996 {
1997 let closure: Vec<_> = self
1998 .tcx
1999 .fn_arg_names(fn_def_id)
2000 .iter()
2001 .enumerate()
2002 .map(|(i, ident)| {
2003 if ident.name.is_empty() || ident.name == kw::SelfLower {
2004 format!("arg{i}")
2005 } else {
2006 format!("{ident}")
2007 }
2008 })
2009 .collect();
2010 let args = closure
2011 .iter()
2012 .zip(both_tys)
2013 .map(|(name, (expected, found))| {
2014 arg_expr(self.infcx, name.to_owned(), expected, found)
2015 })
2016 .collect();
2017 (closure, args)
2018 } else {
2019 let closure_args = expected_inputs
2020 .iter()
2021 .enumerate()
2022 .map(|(i, _)| format!("arg{i}"))
2023 .collect::<Vec<_>>();
2024 let call_args = both_tys
2025 .enumerate()
2026 .map(|(i, (expected, found))| {
2027 arg_expr(self.infcx, format!("arg{i}"), expected, found)
2028 })
2029 .collect::<Vec<_>>();
2030 (closure_args, call_args)
2031 };
2032 let closure_names: Vec<_> = closure_names
2033 .into_iter()
2034 .zip(expected_inputs.iter())
2035 .map(|(name, ty)| {
2036 format!(
2037 "{name}{}",
2038 if ty.has_infer_types() {
2039 String::new()
2040 } else if ty.references_error() {
2041 ": /* type */".to_string()
2042 } else {
2043 format!(": {ty}")
2044 }
2045 )
2046 })
2047 .collect();
2048 err.multipart_suggestion(
2049 "consider wrapping the function in a closure",
2050 vec![
2051 (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
2052 (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
2053 ],
2054 Applicability::MaybeIncorrect,
2055 );
2056 }
2057
2058 fn note_conflicting_closure_bounds(
2061 &self,
2062 cause: &ObligationCauseCode<'tcx>,
2063 err: &mut Diag<'_>,
2064 ) {
2065 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = cause
2069 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2070 && let Some(pred) = predicates.predicates.get(*idx)
2071 && let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
2072 && self.tcx.is_fn_trait(trait_pred.def_id())
2073 {
2074 let expected_self =
2075 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2076 let expected_args =
2077 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.args));
2078
2079 let other_pred = predicates.into_iter().enumerate().find(|(other_idx, (pred, _))| {
2082 match pred.kind().skip_binder() {
2083 ty::ClauseKind::Trait(trait_pred)
2084 if self.tcx.is_fn_trait(trait_pred.def_id())
2085 && other_idx != idx
2086 && expected_self
2089 == self.tcx.anonymize_bound_vars(
2090 pred.kind().rebind(trait_pred.self_ty()),
2091 )
2092 && expected_args
2094 != self.tcx.anonymize_bound_vars(
2095 pred.kind().rebind(trait_pred.trait_ref.args),
2096 ) =>
2097 {
2098 true
2099 }
2100 _ => false,
2101 }
2102 });
2103 if let Some((_, (_, other_pred_span))) = other_pred {
2105 err.span_note(
2106 other_pred_span,
2107 "closure inferred to have a different signature due to this bound",
2108 );
2109 }
2110 }
2111 }
2112
2113 pub(super) fn suggest_fully_qualified_path(
2114 &self,
2115 err: &mut Diag<'_>,
2116 item_def_id: DefId,
2117 span: Span,
2118 trait_ref: DefId,
2119 ) {
2120 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id) {
2121 if let ty::AssocKind::Const | ty::AssocKind::Type = assoc_item.kind {
2122 err.note(format!(
2123 "{}s cannot be accessed directly on a `trait`, they can only be \
2124 accessed through a specific `impl`",
2125 self.tcx.def_kind_descr(assoc_item.kind.as_def_kind(), item_def_id)
2126 ));
2127 err.span_suggestion(
2128 span,
2129 "use the fully qualified path to an implementation",
2130 format!("<Type as {}>::{}", self.tcx.def_path_str(trait_ref), assoc_item.name),
2131 Applicability::HasPlaceholders,
2132 );
2133 }
2134 }
2135 }
2136
2137 #[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2180 pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2181 &self,
2182 err: &mut Diag<'_, G>,
2183 obligation: &PredicateObligation<'tcx>,
2184 ) -> bool {
2185 let hir = self.tcx.hir();
2186
2187 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2210 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
2211 _ => (None, None),
2212 };
2213 let mut coroutine = None;
2214 let mut outer_coroutine = None;
2215 let mut next_code = Some(obligation.cause.code());
2216
2217 let mut seen_upvar_tys_infer_tuple = false;
2218
2219 while let Some(code) = next_code {
2220 debug!(?code);
2221 match code {
2222 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2223 next_code = Some(parent_code);
2224 }
2225 ObligationCauseCode::ImplDerived(cause) => {
2226 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2227 debug!(
2228 parent_trait_ref = ?cause.derived.parent_trait_pred,
2229 self_ty.kind = ?ty.kind(),
2230 "ImplDerived",
2231 );
2232
2233 match *ty.kind() {
2234 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
2235 coroutine = coroutine.or(Some(did));
2236 outer_coroutine = Some(did);
2237 }
2238 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2239 seen_upvar_tys_infer_tuple = true;
2244 }
2245 _ if coroutine.is_none() => {
2246 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2247 target_ty = Some(ty);
2248 }
2249 _ => {}
2250 }
2251
2252 next_code = Some(&cause.derived.parent_code);
2253 }
2254 ObligationCauseCode::WellFormedDerived(derived_obligation)
2255 | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
2256 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2257 debug!(
2258 parent_trait_ref = ?derived_obligation.parent_trait_pred,
2259 self_ty.kind = ?ty.kind(),
2260 );
2261
2262 match *ty.kind() {
2263 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
2264 coroutine = coroutine.or(Some(did));
2265 outer_coroutine = Some(did);
2266 }
2267 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2268 seen_upvar_tys_infer_tuple = true;
2273 }
2274 _ if coroutine.is_none() => {
2275 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2276 target_ty = Some(ty);
2277 }
2278 _ => {}
2279 }
2280
2281 next_code = Some(&derived_obligation.parent_code);
2282 }
2283 _ => break,
2284 }
2285 }
2286
2287 debug!(?coroutine, ?trait_ref, ?target_ty);
2289 let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
2290 (coroutine, trait_ref, target_ty)
2291 else {
2292 return false;
2293 };
2294
2295 let span = self.tcx.def_span(coroutine_did);
2296
2297 let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
2298 debug!(
2299 ?coroutine_did,
2300 ?coroutine_did_root,
2301 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2302 ?span,
2303 );
2304
2305 let coroutine_body =
2306 coroutine_did.as_local().and_then(|def_id| hir.maybe_body_owned_by(def_id));
2307 let mut visitor = AwaitsVisitor::default();
2308 if let Some(body) = coroutine_body {
2309 visitor.visit_body(&body);
2310 }
2311 debug!(awaits = ?visitor.awaits);
2312
2313 let target_ty_erased = self.tcx.erase_regions(target_ty);
2316 let ty_matches = |ty| -> bool {
2317 let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
2330 let ty_erased = self.tcx.erase_regions(ty_erased);
2331 let eq = ty_erased == target_ty_erased;
2332 debug!(?ty_erased, ?target_ty_erased, ?eq);
2333 eq
2334 };
2335
2336 let coroutine_data = match &self.typeck_results {
2341 Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
2342 _ if coroutine_did.is_local() => {
2343 CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
2344 }
2345 _ => return false,
2346 };
2347
2348 let coroutine_within_in_progress_typeck = match &self.typeck_results {
2349 Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
2350 _ => false,
2351 };
2352
2353 let mut interior_or_upvar_span = None;
2354
2355 let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, hir, ty_matches);
2356 debug!(?from_awaited_ty);
2357
2358 if coroutine_did.is_local()
2360 && !coroutine_within_in_progress_typeck
2362 && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
2363 {
2364 debug!(?coroutine_info);
2365 'find_source: for (variant, source_info) in
2366 coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
2367 {
2368 debug!(?variant);
2369 for &local in variant {
2370 let decl = &coroutine_info.field_tys[local];
2371 debug!(?decl);
2372 if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
2373 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
2374 decl.source_info.span,
2375 Some((source_info.span, from_awaited_ty)),
2376 ));
2377 break 'find_source;
2378 }
2379 }
2380 }
2381 }
2382
2383 if interior_or_upvar_span.is_none() {
2384 interior_or_upvar_span =
2385 coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
2386 }
2387
2388 if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
2389 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
2390 }
2391
2392 debug!(?interior_or_upvar_span);
2393 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2394 let is_async = self.tcx.coroutine_is_async(coroutine_did);
2395 self.note_obligation_cause_for_async_await(
2396 err,
2397 interior_or_upvar_span,
2398 is_async,
2399 outer_coroutine,
2400 trait_ref,
2401 target_ty,
2402 obligation,
2403 next_code,
2404 );
2405 true
2406 } else {
2407 false
2408 }
2409 }
2410
2411 #[instrument(level = "debug", skip_all)]
2414 fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2415 &self,
2416 err: &mut Diag<'_, G>,
2417 interior_or_upvar_span: CoroutineInteriorOrUpvar,
2418 is_async: bool,
2419 outer_coroutine: Option<DefId>,
2420 trait_pred: ty::TraitPredicate<'tcx>,
2421 target_ty: Ty<'tcx>,
2422 obligation: &PredicateObligation<'tcx>,
2423 next_code: Option<&ObligationCauseCode<'tcx>>,
2424 ) {
2425 let source_map = self.tcx.sess.source_map();
2426
2427 let (await_or_yield, an_await_or_yield) =
2428 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2429 let future_or_coroutine = if is_async { "future" } else { "coroutine" };
2430
2431 let hir = self.tcx.hir();
2434 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2435 self.tcx.get_diagnostic_name(trait_pred.def_id())
2436 {
2437 let (trait_name, trait_verb) =
2438 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2439
2440 err.code = None;
2441 err.primary_message(format!(
2442 "{future_or_coroutine} cannot be {trait_verb} between threads safely"
2443 ));
2444
2445 let original_span = err.span.primary_span().unwrap();
2446 let mut span = MultiSpan::from_span(original_span);
2447
2448 let message = outer_coroutine
2449 .and_then(|coroutine_did| {
2450 Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
2451 CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
2452 CoroutineKind::Desugared(
2453 CoroutineDesugaring::Async,
2454 CoroutineSource::Fn,
2455 ) => self
2456 .tcx
2457 .parent(coroutine_did)
2458 .as_local()
2459 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2460 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2461 .map(|name| {
2462 format!("future returned by `{name}` is not {trait_name}")
2463 })?,
2464 CoroutineKind::Desugared(
2465 CoroutineDesugaring::Async,
2466 CoroutineSource::Block,
2467 ) => {
2468 format!("future created by async block is not {trait_name}")
2469 }
2470 CoroutineKind::Desugared(
2471 CoroutineDesugaring::Async,
2472 CoroutineSource::Closure,
2473 ) => {
2474 format!("future created by async closure is not {trait_name}")
2475 }
2476 CoroutineKind::Desugared(
2477 CoroutineDesugaring::AsyncGen,
2478 CoroutineSource::Fn,
2479 ) => self
2480 .tcx
2481 .parent(coroutine_did)
2482 .as_local()
2483 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2484 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2485 .map(|name| {
2486 format!("async iterator returned by `{name}` is not {trait_name}")
2487 })?,
2488 CoroutineKind::Desugared(
2489 CoroutineDesugaring::AsyncGen,
2490 CoroutineSource::Block,
2491 ) => {
2492 format!("async iterator created by async gen block is not {trait_name}")
2493 }
2494 CoroutineKind::Desugared(
2495 CoroutineDesugaring::AsyncGen,
2496 CoroutineSource::Closure,
2497 ) => {
2498 format!(
2499 "async iterator created by async gen closure is not {trait_name}"
2500 )
2501 }
2502 CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
2503 self.tcx
2504 .parent(coroutine_did)
2505 .as_local()
2506 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2507 .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
2508 .map(|name| {
2509 format!("iterator returned by `{name}` is not {trait_name}")
2510 })?
2511 }
2512 CoroutineKind::Desugared(
2513 CoroutineDesugaring::Gen,
2514 CoroutineSource::Block,
2515 ) => {
2516 format!("iterator created by gen block is not {trait_name}")
2517 }
2518 CoroutineKind::Desugared(
2519 CoroutineDesugaring::Gen,
2520 CoroutineSource::Closure,
2521 ) => {
2522 format!("iterator created by gen closure is not {trait_name}")
2523 }
2524 })
2525 })
2526 .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
2527
2528 span.push_span_label(original_span, message);
2529 err.span(span);
2530
2531 format!("is not {trait_name}")
2532 } else {
2533 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2534 };
2535
2536 let mut explain_yield = |interior_span: Span, yield_span: Span| {
2537 let mut span = MultiSpan::from_span(yield_span);
2538 let snippet = match source_map.span_to_snippet(interior_span) {
2539 Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
2542 _ => "the value".to_string(),
2543 };
2544 span.push_span_label(
2561 yield_span,
2562 format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
2563 );
2564 span.push_span_label(
2565 interior_span,
2566 format!("has type `{target_ty}` which {trait_explanation}"),
2567 );
2568 err.span_note(
2569 span,
2570 format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
2571 );
2572 };
2573 match interior_or_upvar_span {
2574 CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2575 if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
2576 if let Some(await_span) = from_awaited_ty {
2577 let mut span = MultiSpan::from_span(await_span);
2579 span.push_span_label(
2580 await_span,
2581 format!(
2582 "await occurs here on type `{target_ty}`, which {trait_explanation}"
2583 ),
2584 );
2585 err.span_note(
2586 span,
2587 format!(
2588 "future {trait_explanation} as it awaits another future which {trait_explanation}"
2589 ),
2590 );
2591 } else {
2592 explain_yield(interior_span, yield_span);
2594 }
2595 }
2596 }
2597 CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
2598 let non_send = match target_ty.kind() {
2600 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
2601 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2602 _ => None,
2603 },
2604 _ => None,
2605 };
2606
2607 let (span_label, span_note) = match non_send {
2608 Some((ref_ty, is_mut)) => {
2612 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2613 let ref_kind = if is_mut { "&mut" } else { "&" };
2614 (
2615 format!(
2616 "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
2617 ),
2618 format!(
2619 "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
2620 ),
2621 )
2622 }
2623 None => (
2624 format!("has type `{target_ty}` which {trait_explanation}"),
2625 format!("captured value {trait_explanation}"),
2626 ),
2627 };
2628
2629 let mut span = MultiSpan::from_span(upvar_span);
2630 span.push_span_label(upvar_span, span_label);
2631 err.span_note(span, span_note);
2632 }
2633 }
2634
2635 debug!(?next_code);
2638 self.note_obligation_cause_code(
2639 obligation.cause.body_id,
2640 err,
2641 obligation.predicate,
2642 obligation.param_env,
2643 next_code.unwrap(),
2644 &mut Vec::new(),
2645 &mut Default::default(),
2646 );
2647 }
2648
2649 pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
2650 &self,
2651 body_id: LocalDefId,
2652 err: &mut Diag<'_, G>,
2653 predicate: T,
2654 param_env: ty::ParamEnv<'tcx>,
2655 cause_code: &ObligationCauseCode<'tcx>,
2656 obligated_types: &mut Vec<Ty<'tcx>>,
2657 seen_requirements: &mut FxHashSet<DefId>,
2658 ) where
2659 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
2660 {
2661 let tcx = self.tcx;
2662 let predicate = predicate.upcast(tcx);
2663 let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
2664 if let Some(pred) = predicate.as_trait_clause()
2665 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2666 && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2667 {
2668 err.span_suggestion_verbose(
2669 expr.span.until(inner.span),
2670 "references are always `Sized`, even if they point to unsized data; consider \
2671 not dereferencing the expression",
2672 String::new(),
2673 Applicability::MaybeIncorrect,
2674 );
2675 }
2676 };
2677 match *cause_code {
2678 ObligationCauseCode::ExprAssignable
2679 | ObligationCauseCode::MatchExpressionArm { .. }
2680 | ObligationCauseCode::Pattern { .. }
2681 | ObligationCauseCode::IfExpression { .. }
2682 | ObligationCauseCode::IfExpressionWithNoElse
2683 | ObligationCauseCode::MainFunctionType
2684 | ObligationCauseCode::LangFunctionType(_)
2685 | ObligationCauseCode::IntrinsicType
2686 | ObligationCauseCode::MethodReceiver
2687 | ObligationCauseCode::ReturnNoExpression
2688 | ObligationCauseCode::UnifyReceiver(..)
2689 | ObligationCauseCode::Misc
2690 | ObligationCauseCode::WellFormed(..)
2691 | ObligationCauseCode::MatchImpl(..)
2692 | ObligationCauseCode::ReturnValue(_)
2693 | ObligationCauseCode::BlockTailExpression(..)
2694 | ObligationCauseCode::AwaitableExpr(_)
2695 | ObligationCauseCode::ForLoopIterator
2696 | ObligationCauseCode::QuestionMark
2697 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2698 | ObligationCauseCode::LetElse
2699 | ObligationCauseCode::BinOp { .. }
2700 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2701 | ObligationCauseCode::DropImpl
2702 | ObligationCauseCode::ConstParam(_)
2703 | ObligationCauseCode::ReferenceOutlivesReferent(..)
2704 | ObligationCauseCode::ObjectTypeBound(..) => {}
2705 ObligationCauseCode::RustCall => {
2706 if let Some(pred) = predicate.as_trait_clause()
2707 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2708 {
2709 err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
2710 }
2711 }
2712 ObligationCauseCode::SliceOrArrayElem => {
2713 err.note("slice and array elements must have `Sized` type");
2714 }
2715 ObligationCauseCode::ArrayLen(array_ty) => {
2716 err.note(format!("the length of array `{array_ty}` must be type `usize`"));
2717 }
2718 ObligationCauseCode::TupleElem => {
2719 err.note("only the last element of a tuple may have a dynamically sized type");
2720 }
2721 ObligationCauseCode::WhereClause(item_def_id, span)
2722 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
2723 | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
2724 if !span.is_dummy() =>
2725 {
2726 if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
2727 if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
2728 && let hir::ExprKind::Call(_, args) = expr.kind
2729 && let Some(expr) = args.get(*pos)
2730 {
2731 suggest_remove_deref(err, &expr);
2732 } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2733 && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
2734 && let Some(expr) = args.get(*pos)
2735 {
2736 suggest_remove_deref(err, &expr);
2737 }
2738 }
2739 let item_name = tcx.def_path_str(item_def_id);
2740 let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2741 let mut multispan = MultiSpan::from(span);
2742 let sm = tcx.sess.source_map();
2743 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2744 let same_line =
2745 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2746 (Ok(l), Ok(r)) => l.line == r.line,
2747 _ => true,
2748 };
2749 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2750 multispan.push_span_label(
2751 ident.span,
2752 format!(
2753 "required by a bound in this {}",
2754 tcx.def_kind(item_def_id).descr(item_def_id)
2755 ),
2756 );
2757 }
2758 }
2759 let mut a = "a";
2760 let mut this = "this bound";
2761 let mut note = None;
2762 let mut help = None;
2763 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
2764 match clause {
2765 ty::ClauseKind::Trait(trait_pred) => {
2766 let def_id = trait_pred.def_id();
2767 let visible_item = if let Some(local) = def_id.as_local() {
2768 let vis = &tcx.resolutions(()).effective_visibilities;
2770 let is_locally_reachable = tcx.parent(def_id).is_crate_root();
2772 vis.is_reachable(local) || is_locally_reachable
2773 } else {
2774 tcx.visible_parent_map(()).get(&def_id).is_some()
2776 };
2777 if tcx.is_lang_item(def_id, LangItem::Sized) {
2778 if tcx
2780 .generics_of(item_def_id)
2781 .own_params
2782 .iter()
2783 .any(|param| tcx.def_span(param.def_id) == span)
2784 {
2785 a = "an implicit `Sized`";
2786 this =
2787 "the implicit `Sized` requirement on this type parameter";
2788 }
2789 if let Some(hir::Node::TraitItem(hir::TraitItem {
2790 generics,
2791 kind: hir::TraitItemKind::Type(bounds, None),
2792 ..
2793 })) = tcx.hir().get_if_local(item_def_id)
2794 && !bounds.iter()
2796 .filter_map(|bound| bound.trait_ref())
2797 .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
2798 {
2799 let (span, separator) = if let [.., last] = bounds {
2800 (last.span().shrink_to_hi(), " +")
2801 } else {
2802 (generics.span.shrink_to_hi(), ":")
2803 };
2804 err.span_suggestion_verbose(
2805 span,
2806 "consider relaxing the implicit `Sized` restriction",
2807 format!("{separator} ?Sized"),
2808 Applicability::MachineApplicable,
2809 );
2810 }
2811 }
2812 if let DefKind::Trait = tcx.def_kind(item_def_id)
2813 && !visible_item
2814 {
2815 note = Some(format!(
2816 "`{short_item_name}` is a \"sealed trait\", because to implement it \
2817 you also need to implement `{}`, which is not accessible; this is \
2818 usually done to force you to use one of the provided types that \
2819 already implement it",
2820 with_no_trimmed_paths!(tcx.def_path_str(def_id)),
2821 ));
2822 let impls_of = tcx.trait_impls_of(def_id);
2823 let impls = impls_of
2824 .non_blanket_impls()
2825 .values()
2826 .flatten()
2827 .chain(impls_of.blanket_impls().iter())
2828 .collect::<Vec<_>>();
2829 if !impls.is_empty() {
2830 let len = impls.len();
2831 let mut types = impls
2832 .iter()
2833 .map(|t| {
2834 with_no_trimmed_paths!(format!(
2835 " {}",
2836 tcx.type_of(*t).instantiate_identity(),
2837 ))
2838 })
2839 .collect::<Vec<_>>();
2840 let post = if types.len() > 9 {
2841 types.truncate(8);
2842 format!("\nand {} others", len - 8)
2843 } else {
2844 String::new()
2845 };
2846 help = Some(format!(
2847 "the following type{} implement{} the trait:\n{}{post}",
2848 pluralize!(len),
2849 if len == 1 { "s" } else { "" },
2850 types.join("\n"),
2851 ));
2852 }
2853 }
2854 }
2855 ty::ClauseKind::ConstArgHasType(..) => {
2856 let descr =
2857 format!("required by a const generic parameter in `{item_name}`");
2858 if span.is_visible(sm) {
2859 let msg = format!(
2860 "required by this const generic parameter in `{short_item_name}`"
2861 );
2862 multispan.push_span_label(span, msg);
2863 err.span_note(multispan, descr);
2864 } else {
2865 err.span_note(tcx.def_span(item_def_id), descr);
2866 }
2867 return;
2868 }
2869 _ => (),
2870 }
2871 }
2872 let descr = format!("required by {a} bound in `{item_name}`");
2873 if span.is_visible(sm) {
2874 let msg = format!("required by {this} in `{short_item_name}`");
2875 multispan.push_span_label(span, msg);
2876 err.span_note(multispan, descr);
2877 } else {
2878 err.span_note(tcx.def_span(item_def_id), descr);
2879 }
2880 if let Some(note) = note {
2881 err.note(note);
2882 }
2883 if let Some(help) = help {
2884 err.help(help);
2885 }
2886 }
2887 ObligationCauseCode::WhereClause(..)
2888 | ObligationCauseCode::WhereClauseInExpr(..)
2889 | ObligationCauseCode::HostEffectInExpr(..) => {
2890 }
2893 ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
2894 err.span_note(span, "required by a bound in an opaque type");
2895 if let Some(definition_def_id) = definition_def_id
2896 && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
2900 {
2901 err.span_note(
2904 tcx.def_span(definition_def_id),
2905 "this definition site has more where clauses than the opaque type",
2906 );
2907 }
2908 }
2909 ObligationCauseCode::Coercion { source, target } => {
2910 let source =
2911 tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
2912 let target =
2913 tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
2914 err.note(with_forced_trimmed_paths!(format!(
2915 "required for the cast from `{source}` to `{target}`",
2916 )));
2917 }
2918 ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
2919 err.note(
2920 "the `Copy` trait is required because this value will be copied for each element of the array",
2921 );
2922 let sm = tcx.sess.source_map();
2923 if matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
2924 && let Ok(snip) = sm.span_to_snippet(elt_span)
2925 {
2926 err.span_suggestion(
2927 elt_span,
2928 "create an inline `const` block",
2929 format!("const {{ {snip} }}"),
2930 Applicability::MachineApplicable,
2931 );
2932 } else {
2933 err.help("consider using `core::array::from_fn` to initialize the array");
2935 err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
2936 }
2937 }
2938 ObligationCauseCode::VariableType(hir_id) => {
2939 if let Some(typeck_results) = &self.typeck_results
2940 && let Some(ty) = typeck_results.node_type_opt(hir_id)
2941 && let ty::Error(_) = ty.kind()
2942 {
2943 err.note(format!(
2944 "`{predicate}` isn't satisfied, but the type of this pattern is \
2945 `{{type error}}`",
2946 ));
2947 err.downgrade_to_delayed_bug();
2948 }
2949 let mut local = true;
2950 match tcx.parent_hir_node(hir_id) {
2951 Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
2952 err.span_suggestion_verbose(
2953 ty.span.shrink_to_lo(),
2954 "consider borrowing here",
2955 "&",
2956 Applicability::MachineApplicable,
2957 );
2958 }
2959 Node::LetStmt(hir::LetStmt {
2960 init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
2961 ..
2962 }) => {
2963 err.span_suggestion_verbose(
2967 span.shrink_to_lo(),
2968 "consider borrowing here",
2969 "&",
2970 Applicability::MachineApplicable,
2971 );
2972 }
2973 Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
2974 suggest_remove_deref(err, &expr);
2977 }
2978 Node::Param(param) => {
2979 err.span_suggestion_verbose(
2980 param.ty_span.shrink_to_lo(),
2981 "function arguments must have a statically known size, borrowed types \
2982 always have a known size",
2983 "&",
2984 Applicability::MachineApplicable,
2985 );
2986 local = false;
2987 }
2988 _ => {}
2989 }
2990 if local {
2991 err.note("all local variables must have a statically known size");
2992 }
2993 if !tcx.features().unsized_locals() {
2994 err.help("unsized locals are gated as an unstable feature");
2995 }
2996 }
2997 ObligationCauseCode::SizedArgumentType(hir_id) => {
2998 let mut ty = None;
2999 let borrowed_msg = "function arguments must have a statically known size, borrowed \
3000 types always have a known size";
3001 if let Some(hir_id) = hir_id
3002 && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
3003 && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
3004 && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
3005 {
3006 ty = Some(t);
3014 } else if let Some(hir_id) = hir_id
3015 && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
3016 {
3017 ty = Some(t);
3018 }
3019 if let Some(ty) = ty {
3020 match ty.kind {
3021 hir::TyKind::TraitObject(traits, _) => {
3022 let (span, kw) = match traits {
3023 [first, ..] if first.span.lo() == ty.span.lo() => {
3024 (ty.span.shrink_to_lo(), "dyn ")
3026 }
3027 [first, ..] => (ty.span.until(first.span), ""),
3028 [] => span_bug!(ty.span, "trait object with no traits: {ty:?}"),
3029 };
3030 let needs_parens = traits.len() != 1;
3031 err.span_suggestion_verbose(
3032 span,
3033 "you can use `impl Trait` as the argument type",
3034 "impl ",
3035 Applicability::MaybeIncorrect,
3036 );
3037 let sugg = if !needs_parens {
3038 vec![(span.shrink_to_lo(), format!("&{kw}"))]
3039 } else {
3040 vec![
3041 (span.shrink_to_lo(), format!("&({kw}")),
3042 (ty.span.shrink_to_hi(), ")".to_string()),
3043 ]
3044 };
3045 err.multipart_suggestion_verbose(
3046 borrowed_msg,
3047 sugg,
3048 Applicability::MachineApplicable,
3049 );
3050 }
3051 hir::TyKind::Slice(_ty) => {
3052 err.span_suggestion_verbose(
3053 ty.span.shrink_to_lo(),
3054 "function arguments must have a statically known size, borrowed \
3055 slices always have a known size",
3056 "&",
3057 Applicability::MachineApplicable,
3058 );
3059 }
3060 hir::TyKind::Path(_) => {
3061 err.span_suggestion_verbose(
3062 ty.span.shrink_to_lo(),
3063 borrowed_msg,
3064 "&",
3065 Applicability::MachineApplicable,
3066 );
3067 }
3068 _ => {}
3069 }
3070 } else {
3071 err.note("all function arguments must have a statically known size");
3072 }
3073 if tcx.sess.opts.unstable_features.is_nightly_build()
3074 && !tcx.features().unsized_fn_params()
3075 {
3076 err.help("unsized fn params are gated as an unstable feature");
3077 }
3078 }
3079 ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
3080 err.note("the return type of a function must have a statically known size");
3081 }
3082 ObligationCauseCode::SizedYieldType => {
3083 err.note("the yield type of a coroutine must have a statically known size");
3084 }
3085 ObligationCauseCode::AssignmentLhsSized => {
3086 err.note("the left-hand-side of an assignment must have a statically known size");
3087 }
3088 ObligationCauseCode::TupleInitializerSized => {
3089 err.note("tuples must have a statically known size to be initialized");
3090 }
3091 ObligationCauseCode::StructInitializerSized => {
3092 err.note("structs must have a statically known size to be initialized");
3093 }
3094 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
3095 match *item {
3096 AdtKind::Struct => {
3097 if last {
3098 err.note(
3099 "the last field of a packed struct may only have a \
3100 dynamically sized type if it does not need drop to be run",
3101 );
3102 } else {
3103 err.note(
3104 "only the last field of a struct may have a dynamically sized type",
3105 );
3106 }
3107 }
3108 AdtKind::Union => {
3109 err.note("no field of a union may have a dynamically sized type");
3110 }
3111 AdtKind::Enum => {
3112 err.note("no field of an enum variant may have a dynamically sized type");
3113 }
3114 }
3115 err.help("change the field's type to have a statically known size");
3116 err.span_suggestion(
3117 span.shrink_to_lo(),
3118 "borrowed types always have a statically known size",
3119 "&",
3120 Applicability::MachineApplicable,
3121 );
3122 err.multipart_suggestion(
3123 "the `Box` type always has a statically known size and allocates its contents \
3124 in the heap",
3125 vec![
3126 (span.shrink_to_lo(), "Box<".to_string()),
3127 (span.shrink_to_hi(), ">".to_string()),
3128 ],
3129 Applicability::MachineApplicable,
3130 );
3131 }
3132 ObligationCauseCode::ConstSized => {
3133 err.note("constant expressions must have a statically known size");
3134 }
3135 ObligationCauseCode::InlineAsmSized => {
3136 err.note("all inline asm arguments must have a statically known size");
3137 }
3138 ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
3139 err.note(
3140 "all values captured by value by a closure must have a statically known size",
3141 );
3142 let hir::ExprKind::Closure(closure) =
3143 tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
3144 else {
3145 bug!("expected closure in SizedClosureCapture obligation");
3146 };
3147 if let hir::CaptureBy::Value { .. } = closure.capture_clause
3148 && let Some(span) = closure.fn_arg_span
3149 {
3150 err.span_label(span, "this closure captures all values by move");
3151 }
3152 }
3153 ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
3154 let what = match tcx.coroutine_kind(coroutine_def_id) {
3155 None
3156 | Some(hir::CoroutineKind::Coroutine(_))
3157 | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
3158 "yield"
3159 }
3160 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3161 "await"
3162 }
3163 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
3164 "yield`/`await"
3165 }
3166 };
3167 err.note(format!(
3168 "all values live across `{what}` must have a statically known size"
3169 ));
3170 }
3171 ObligationCauseCode::SharedStatic => {
3172 err.note("shared static variables must have a type that implements `Sync`");
3173 }
3174 ObligationCauseCode::BuiltinDerived(ref data) => {
3175 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3176 let ty = parent_trait_ref.skip_binder().self_ty();
3177 if parent_trait_ref.references_error() {
3178 err.downgrade_to_delayed_bug();
3181 return;
3182 }
3183
3184 let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
3187 false
3188 } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
3189 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3190 let nested_ty = parent_trait_ref.skip_binder().self_ty();
3191 matches!(nested_ty.kind(), ty::Coroutine(..))
3192 || matches!(nested_ty.kind(), ty::Closure(..))
3193 } else {
3194 false
3195 };
3196
3197 if !is_upvar_tys_infer_tuple {
3198 let ty_str = tcx.short_string(ty, err.long_ty_path());
3199 let msg = format!("required because it appears within the type `{ty_str}`");
3200 match ty.kind() {
3201 ty::Adt(def, _) => match tcx.opt_item_ident(def.did()) {
3202 Some(ident) => {
3203 err.span_note(ident.span, msg);
3204 }
3205 None => {
3206 err.note(msg);
3207 }
3208 },
3209 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
3210 let is_future = tcx.ty_is_opaque_future(ty);
3213 debug!(
3214 ?obligated_types,
3215 ?is_future,
3216 "note_obligation_cause_code: check for async fn"
3217 );
3218 if is_future
3219 && obligated_types.last().is_some_and(|ty| match ty.kind() {
3220 ty::Coroutine(last_def_id, ..) => {
3221 tcx.coroutine_is_async(*last_def_id)
3222 }
3223 _ => false,
3224 })
3225 {
3226 } else {
3228 err.span_note(tcx.def_span(def_id), msg);
3229 }
3230 }
3231 ty::Coroutine(def_id, _) => {
3232 let sp = tcx.def_span(def_id);
3233
3234 let kind = tcx.coroutine_kind(def_id).unwrap();
3236 err.span_note(
3237 sp,
3238 with_forced_trimmed_paths!(format!(
3239 "required because it's used within this {kind:#}",
3240 )),
3241 );
3242 }
3243 ty::CoroutineWitness(..) => {
3244 }
3247 ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
3248 err.span_note(
3249 tcx.def_span(def_id),
3250 "required because it's used within this closure",
3251 );
3252 }
3253 ty::Str => {
3254 err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
3255 }
3256 _ => {
3257 err.note(msg);
3258 }
3259 };
3260 }
3261
3262 obligated_types.push(ty);
3263
3264 let parent_predicate = parent_trait_ref;
3265 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
3266 ensure_sufficient_stack(|| {
3268 self.note_obligation_cause_code(
3269 body_id,
3270 err,
3271 parent_predicate,
3272 param_env,
3273 &data.parent_code,
3274 obligated_types,
3275 seen_requirements,
3276 )
3277 });
3278 } else {
3279 ensure_sufficient_stack(|| {
3280 self.note_obligation_cause_code(
3281 body_id,
3282 err,
3283 parent_predicate,
3284 param_env,
3285 cause_code.peel_derives(),
3286 obligated_types,
3287 seen_requirements,
3288 )
3289 });
3290 }
3291 }
3292 ObligationCauseCode::ImplDerived(ref data) => {
3293 let mut parent_trait_pred =
3294 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3295 let parent_def_id = parent_trait_pred.def_id();
3296 let self_ty_str =
3297 tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
3298 let trait_name = parent_trait_pred.print_modifiers_and_trait_path().to_string();
3299 let msg = format!("required for `{self_ty_str}` to implement `{trait_name}`");
3300 let mut is_auto_trait = false;
3301 match tcx.hir().get_if_local(data.impl_or_alias_def_id) {
3302 Some(Node::Item(hir::Item {
3303 kind: hir::ItemKind::Trait(is_auto, ..),
3304 ident,
3305 ..
3306 })) => {
3307 is_auto_trait = matches!(is_auto, hir::IsAuto::Yes);
3310 err.span_note(ident.span, msg);
3311 }
3312 Some(Node::Item(hir::Item {
3313 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
3314 ..
3315 })) => {
3316 let mut spans = Vec::with_capacity(2);
3317 if let Some(trait_ref) = of_trait {
3318 spans.push(trait_ref.path.span);
3319 }
3320 spans.push(self_ty.span);
3321 let mut spans: MultiSpan = spans.into();
3322 if matches!(
3323 self_ty.span.ctxt().outer_expn_data().kind,
3324 ExpnKind::Macro(MacroKind::Derive, _)
3325 ) || matches!(
3326 of_trait.as_ref().map(|t| t.path.span.ctxt().outer_expn_data().kind),
3327 Some(ExpnKind::Macro(MacroKind::Derive, _))
3328 ) {
3329 spans.push_span_label(
3330 data.span,
3331 "unsatisfied trait bound introduced in this `derive` macro",
3332 );
3333 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
3334 spans.push_span_label(
3335 data.span,
3336 "unsatisfied trait bound introduced here",
3337 );
3338 }
3339 err.span_note(spans, msg);
3340 point_at_assoc_type_restriction(
3341 tcx,
3342 err,
3343 &self_ty_str,
3344 &trait_name,
3345 predicate,
3346 &generics,
3347 &data,
3348 );
3349 }
3350 _ => {
3351 err.note(msg);
3352 }
3353 };
3354
3355 let mut parent_predicate = parent_trait_pred;
3356 let mut data = &data.derived;
3357 let mut count = 0;
3358 seen_requirements.insert(parent_def_id);
3359 if is_auto_trait {
3360 while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
3363 let child_trait_ref =
3364 self.resolve_vars_if_possible(derived.parent_trait_pred);
3365 let child_def_id = child_trait_ref.def_id();
3366 if seen_requirements.insert(child_def_id) {
3367 break;
3368 }
3369 data = derived;
3370 parent_predicate = child_trait_ref.upcast(tcx);
3371 parent_trait_pred = child_trait_ref;
3372 }
3373 }
3374 while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
3375 let child_trait_pred =
3377 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3378 let child_def_id = child_trait_pred.def_id();
3379 if seen_requirements.insert(child_def_id) {
3380 break;
3381 }
3382 count += 1;
3383 data = &child.derived;
3384 parent_predicate = child_trait_pred.upcast(tcx);
3385 parent_trait_pred = child_trait_pred;
3386 }
3387 if count > 0 {
3388 err.note(format!(
3389 "{} redundant requirement{} hidden",
3390 count,
3391 pluralize!(count)
3392 ));
3393 let self_ty = tcx.short_string(
3394 parent_trait_pred.skip_binder().self_ty(),
3395 err.long_ty_path(),
3396 );
3397 err.note(format!(
3398 "required for `{self_ty}` to implement `{}`",
3399 parent_trait_pred.print_modifiers_and_trait_path()
3400 ));
3401 }
3402 ensure_sufficient_stack(|| {
3404 self.note_obligation_cause_code(
3405 body_id,
3406 err,
3407 parent_predicate,
3408 param_env,
3409 &data.parent_code,
3410 obligated_types,
3411 seen_requirements,
3412 )
3413 });
3414 }
3415 ObligationCauseCode::ImplDerivedHost(ref data) => {
3416 let self_ty =
3417 self.resolve_vars_if_possible(data.derived.parent_host_pred.self_ty());
3418 let msg = format!(
3419 "required for `{self_ty}` to implement `{} {}`",
3420 data.derived.parent_host_pred.skip_binder().constness,
3421 data.derived
3422 .parent_host_pred
3423 .map_bound(|pred| pred.trait_ref)
3424 .print_only_trait_path(),
3425 );
3426 match tcx.hir().get_if_local(data.impl_def_id) {
3427 Some(Node::Item(hir::Item {
3428 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
3429 ..
3430 })) => {
3431 let mut spans = vec![self_ty.span];
3432 spans.extend(of_trait.as_ref().map(|t| t.path.span));
3433 let mut spans: MultiSpan = spans.into();
3434 spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
3435 err.span_note(spans, msg);
3436 }
3437 _ => {
3438 err.note(msg);
3439 }
3440 }
3441 ensure_sufficient_stack(|| {
3442 self.note_obligation_cause_code(
3443 body_id,
3444 err,
3445 data.derived.parent_host_pred,
3446 param_env,
3447 &data.derived.parent_code,
3448 obligated_types,
3449 seen_requirements,
3450 )
3451 });
3452 }
3453 ObligationCauseCode::BuiltinDerivedHost(ref data) => {
3454 ensure_sufficient_stack(|| {
3455 self.note_obligation_cause_code(
3456 body_id,
3457 err,
3458 data.parent_host_pred,
3459 param_env,
3460 &data.parent_code,
3461 obligated_types,
3462 seen_requirements,
3463 )
3464 });
3465 }
3466 ObligationCauseCode::WellFormedDerived(ref data) => {
3467 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3468 let parent_predicate = parent_trait_ref;
3469 ensure_sufficient_stack(|| {
3471 self.note_obligation_cause_code(
3472 body_id,
3473 err,
3474 parent_predicate,
3475 param_env,
3476 &data.parent_code,
3477 obligated_types,
3478 seen_requirements,
3479 )
3480 });
3481 }
3482 ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
3483 ensure_sufficient_stack(|| {
3485 self.note_obligation_cause_code(
3486 body_id,
3487 err,
3488 predicate,
3489 param_env,
3490 nested,
3491 obligated_types,
3492 seen_requirements,
3493 )
3494 });
3495 let mut multispan = MultiSpan::from(span);
3496 multispan.push_span_label(span, "required by this bound");
3497 err.span_note(
3498 multispan,
3499 format!("required by a bound on the type alias `{}`", tcx.item_name(def_id)),
3500 );
3501 }
3502 ObligationCauseCode::FunctionArg {
3503 arg_hir_id, call_hir_id, ref parent_code, ..
3504 } => {
3505 self.note_function_argument_obligation(
3506 body_id,
3507 err,
3508 arg_hir_id,
3509 parent_code,
3510 param_env,
3511 predicate,
3512 call_hir_id,
3513 );
3514 ensure_sufficient_stack(|| {
3515 self.note_obligation_cause_code(
3516 body_id,
3517 err,
3518 predicate,
3519 param_env,
3520 parent_code,
3521 obligated_types,
3522 seen_requirements,
3523 )
3524 });
3525 }
3526 ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
3529 if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
3530 ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
3531 let item_name = tcx.item_name(trait_item_def_id);
3532 let msg = format!(
3533 "the requirement `{predicate}` appears on the `impl`'s {kind} \
3534 `{item_name}` but not on the corresponding trait's {kind}",
3535 );
3536 let sp = tcx
3537 .opt_item_ident(trait_item_def_id)
3538 .map(|i| i.span)
3539 .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
3540 let mut assoc_span: MultiSpan = sp.into();
3541 assoc_span.push_span_label(
3542 sp,
3543 format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3544 );
3545 if let Some(ident) = tcx
3546 .opt_associated_item(trait_item_def_id)
3547 .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
3548 {
3549 assoc_span.push_span_label(ident.span, "in this trait");
3550 }
3551 err.span_note(assoc_span, msg);
3552 }
3553 ObligationCauseCode::TrivialBound => {
3554 err.help("see issue #48214");
3555 tcx.disabled_nightly_features(
3556 err,
3557 Some(tcx.local_def_id_to_hir_id(body_id)),
3558 [(String::new(), sym::trivial_bounds)],
3559 );
3560 }
3561 ObligationCauseCode::OpaqueReturnType(expr_info) => {
3562 let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
3563 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3564 let expr = tcx.hir().expect_expr(hir_id);
3565 (expr_ty, expr)
3566 } else if let Some(body_id) = tcx.hir_node_by_def_id(body_id).body_id()
3567 && let body = tcx.hir().body(body_id)
3568 && let hir::ExprKind::Block(block, _) = body.value.kind
3569 && let Some(expr) = block.expr
3570 && let Some(expr_ty) = self
3571 .typeck_results
3572 .as_ref()
3573 .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
3574 && let Some(pred) = predicate.as_clause()
3575 && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
3576 && self.can_eq(param_env, pred.self_ty(), expr_ty)
3577 {
3578 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3579 (expr_ty, expr)
3580 } else {
3581 return;
3582 };
3583 err.span_label(
3584 expr.span,
3585 with_forced_trimmed_paths!(format!(
3586 "return type was inferred to be `{expr_ty}` here",
3587 )),
3588 );
3589 suggest_remove_deref(err, &expr);
3590 }
3591 }
3592 }
3593
3594 #[instrument(
3595 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3596 )]
3597 pub(super) fn suggest_await_before_try(
3598 &self,
3599 err: &mut Diag<'_>,
3600 obligation: &PredicateObligation<'tcx>,
3601 trait_pred: ty::PolyTraitPredicate<'tcx>,
3602 span: Span,
3603 ) {
3604 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
3605
3606 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3607 let impls_future = self.type_implements_trait(
3608 future_trait,
3609 [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
3610 obligation.param_env,
3611 );
3612 if !impls_future.must_apply_modulo_regions() {
3613 return;
3614 }
3615
3616 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3617 let projection_ty = trait_pred.map_bound(|trait_pred| {
3619 Ty::new_projection(
3620 self.tcx,
3621 item_def_id,
3622 [trait_pred.self_ty()],
3624 )
3625 });
3626 let InferOk { value: projection_ty, .. } =
3627 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3628
3629 debug!(
3630 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3631 );
3632 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3633 obligation.param_env,
3634 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3635 );
3636 debug!(try_trait_obligation = ?try_obligation);
3637 if self.predicate_may_hold(&try_obligation)
3638 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3639 && snippet.ends_with('?')
3640 {
3641 match self.tcx.coroutine_kind(obligation.cause.body_id) {
3642 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3643 err.span_suggestion_verbose(
3644 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3645 "consider `await`ing on the `Future`",
3646 ".await",
3647 Applicability::MaybeIncorrect,
3648 );
3649 }
3650 _ => {
3651 let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
3652 span.push_span_label(
3653 self.tcx.def_span(obligation.cause.body_id),
3654 "this is not `async`",
3655 );
3656 err.span_note(
3657 span,
3658 "this implements `Future` and its output type supports \
3659 `?`, but the future cannot be awaited in a synchronous function",
3660 );
3661 }
3662 }
3663 }
3664 }
3665
3666 pub(super) fn suggest_floating_point_literal(
3667 &self,
3668 obligation: &PredicateObligation<'tcx>,
3669 err: &mut Diag<'_>,
3670 trait_pred: ty::PolyTraitPredicate<'tcx>,
3671 ) {
3672 let rhs_span = match obligation.cause.code() {
3673 ObligationCauseCode::BinOp { rhs_span: Some(span), rhs_is_lit, .. } if *rhs_is_lit => {
3674 span
3675 }
3676 _ => return,
3677 };
3678 if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
3679 && let ty::Infer(InferTy::IntVar(_)) =
3680 trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
3681 {
3682 err.span_suggestion_verbose(
3683 rhs_span.shrink_to_hi(),
3684 "consider using a floating-point literal by writing it with `.0`",
3685 ".0",
3686 Applicability::MaybeIncorrect,
3687 );
3688 }
3689 }
3690
3691 pub fn suggest_derive(
3692 &self,
3693 obligation: &PredicateObligation<'tcx>,
3694 err: &mut Diag<'_>,
3695 trait_pred: ty::PolyTraitPredicate<'tcx>,
3696 ) {
3697 if trait_pred.polarity() == ty::PredicatePolarity::Negative {
3698 return;
3699 }
3700 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3701 return;
3702 };
3703 let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
3704 ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
3705 _ => return,
3706 };
3707 let can_derive = {
3708 let is_derivable_trait = match diagnostic_name {
3709 sym::Default => !adt.is_enum(),
3710 sym::PartialEq | sym::PartialOrd => {
3711 let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3712 trait_pred.skip_binder().self_ty() == rhs_ty
3713 }
3714 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
3715 _ => false,
3716 };
3717 is_derivable_trait &&
3718 adt.all_fields().all(|field| {
3720 let field_ty = ty::GenericArg::from(field.ty(self.tcx, args));
3721 let trait_args = match diagnostic_name {
3722 sym::PartialEq | sym::PartialOrd => {
3723 Some(field_ty)
3724 }
3725 _ => None,
3726 };
3727 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
3728 trait_ref: ty::TraitRef::new(self.tcx,
3729 trait_pred.def_id(),
3730 [field_ty].into_iter().chain(trait_args),
3731 ),
3732 ..*tr
3733 });
3734 let field_obl = Obligation::new(
3735 self.tcx,
3736 obligation.cause.clone(),
3737 obligation.param_env,
3738 trait_pred,
3739 );
3740 self.predicate_must_hold_modulo_regions(&field_obl)
3741 })
3742 };
3743 if can_derive {
3744 err.span_suggestion_verbose(
3745 self.tcx.def_span(adt.did()).shrink_to_lo(),
3746 format!(
3747 "consider annotating `{}` with `#[derive({})]`",
3748 trait_pred.skip_binder().self_ty(),
3749 diagnostic_name,
3750 ),
3751 format!("#[derive({diagnostic_name})]\n"),
3753 Applicability::MaybeIncorrect,
3754 );
3755 }
3756 }
3757
3758 pub(super) fn suggest_dereferencing_index(
3759 &self,
3760 obligation: &PredicateObligation<'tcx>,
3761 err: &mut Diag<'_>,
3762 trait_pred: ty::PolyTraitPredicate<'tcx>,
3763 ) {
3764 if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
3765 && self
3766 .tcx
3767 .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
3768 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
3769 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
3770 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
3771 {
3772 err.span_suggestion_verbose(
3773 obligation.cause.span.shrink_to_lo(),
3774 "dereference this index",
3775 '*',
3776 Applicability::MachineApplicable,
3777 );
3778 }
3779 }
3780
3781 fn note_function_argument_obligation<G: EmissionGuarantee>(
3782 &self,
3783 body_id: LocalDefId,
3784 err: &mut Diag<'_, G>,
3785 arg_hir_id: HirId,
3786 parent_code: &ObligationCauseCode<'tcx>,
3787 param_env: ty::ParamEnv<'tcx>,
3788 failed_pred: ty::Predicate<'tcx>,
3789 call_hir_id: HirId,
3790 ) {
3791 let tcx = self.tcx;
3792 if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
3793 && let Some(typeck_results) = &self.typeck_results
3794 {
3795 if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
3796 && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
3797 && let Some(failed_pred) = failed_pred.as_trait_clause()
3798 && let pred = failed_pred.map_bound(|pred| pred.with_self_ty(tcx, ty))
3799 && self.predicate_must_hold_modulo_regions(&Obligation::misc(
3800 tcx, expr.span, body_id, param_env, pred,
3801 ))
3802 && expr.span.hi() != rcvr.span.hi()
3803 {
3804 err.span_suggestion_verbose(
3805 expr.span.with_lo(rcvr.span.hi()),
3806 format!(
3807 "consider removing this method call, as the receiver has type `{ty}` and \
3808 `{pred}` trivially holds",
3809 ),
3810 "",
3811 Applicability::MaybeIncorrect,
3812 );
3813 }
3814 if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
3815 let inner_expr = expr.peel_blocks();
3816 let ty = typeck_results
3817 .expr_ty_adjusted_opt(inner_expr)
3818 .unwrap_or(Ty::new_misc_error(tcx));
3819 let span = inner_expr.span;
3820 if Some(span) != err.span.primary_span() {
3821 err.span_label(
3822 span,
3823 if ty.references_error() {
3824 String::new()
3825 } else {
3826 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
3827 format!("this tail expression is of type `{ty}`")
3828 },
3829 );
3830 if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
3831 && let ty::ClauseKind::Trait(pred) = clause
3832 && [
3833 tcx.lang_items().fn_once_trait(),
3834 tcx.lang_items().fn_mut_trait(),
3835 tcx.lang_items().fn_trait(),
3836 ]
3837 .contains(&Some(pred.def_id()))
3838 {
3839 if let [stmt, ..] = block.stmts
3840 && let hir::StmtKind::Semi(value) = stmt.kind
3841 && let hir::ExprKind::Closure(hir::Closure {
3842 body, fn_decl_span, ..
3843 }) = value.kind
3844 && let body = tcx.hir().body(*body)
3845 && !matches!(body.value.kind, hir::ExprKind::Block(..))
3846 {
3847 err.multipart_suggestion(
3850 "you might have meant to open the closure body instead of placing \
3851 a closure within a block",
3852 vec![
3853 (expr.span.with_hi(value.span.lo()), String::new()),
3854 (fn_decl_span.shrink_to_hi(), " {".to_string()),
3855 ],
3856 Applicability::MaybeIncorrect,
3857 );
3858 } else {
3859 err.span_suggestion_verbose(
3861 expr.span.shrink_to_lo(),
3862 "you might have meant to create the closure instead of a block",
3863 format!(
3864 "|{}| ",
3865 (0..pred.trait_ref.args.len() - 1)
3866 .map(|_| "_")
3867 .collect::<Vec<_>>()
3868 .join(", ")
3869 ),
3870 Applicability::MaybeIncorrect,
3871 );
3872 }
3873 }
3874 }
3875 }
3876
3877 let mut type_diffs = vec![];
3882 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = parent_code
3883 && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
3884 && let where_clauses =
3885 self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args)
3886 && let Some(where_pred) = where_clauses.predicates.get(*idx)
3887 {
3888 if let Some(where_pred) = where_pred.as_trait_clause()
3889 && let Some(failed_pred) = failed_pred.as_trait_clause()
3890 && where_pred.def_id() == failed_pred.def_id()
3891 {
3892 self.enter_forall(where_pred, |where_pred| {
3893 let failed_pred = self.instantiate_binder_with_fresh_vars(
3894 expr.span,
3895 BoundRegionConversionTime::FnCall,
3896 failed_pred,
3897 );
3898
3899 let zipped =
3900 iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
3901 for (expected, actual) in zipped {
3902 self.probe(|_| {
3903 match self
3904 .at(&ObligationCause::misc(expr.span, body_id), param_env)
3905 .eq(DefineOpaqueTypes::Yes, expected, actual)
3908 {
3909 Ok(_) => (), Err(err) => type_diffs.push(err),
3911 }
3912 })
3913 }
3914 })
3915 } else if let Some(where_pred) = where_pred.as_projection_clause()
3916 && let Some(failed_pred) = failed_pred.as_projection_clause()
3917 && let Some(found) = failed_pred.skip_binder().term.as_type()
3918 {
3919 type_diffs = vec![TypeError::Sorts(ty::error::ExpectedFound {
3920 expected: where_pred
3921 .skip_binder()
3922 .projection_term
3923 .expect_ty(self.tcx)
3924 .to_ty(self.tcx),
3925 found,
3926 })];
3927 }
3928 }
3929 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
3930 && let hir::Path { res: Res::Local(hir_id), .. } = path
3931 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
3932 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
3933 && let Some(binding_expr) = local.init
3934 {
3935 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
3939 } else {
3940 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
3941 }
3942 }
3943 let call_node = tcx.hir_node(call_hir_id);
3944 if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
3945 call_node
3946 {
3947 if Some(rcvr.span) == err.span.primary_span() {
3948 err.replace_span_with(path.ident.span, true);
3949 }
3950 }
3951
3952 if let Node::Expr(expr) = call_node {
3953 if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
3954 | hir::ExprKind::MethodCall(
3955 hir::PathSegment { ident: Ident { span, .. }, .. },
3956 ..,
3957 ) = expr.kind
3958 {
3959 if Some(*span) != err.span.primary_span() {
3960 err.span_label(*span, "required by a bound introduced by this call");
3961 }
3962 }
3963
3964 if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
3965 self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
3966 }
3967 }
3968 }
3969
3970 fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
3971 &self,
3972 failed_pred: ty::Predicate<'tcx>,
3973 param_env: ty::ParamEnv<'tcx>,
3974 err: &mut Diag<'_, G>,
3975 expr: &hir::Expr<'_>,
3976 ) {
3977 let tcx = self.tcx;
3978 let infcx = self.infcx;
3979 let Some(typeck_results) = self.typeck_results.as_ref() else { return };
3980
3981 let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
3983 return;
3984 };
3985 if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
3986 return;
3987 }
3988
3989 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. }))
3992 = failed_pred.kind().skip_binder()
3993 && tcx.is_fn_trait(trait_ref.def_id)
3994 && let [self_ty, found_ty] = trait_ref.args.as_slice()
3995 && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
3996 && let fn_sig @ ty::FnSig {
3997 abi: ExternAbi::Rust,
3998 c_variadic: false,
3999 safety: hir::Safety::Safe,
4000 ..
4001 } = fn_ty.fn_sig(tcx).skip_binder()
4002
4003 && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
4005 && !target_ty.has_escaping_bound_vars()
4006
4007 && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
4009 && let &[found_ty] = tys.as_slice()
4010 && !found_ty.has_escaping_bound_vars()
4011
4012 && let Some(deref_target_did) = tcx.lang_items().deref_target()
4014 && let projection = Ty::new_projection_from_args(tcx,deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
4015 && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(projection)
4016 && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
4017 && infcx.can_eq(param_env, deref_target, target_ty)
4018 {
4019 let help = if let hir::Mutability::Mut = needs_mut
4020 && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
4021 && infcx
4022 .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
4023 .must_apply_modulo_regions()
4024 {
4025 Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
4026 } else if let hir::Mutability::Not = needs_mut {
4027 Some(("call `Option::as_deref()` first", ".as_deref()"))
4028 } else {
4029 None
4030 };
4031
4032 if let Some((msg, sugg)) = help {
4033 err.span_suggestion_with_style(
4034 expr.span.shrink_to_hi(),
4035 msg,
4036 sugg,
4037 Applicability::MaybeIncorrect,
4038 SuggestionStyle::ShowAlways,
4039 );
4040 }
4041 }
4042 }
4043
4044 fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
4045 &self,
4046 assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
4047 typeck_results: &TypeckResults<'tcx>,
4048 type_diffs: &[TypeError<'tcx>],
4049 param_env: ty::ParamEnv<'tcx>,
4050 path_segment: &hir::PathSegment<'_>,
4051 args: &[hir::Expr<'_>],
4052 err: &mut Diag<'_, G>,
4053 ) {
4054 let tcx = self.tcx;
4055 for entry in assocs_in_this_method {
4058 let Some((_span, (def_id, ty))) = entry else {
4059 continue;
4060 };
4061 for diff in type_diffs {
4062 let TypeError::Sorts(expected_found) = diff else {
4063 continue;
4064 };
4065 if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
4066 && path_segment.ident.name == sym::map
4067 && self.can_eq(param_env, expected_found.found, *ty)
4068 && let [arg] = args
4069 && let hir::ExprKind::Closure(closure) = arg.kind
4070 {
4071 let body = tcx.hir().body(closure.body);
4072 if let hir::ExprKind::Block(block, None) = body.value.kind
4073 && let None = block.expr
4074 && let [.., stmt] = block.stmts
4075 && let hir::StmtKind::Semi(expr) = stmt.kind
4076 && expected_found.found.is_unit()
4080 && expr.span.hi() != stmt.span.hi()
4085 {
4086 err.span_suggestion_verbose(
4087 expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
4088 "consider removing this semicolon",
4089 String::new(),
4090 Applicability::MachineApplicable,
4091 );
4092 }
4093 let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
4094 && let Some(expr) = block.expr
4095 {
4096 expr
4097 } else {
4098 body.value
4099 };
4100 if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
4101 && path_segment.ident.name == sym::clone
4102 && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
4103 && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
4104 && self.can_eq(param_env, expr_ty, rcvr_ty)
4105 && let ty::Ref(_, ty, _) = expr_ty.kind()
4106 {
4107 err.span_label(
4108 span,
4109 format!(
4110 "this method call is cloning the reference `{expr_ty}`, not \
4111 `{ty}` which doesn't implement `Clone`",
4112 ),
4113 );
4114 let ty::Param(..) = ty.kind() else {
4115 continue;
4116 };
4117 let hir = tcx.hir();
4118 let node = tcx.hir_node_by_def_id(hir.get_parent_item(expr.hir_id).def_id);
4119
4120 let pred = ty::Binder::dummy(ty::TraitPredicate {
4121 trait_ref: ty::TraitRef::new(
4122 tcx,
4123 tcx.require_lang_item(LangItem::Clone, Some(span)),
4124 [*ty],
4125 ),
4126 polarity: ty::PredicatePolarity::Positive,
4127 });
4128 let Some(generics) = node.generics() else {
4129 continue;
4130 };
4131 let Some(body_id) = node.body_id() else {
4132 continue;
4133 };
4134 suggest_restriction(
4135 tcx,
4136 hir.body_owner_def_id(body_id),
4137 generics,
4138 &format!("type parameter `{ty}`"),
4139 err,
4140 node.fn_sig(),
4141 None,
4142 pred,
4143 None,
4144 );
4145 }
4146 }
4147 }
4148 }
4149 }
4150
4151 fn point_at_chain<G: EmissionGuarantee>(
4152 &self,
4153 expr: &hir::Expr<'_>,
4154 typeck_results: &TypeckResults<'tcx>,
4155 type_diffs: Vec<TypeError<'tcx>>,
4156 param_env: ty::ParamEnv<'tcx>,
4157 err: &mut Diag<'_, G>,
4158 ) {
4159 let mut primary_spans = vec![];
4160 let mut span_labels = vec![];
4161
4162 let tcx = self.tcx;
4163
4164 let mut print_root_expr = true;
4165 let mut assocs = vec![];
4166 let mut expr = expr;
4167 let mut prev_ty = self.resolve_vars_if_possible(
4168 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4169 );
4170 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
4171 expr = rcvr_expr;
4175 let assocs_in_this_method =
4176 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
4177 self.look_for_iterator_item_mistakes(
4178 &assocs_in_this_method,
4179 typeck_results,
4180 &type_diffs,
4181 param_env,
4182 path_segment,
4183 args,
4184 err,
4185 );
4186 assocs.push(assocs_in_this_method);
4187 prev_ty = self.resolve_vars_if_possible(
4188 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4189 );
4190
4191 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4192 && let hir::Path { res: Res::Local(hir_id), .. } = path
4193 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4194 {
4195 let parent = self.tcx.parent_hir_node(binding.hir_id);
4196 if let hir::Node::LetStmt(local) = parent
4198 && let Some(binding_expr) = local.init
4199 {
4200 expr = binding_expr;
4202 }
4203 if let hir::Node::Param(param) = parent {
4204 let prev_ty = self.resolve_vars_if_possible(
4206 typeck_results
4207 .node_type_opt(param.hir_id)
4208 .unwrap_or(Ty::new_misc_error(tcx)),
4209 );
4210 let assocs_in_this_method = self.probe_assoc_types_at_expr(
4211 &type_diffs,
4212 param.ty_span,
4213 prev_ty,
4214 param.hir_id,
4215 param_env,
4216 );
4217 if assocs_in_this_method.iter().any(|a| a.is_some()) {
4218 assocs.push(assocs_in_this_method);
4219 print_root_expr = false;
4220 }
4221 break;
4222 }
4223 }
4224 }
4225 if let Some(ty) = typeck_results.expr_ty_opt(expr)
4228 && print_root_expr
4229 {
4230 let ty = with_forced_trimmed_paths!(self.ty_to_string(ty));
4231 span_labels.push((expr.span, format!("this expression has type `{ty}`")));
4235 };
4236 let mut assocs = assocs.into_iter().peekable();
4239 while let Some(assocs_in_method) = assocs.next() {
4240 let Some(prev_assoc_in_method) = assocs.peek() else {
4241 for entry in assocs_in_method {
4242 let Some((span, (assoc, ty))) = entry else {
4243 continue;
4244 };
4245 if primary_spans.is_empty()
4246 || type_diffs.iter().any(|diff| {
4247 let TypeError::Sorts(expected_found) = diff else {
4248 return false;
4249 };
4250 self.can_eq(param_env, expected_found.found, ty)
4251 })
4252 {
4253 primary_spans.push(span);
4259 }
4260 span_labels.push((
4261 span,
4262 with_forced_trimmed_paths!(format!(
4263 "`{}` is `{ty}` here",
4264 self.tcx.def_path_str(assoc),
4265 )),
4266 ));
4267 }
4268 break;
4269 };
4270 for (entry, prev_entry) in
4271 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
4272 {
4273 match (entry, prev_entry) {
4274 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
4275 let ty_str = with_forced_trimmed_paths!(self.ty_to_string(ty));
4276
4277 let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
4278 if !self.can_eq(param_env, ty, *prev_ty) {
4279 if type_diffs.iter().any(|diff| {
4280 let TypeError::Sorts(expected_found) = diff else {
4281 return false;
4282 };
4283 self.can_eq(param_env, expected_found.found, ty)
4284 }) {
4285 primary_spans.push(span);
4286 }
4287 span_labels
4288 .push((span, format!("`{assoc}` changed to `{ty_str}` here")));
4289 } else {
4290 span_labels.push((span, format!("`{assoc}` remains `{ty_str}` here")));
4291 }
4292 }
4293 (Some((span, (assoc, ty))), None) => {
4294 span_labels.push((
4295 span,
4296 with_forced_trimmed_paths!(format!(
4297 "`{}` is `{}` here",
4298 self.tcx.def_path_str(assoc),
4299 self.ty_to_string(ty),
4300 )),
4301 ));
4302 }
4303 (None, Some(_)) | (None, None) => {}
4304 }
4305 }
4306 }
4307 if !primary_spans.is_empty() {
4308 let mut multi_span: MultiSpan = primary_spans.into();
4309 for (span, label) in span_labels {
4310 multi_span.push_span_label(span, label);
4311 }
4312 err.span_note(
4313 multi_span,
4314 "the method call chain might not have had the expected associated types",
4315 );
4316 }
4317 }
4318
4319 fn probe_assoc_types_at_expr(
4320 &self,
4321 type_diffs: &[TypeError<'tcx>],
4322 span: Span,
4323 prev_ty: Ty<'tcx>,
4324 body_id: HirId,
4325 param_env: ty::ParamEnv<'tcx>,
4326 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
4327 let ocx = ObligationCtxt::new(self.infcx);
4328 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
4329 for diff in type_diffs {
4330 let TypeError::Sorts(expected_found) = diff else {
4331 continue;
4332 };
4333 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else {
4334 continue;
4335 };
4336
4337 let args = GenericArgs::for_item(self.tcx, proj.def_id, |param, _| {
4341 if param.index == 0 {
4342 debug_assert_matches!(param.kind, ty::GenericParamDefKind::Type { .. });
4343 return prev_ty.into();
4344 }
4345 self.var_for_def(span, param)
4346 });
4347 let ty = self.infcx.next_ty_var(span);
4351 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
4353 ty::ClauseKind::Projection(ty::ProjectionPredicate {
4354 projection_term: ty::AliasTerm::new_from_args(self.tcx, proj.def_id, args),
4355 term: ty.into(),
4356 }),
4357 ));
4358 let body_def_id = self.tcx.hir().enclosing_body_owner(body_id);
4359 ocx.register_obligation(Obligation::misc(
4361 self.tcx,
4362 span,
4363 body_def_id,
4364 param_env,
4365 projection,
4366 ));
4367 if ocx.select_where_possible().is_empty()
4368 && let ty = self.resolve_vars_if_possible(ty)
4369 && !ty.is_ty_var()
4370 {
4371 assocs_in_this_method.push(Some((span, (proj.def_id, ty))));
4372 } else {
4373 assocs_in_this_method.push(None);
4378 }
4379 }
4380 assocs_in_this_method
4381 }
4382
4383 pub(super) fn suggest_convert_to_slice(
4387 &self,
4388 err: &mut Diag<'_>,
4389 obligation: &PredicateObligation<'tcx>,
4390 trait_pred: ty::PolyTraitPredicate<'tcx>,
4391 candidate_impls: &[ImplCandidate<'tcx>],
4392 span: Span,
4393 ) {
4394 let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
4397 obligation.cause.code()
4398 else {
4399 return;
4400 };
4401
4402 let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
4407 ty::Array(element_ty, _) => (element_ty, None),
4408
4409 ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
4410 ty::Array(element_ty, _) => (element_ty, Some(mutability)),
4411 _ => return,
4412 },
4413
4414 _ => return,
4415 };
4416
4417 let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
4420 ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
4421 if matches!(*t.kind(), ty::Slice(e) if e == element_ty)
4422 && m == mutability.unwrap_or(m)
4423 {
4424 mutability = Some(m);
4426 true
4427 } else {
4428 false
4429 }
4430 }
4431 _ => false,
4432 };
4433
4434 if let Some(slice_ty) = candidate_impls
4436 .iter()
4437 .map(|trait_ref| trait_ref.trait_ref.self_ty())
4438 .find(|t| is_slice(*t))
4439 {
4440 let msg = format!("convert the array to a `{slice_ty}` slice instead");
4441
4442 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
4443 let mut suggestions = vec![];
4444 if snippet.starts_with('&') {
4445 } else if let Some(hir::Mutability::Mut) = mutability {
4446 suggestions.push((span.shrink_to_lo(), "&mut ".into()));
4447 } else {
4448 suggestions.push((span.shrink_to_lo(), "&".into()));
4449 }
4450 suggestions.push((span.shrink_to_hi(), "[..]".into()));
4451 err.multipart_suggestion_verbose(msg, suggestions, Applicability::MaybeIncorrect);
4452 } else {
4453 err.span_help(span, msg);
4454 }
4455 }
4456 }
4457
4458 pub(super) fn suggest_tuple_wrapping(
4463 &self,
4464 err: &mut Diag<'_>,
4465 root_obligation: &PredicateObligation<'tcx>,
4466 obligation: &PredicateObligation<'tcx>,
4467 ) {
4468 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
4469 return;
4470 };
4471
4472 let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
4473
4474 let trait_ref = root_pred.map_bound(|root_pred| {
4475 root_pred
4476 .trait_ref
4477 .with_self_ty(self.tcx, Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]))
4478 });
4479
4480 let obligation =
4481 Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
4482
4483 if self.predicate_must_hold_modulo_regions(&obligation) {
4484 let arg_span = self.tcx.hir().span(*arg_hir_id);
4485 err.multipart_suggestion_verbose(
4486 format!("use a unary tuple instead"),
4487 vec![(arg_span.shrink_to_lo(), "(".into()), (arg_span.shrink_to_hi(), ",)".into())],
4488 Applicability::MaybeIncorrect,
4489 );
4490 }
4491 }
4492
4493 pub(super) fn explain_hrtb_projection(
4494 &self,
4495 diag: &mut Diag<'_>,
4496 pred: ty::PolyTraitPredicate<'tcx>,
4497 param_env: ty::ParamEnv<'tcx>,
4498 cause: &ObligationCause<'tcx>,
4499 ) {
4500 if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
4501 {
4502 self.probe(|_| {
4503 let ocx = ObligationCtxt::new(self);
4504 self.enter_forall(pred, |pred| {
4505 let pred = ocx.normalize(&ObligationCause::dummy(), param_env, pred);
4506 ocx.register_obligation(Obligation::new(
4507 self.tcx,
4508 ObligationCause::dummy(),
4509 param_env,
4510 pred,
4511 ));
4512 });
4513 if !ocx.select_where_possible().is_empty() {
4514 return;
4516 }
4517
4518 if let ObligationCauseCode::FunctionArg {
4519 call_hir_id,
4520 arg_hir_id,
4521 parent_code: _,
4522 } = cause.code()
4523 {
4524 let arg_span = self.tcx.hir().span(*arg_hir_id);
4525 let mut sp: MultiSpan = arg_span.into();
4526
4527 sp.push_span_label(
4528 arg_span,
4529 "the trait solver is unable to infer the \
4530 generic types that should be inferred from this argument",
4531 );
4532 sp.push_span_label(
4533 self.tcx.hir().span(*call_hir_id),
4534 "add turbofish arguments to this call to \
4535 specify the types manually, even if it's redundant",
4536 );
4537 diag.span_note(
4538 sp,
4539 "this is a known limitation of the trait solver that \
4540 will be lifted in the future",
4541 );
4542 } else {
4543 let mut sp: MultiSpan = cause.span.into();
4544 sp.push_span_label(
4545 cause.span,
4546 "try adding turbofish arguments to this expression to \
4547 specify the types manually, even if it's redundant",
4548 );
4549 diag.span_note(
4550 sp,
4551 "this is a known limitation of the trait solver that \
4552 will be lifted in the future",
4553 );
4554 }
4555 });
4556 }
4557 }
4558
4559 pub(super) fn suggest_desugaring_async_fn_in_trait(
4560 &self,
4561 err: &mut Diag<'_>,
4562 trait_pred: ty::PolyTraitPredicate<'tcx>,
4563 ) {
4564 if self.tcx.features().return_type_notation() {
4566 return;
4567 }
4568
4569 let trait_def_id = trait_pred.def_id();
4570
4571 if !self.tcx.trait_is_auto(trait_def_id) {
4573 return;
4574 }
4575
4576 let ty::Alias(ty::Projection, alias_ty) = trait_pred.self_ty().skip_binder().kind() else {
4578 return;
4579 };
4580 let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
4581 self.tcx.opt_rpitit_info(alias_ty.def_id)
4582 else {
4583 return;
4584 };
4585
4586 let auto_trait = self.tcx.def_path_str(trait_def_id);
4587 let Some(fn_def_id) = fn_def_id.as_local() else {
4589 if self.tcx.asyncness(fn_def_id).is_async() {
4591 err.span_note(
4592 self.tcx.def_span(fn_def_id),
4593 format!(
4594 "`{}::{}` is an `async fn` in trait, which does not \
4595 automatically imply that its future is `{auto_trait}`",
4596 alias_ty.trait_ref(self.tcx),
4597 self.tcx.item_name(fn_def_id)
4598 ),
4599 );
4600 }
4601 return;
4602 };
4603 let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
4604 return;
4605 };
4606
4607 let (sig, body) = item.expect_fn();
4609 let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
4610 sig.decl.output
4611 else {
4612 return;
4614 };
4615
4616 if opaq_def.def_id.to_def_id() != opaque_def_id {
4619 return;
4620 }
4621
4622 let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
4623 self.tcx,
4624 *sig,
4625 *body,
4626 opaque_def_id.expect_local(),
4627 &format!(" + {auto_trait}"),
4628 ) else {
4629 return;
4630 };
4631
4632 let function_name = self.tcx.def_path_str(fn_def_id);
4633 err.multipart_suggestion(
4634 format!(
4635 "`{auto_trait}` can be made part of the associated future's \
4636 guarantees for all implementations of `{function_name}`"
4637 ),
4638 sugg,
4639 Applicability::MachineApplicable,
4640 );
4641 }
4642
4643 pub fn ty_kind_suggestion(
4644 &self,
4645 param_env: ty::ParamEnv<'tcx>,
4646 ty: Ty<'tcx>,
4647 ) -> Option<String> {
4648 let tcx = self.infcx.tcx;
4649 let implements_default = |ty| {
4650 let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
4651 return false;
4652 };
4653 self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
4654 };
4655
4656 Some(match *ty.kind() {
4657 ty::Never | ty::Error(_) => return None,
4658 ty::Bool => "false".to_string(),
4659 ty::Char => "\'x\'".to_string(),
4660 ty::Int(_) | ty::Uint(_) => "42".into(),
4661 ty::Float(_) => "3.14159".into(),
4662 ty::Slice(_) => "[]".to_string(),
4663 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
4664 "vec![]".to_string()
4665 }
4666 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
4667 "String::new()".to_string()
4668 }
4669 ty::Adt(def, args) if def.is_box() => {
4670 format!("Box::new({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
4671 }
4672 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
4673 "None".to_string()
4674 }
4675 ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
4676 format!("Ok({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
4677 }
4678 ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
4679 ty::Ref(_, ty, mutability) => {
4680 if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
4681 "\"\"".to_string()
4682 } else {
4683 let ty = self.ty_kind_suggestion(param_env, ty)?;
4684 format!("&{}{ty}", mutability.prefix_str())
4685 }
4686 }
4687 ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
4688 if len == 0 {
4689 "[]".to_string()
4690 } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
4691 format!("[{}; {}]", self.ty_kind_suggestion(param_env, ty)?, len)
4693 } else {
4694 "/* value */".to_string()
4695 }
4696 }
4697 ty::Tuple(tys) => format!(
4698 "({}{})",
4699 tys.iter()
4700 .map(|ty| self.ty_kind_suggestion(param_env, ty))
4701 .collect::<Option<Vec<String>>>()?
4702 .join(", "),
4703 if tys.len() == 1 { "," } else { "" }
4704 ),
4705 _ => "/* value */".to_string(),
4706 })
4707 }
4708
4709 pub(super) fn suggest_add_result_as_return_type(
4713 &self,
4714 obligation: &PredicateObligation<'tcx>,
4715 err: &mut Diag<'_>,
4716 trait_pred: ty::PolyTraitPredicate<'tcx>,
4717 ) {
4718 if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
4719 return;
4720 }
4721
4722 fn choose_suggest_items<'tcx, 'hir>(
4729 tcx: TyCtxt<'tcx>,
4730 node: hir::Node<'hir>,
4731 ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
4732 match node {
4733 hir::Node::Item(item)
4734 if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
4735 {
4736 Some((sig.decl, body_id))
4737 }
4738 hir::Node::ImplItem(item)
4739 if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
4740 {
4741 let parent = tcx.parent_hir_node(item.hir_id());
4742 if let hir::Node::Item(item) = parent
4743 && let hir::ItemKind::Impl(imp) = item.kind
4744 && imp.of_trait.is_none()
4745 {
4746 return Some((sig.decl, body_id));
4747 }
4748 None
4749 }
4750 _ => None,
4751 }
4752 }
4753
4754 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
4755 if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
4756 && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
4757 && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
4758 && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
4759 && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4760 && self.tcx.is_diagnostic_item(sym::Result, def.did())
4761 {
4762 let mut sugg_spans =
4763 vec![(ret_span, " -> Result<(), Box<dyn std::error::Error>>".to_string())];
4764 let body = self.tcx.hir().body(body_id);
4765 if let hir::ExprKind::Block(b, _) = body.value.kind
4766 && b.expr.is_none()
4767 {
4768 let span = self.tcx.sess.source_map().end_point(b.span);
4770 sugg_spans.push((
4771 span.shrink_to_lo(),
4772 format!(
4773 "{}{}",
4774 " Ok(())\n",
4775 self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
4776 ),
4777 ));
4778 }
4779 err.multipart_suggestion_verbose(
4780 format!("consider adding return type"),
4781 sugg_spans,
4782 Applicability::MaybeIncorrect,
4783 );
4784 }
4785 }
4786
4787 #[instrument(level = "debug", skip_all)]
4788 pub(super) fn suggest_unsized_bound_if_applicable(
4789 &self,
4790 err: &mut Diag<'_>,
4791 obligation: &PredicateObligation<'tcx>,
4792 ) {
4793 let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
4794 obligation.predicate.kind().skip_binder()
4795 else {
4796 return;
4797 };
4798 let (ObligationCauseCode::WhereClause(item_def_id, span)
4799 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
4800 *obligation.cause.code().peel_derives()
4801 else {
4802 return;
4803 };
4804 if span.is_dummy() {
4805 return;
4806 }
4807 debug!(?pred, ?item_def_id, ?span);
4808
4809 let (Some(node), true) = (
4810 self.tcx.hir().get_if_local(item_def_id),
4811 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
4812 ) else {
4813 return;
4814 };
4815
4816 let Some(generics) = node.generics() else {
4817 return;
4818 };
4819 let sized_trait = self.tcx.lang_items().sized_trait();
4820 debug!(?generics.params);
4821 debug!(?generics.predicates);
4822 let Some(param) = generics.params.iter().find(|param| param.span == span) else {
4823 return;
4824 };
4825 let explicitly_sized = generics
4828 .bounds_for_param(param.def_id)
4829 .flat_map(|bp| bp.bounds)
4830 .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
4831 if explicitly_sized {
4832 return;
4833 }
4834 debug!(?param);
4835 match node {
4836 hir::Node::Item(
4837 item @ hir::Item {
4838 kind:
4840 hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
4841 ..
4842 },
4843 ) => {
4844 if self.suggest_indirection_for_unsized(err, item, param) {
4845 return;
4846 }
4847 }
4848 _ => {}
4849 };
4850
4851 let (span, separator, open_paren_sp) =
4853 if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
4854 (s, " +", open_paren_sp)
4855 } else {
4856 (param.name.ident().span.shrink_to_hi(), ":", None)
4857 };
4858
4859 let mut suggs = vec![];
4860 let suggestion = format!("{separator} ?Sized");
4861
4862 if let Some(open_paren_sp) = open_paren_sp {
4863 suggs.push((open_paren_sp, "(".to_string()));
4864 suggs.push((span, format!("){suggestion}")));
4865 } else {
4866 suggs.push((span, suggestion));
4867 }
4868
4869 err.multipart_suggestion_verbose(
4870 "consider relaxing the implicit `Sized` restriction",
4871 suggs,
4872 Applicability::MachineApplicable,
4873 );
4874 }
4875
4876 fn suggest_indirection_for_unsized(
4877 &self,
4878 err: &mut Diag<'_>,
4879 item: &hir::Item<'tcx>,
4880 param: &hir::GenericParam<'tcx>,
4881 ) -> bool {
4882 let mut visitor =
4886 FindTypeParam { param: param.name.ident().name, invalid_spans: vec![], nested: false };
4887 visitor.visit_item(item);
4888 if visitor.invalid_spans.is_empty() {
4889 return false;
4890 }
4891 let mut multispan: MultiSpan = param.span.into();
4892 multispan.push_span_label(
4893 param.span,
4894 format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
4895 );
4896 for sp in visitor.invalid_spans {
4897 multispan.push_span_label(
4898 sp,
4899 format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
4900 );
4901 }
4902 err.span_help(
4903 multispan,
4904 format!(
4905 "you could relax the implicit `Sized` bound on `{T}` if it were \
4906 used through indirection like `&{T}` or `Box<{T}>`",
4907 T = param.name.ident(),
4908 ),
4909 );
4910 true
4911 }
4912}
4913
4914fn hint_missing_borrow<'tcx>(
4916 infcx: &InferCtxt<'tcx>,
4917 param_env: ty::ParamEnv<'tcx>,
4918 span: Span,
4919 found: Ty<'tcx>,
4920 expected: Ty<'tcx>,
4921 found_node: Node<'_>,
4922 err: &mut Diag<'_>,
4923) {
4924 if matches!(found_node, Node::TraitItem(..)) {
4925 return;
4926 }
4927
4928 let found_args = match found.kind() {
4929 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
4930 kind => {
4931 span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
4932 }
4933 };
4934 let expected_args = match expected.kind() {
4935 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
4936 kind => {
4937 span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
4938 }
4939 };
4940
4941 let Some(fn_decl) = found_node.fn_decl() else {
4943 return;
4944 };
4945
4946 let args = fn_decl.inputs.iter();
4947
4948 let mut to_borrow = Vec::new();
4949 let mut remove_borrow = Vec::new();
4950
4951 for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
4952 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
4953 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
4954
4955 if infcx.can_eq(param_env, found_ty, expected_ty) {
4956 if found_refs.len() < expected_refs.len()
4958 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
4959 {
4960 to_borrow.push((
4961 arg.span.shrink_to_lo(),
4962 expected_refs[..expected_refs.len() - found_refs.len()]
4963 .iter()
4964 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
4965 .collect::<Vec<_>>()
4966 .join(""),
4967 ));
4968 } else if found_refs.len() > expected_refs.len() {
4969 let mut span = arg.span.shrink_to_lo();
4970 let mut left = found_refs.len() - expected_refs.len();
4971 let mut ty = arg;
4972 while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
4973 && left > 0
4974 {
4975 span = span.with_hi(mut_ty.ty.span.lo());
4976 ty = mut_ty.ty;
4977 left -= 1;
4978 }
4979 let sugg = if left == 0 {
4980 (span, String::new())
4981 } else {
4982 (arg.span, expected_arg.to_string())
4983 };
4984 remove_borrow.push(sugg);
4985 }
4986 }
4987 }
4988
4989 if !to_borrow.is_empty() {
4990 err.subdiagnostic(errors::AdjustSignatureBorrow::Borrow { to_borrow });
4991 }
4992
4993 if !remove_borrow.is_empty() {
4994 err.subdiagnostic(errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
4995 }
4996}
4997
4998#[derive(Debug)]
5001pub struct SelfVisitor<'v> {
5002 pub paths: Vec<&'v hir::Ty<'v>>,
5003 pub name: Option<Symbol>,
5004}
5005
5006impl<'v> Visitor<'v> for SelfVisitor<'v> {
5007 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
5008 if let hir::TyKind::Path(path) = ty.kind
5009 && let hir::QPath::TypeRelative(inner_ty, segment) = path
5010 && (Some(segment.ident.name) == self.name || self.name.is_none())
5011 && let hir::TyKind::Path(inner_path) = inner_ty.kind
5012 && let hir::QPath::Resolved(None, inner_path) = inner_path
5013 && let Res::SelfTyAlias { .. } = inner_path.res
5014 {
5015 self.paths.push(ty.as_unambig_ty());
5016 }
5017 hir::intravisit::walk_ty(self, ty);
5018 }
5019}
5020
5021#[derive(Default)]
5024pub struct ReturnsVisitor<'v> {
5025 pub returns: Vec<&'v hir::Expr<'v>>,
5026 in_block_tail: bool,
5027}
5028
5029impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
5030 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5031 match ex.kind {
5036 hir::ExprKind::Ret(Some(ex)) => {
5037 self.returns.push(ex);
5038 }
5039 hir::ExprKind::Block(block, _) if self.in_block_tail => {
5040 self.in_block_tail = false;
5041 for stmt in block.stmts {
5042 hir::intravisit::walk_stmt(self, stmt);
5043 }
5044 self.in_block_tail = true;
5045 if let Some(expr) = block.expr {
5046 self.visit_expr(expr);
5047 }
5048 }
5049 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
5050 self.visit_expr(then);
5051 if let Some(el) = else_opt {
5052 self.visit_expr(el);
5053 }
5054 }
5055 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
5056 for arm in arms {
5057 self.visit_expr(arm.body);
5058 }
5059 }
5060 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
5062 _ => self.returns.push(ex),
5063 }
5064 }
5065
5066 fn visit_body(&mut self, body: &hir::Body<'v>) {
5067 assert!(!self.in_block_tail);
5068 self.in_block_tail = true;
5069 hir::intravisit::walk_body(self, body);
5070 }
5071}
5072
5073#[derive(Default)]
5075struct AwaitsVisitor {
5076 awaits: Vec<HirId>,
5077}
5078
5079impl<'v> Visitor<'v> for AwaitsVisitor {
5080 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5081 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
5082 self.awaits.push(id)
5083 }
5084 hir::intravisit::walk_expr(self, ex)
5085 }
5086}
5087
5088pub trait NextTypeParamName {
5092 fn next_type_param_name(&self, name: Option<&str>) -> String;
5093}
5094
5095impl NextTypeParamName for &[hir::GenericParam<'_>] {
5096 fn next_type_param_name(&self, name: Option<&str>) -> String {
5097 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
5099 let name = name.as_deref();
5100
5101 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
5103
5104 let used_names: Vec<Symbol> = self
5106 .iter()
5107 .filter_map(|param| match param.name {
5108 hir::ParamName::Plain(ident) => Some(ident.name),
5109 _ => None,
5110 })
5111 .collect();
5112
5113 possible_names
5115 .iter()
5116 .find(|n| !used_names.contains(&Symbol::intern(n)))
5117 .unwrap_or(&"ParamName")
5118 .to_string()
5119 }
5120}
5121
5122struct ReplaceImplTraitVisitor<'a> {
5124 ty_spans: &'a mut Vec<Span>,
5125 param_did: DefId,
5126}
5127
5128impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
5129 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
5130 if let hir::TyKind::Path(hir::QPath::Resolved(
5131 None,
5132 hir::Path { res: Res::Def(_, segment_did), .. },
5133 )) = t.kind
5134 {
5135 if self.param_did == *segment_did {
5136 self.ty_spans.push(t.span);
5141 return;
5142 }
5143 }
5144
5145 hir::intravisit::walk_ty(self, t);
5146 }
5147}
5148
5149pub(super) fn get_explanation_based_on_obligation<'tcx>(
5150 tcx: TyCtxt<'tcx>,
5151 obligation: &PredicateObligation<'tcx>,
5152 trait_predicate: ty::PolyTraitPredicate<'tcx>,
5153 pre_message: String,
5154) -> String {
5155 if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
5156 "consider using `()`, or a `Result`".to_owned()
5157 } else {
5158 let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
5159 ty::FnDef(_, _) => Some("fn item"),
5160 ty::Closure(_, _) => Some("closure"),
5161 _ => None,
5162 };
5163
5164 let desc = match ty_desc {
5165 Some(desc) => format!(" {desc}"),
5166 None => String::new(),
5167 };
5168 if let ty::PredicatePolarity::Positive = trait_predicate.polarity() {
5169 format!(
5170 "{pre_message}the trait `{}` is not implemented for{desc} `{}`",
5171 trait_predicate.print_modifiers_and_trait_path(),
5172 tcx.short_string(trait_predicate.self_ty().skip_binder(), &mut None),
5173 )
5174 } else {
5175 format!("{pre_message}the trait bound `{trait_predicate}` is not satisfied")
5179 }
5180 }
5181}
5182
5183struct ReplaceImplTraitFolder<'tcx> {
5185 tcx: TyCtxt<'tcx>,
5186 param: &'tcx ty::GenericParamDef,
5187 replace_ty: Ty<'tcx>,
5188}
5189
5190impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
5191 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
5192 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
5193 if self.param.index == *index {
5194 return self.replace_ty;
5195 }
5196 }
5197 t.super_fold_with(self)
5198 }
5199
5200 fn cx(&self) -> TyCtxt<'tcx> {
5201 self.tcx
5202 }
5203}
5204
5205pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
5206 tcx: TyCtxt<'tcx>,
5207 sig: hir::FnSig<'tcx>,
5208 body: hir::TraitFn<'tcx>,
5209 opaque_def_id: LocalDefId,
5210 add_bounds: &str,
5211) -> Option<Vec<(Span, String)>> {
5212 let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
5213 return None;
5214 };
5215 let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
5216
5217 let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
5218 let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
5219 return None;
5221 };
5222 let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
5223 else {
5224 return None;
5226 };
5227 let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
5228 else {
5229 return None;
5231 };
5232
5233 let mut sugg = if future_output_ty.span.is_empty() {
5234 vec![
5235 (async_span, String::new()),
5236 (
5237 future_output_ty.span,
5238 format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
5239 ),
5240 ]
5241 } else {
5242 vec![
5243 (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
5244 (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
5245 (async_span, String::new()),
5246 ]
5247 };
5248
5249 if let hir::TraitFn::Provided(body) = body {
5251 let body = tcx.hir().body(body);
5252 let body_span = body.value.span;
5253 let body_span_without_braces =
5254 body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
5255 if body_span_without_braces.is_empty() {
5256 sugg.push((body_span_without_braces, " async {} ".to_owned()));
5257 } else {
5258 sugg.extend([
5259 (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
5260 (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
5261 ]);
5262 }
5263 }
5264
5265 Some(sugg)
5266}
5267
5268fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
5271 tcx: TyCtxt<'_>,
5272 err: &mut Diag<'_, G>,
5273 self_ty_str: &str,
5274 trait_name: &str,
5275 predicate: ty::Predicate<'_>,
5276 generics: &hir::Generics<'_>,
5277 data: &ImplDerivedCause<'_>,
5278) {
5279 let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
5280 return;
5281 };
5282 let ty::ClauseKind::Projection(proj) = clause else {
5283 return;
5284 };
5285 let name = tcx.item_name(proj.projection_term.def_id);
5286 let mut predicates = generics.predicates.iter().peekable();
5287 let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
5288 while let Some(pred) = predicates.next() {
5289 let curr_span = pred.span;
5290 let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
5291 continue;
5292 };
5293 let mut bounds = pred.bounds.iter();
5294 while let Some(bound) = bounds.next() {
5295 let Some(trait_ref) = bound.trait_ref() else {
5296 continue;
5297 };
5298 if bound.span() != data.span {
5299 continue;
5300 }
5301 if let hir::TyKind::Path(path) = pred.bounded_ty.kind
5302 && let hir::QPath::TypeRelative(ty, segment) = path
5303 && segment.ident.name == name
5304 && let hir::TyKind::Path(inner_path) = ty.kind
5305 && let hir::QPath::Resolved(None, inner_path) = inner_path
5306 && let Res::SelfTyAlias { .. } = inner_path.res
5307 {
5308 let span = if pred.origin == hir::PredicateOrigin::WhereClause
5311 && generics
5312 .predicates
5313 .iter()
5314 .filter(|p| {
5315 matches!(
5316 p.kind,
5317 hir::WherePredicateKind::BoundPredicate(p)
5318 if hir::PredicateOrigin::WhereClause == p.origin
5319 )
5320 })
5321 .count()
5322 == 1
5323 {
5324 generics.where_clause_span
5327 } else if let Some(next_pred) = predicates.peek()
5328 && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
5329 && pred.origin == next.origin
5330 {
5331 curr_span.until(next_pred.span)
5333 } else if let Some((prev, prev_span)) = prev
5334 && pred.origin == prev.origin
5335 {
5336 prev_span.shrink_to_hi().to(curr_span)
5338 } else if pred.origin == hir::PredicateOrigin::WhereClause {
5339 curr_span.with_hi(generics.where_clause_span.hi())
5340 } else {
5341 curr_span
5342 };
5343
5344 err.span_suggestion_verbose(
5345 span,
5346 "associated type for the current `impl` cannot be restricted in `where` \
5347 clauses, remove this bound",
5348 "",
5349 Applicability::MaybeIncorrect,
5350 );
5351 }
5352 if let Some(new) =
5353 tcx.associated_items(data.impl_or_alias_def_id).find_by_name_and_kind(
5354 tcx,
5355 Ident::with_dummy_span(name),
5356 ty::AssocKind::Type,
5357 data.impl_or_alias_def_id,
5358 )
5359 {
5360 let span = tcx.def_span(new.def_id);
5363 err.span_label(
5364 span,
5365 format!(
5366 "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
5367 here",
5368 ),
5369 );
5370 let mut visitor = SelfVisitor { paths: vec![], name: Some(name) };
5373 visitor.visit_trait_ref(trait_ref);
5374 for path in visitor.paths {
5375 err.span_suggestion_verbose(
5376 path.span,
5377 "replace the associated type with the type specified in this `impl`",
5378 tcx.type_of(new.def_id).skip_binder(),
5379 Applicability::MachineApplicable,
5380 );
5381 }
5382 } else {
5383 let mut visitor = SelfVisitor { paths: vec![], name: None };
5384 visitor.visit_trait_ref(trait_ref);
5385 let span: MultiSpan =
5386 visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
5387 err.span_note(
5388 span,
5389 "associated types for the current `impl` cannot be restricted in `where` \
5390 clauses",
5391 );
5392 }
5393 }
5394 prev = Some((pred, curr_span));
5395 }
5396}
5397
5398fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
5399 let mut refs = vec![];
5400
5401 while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
5402 ty = *new_ty;
5403 refs.push(*mutbl);
5404 }
5405
5406 (ty, refs)
5407}
5408
5409struct FindTypeParam {
5412 param: rustc_span::Symbol,
5413 invalid_spans: Vec<Span>,
5414 nested: bool,
5415}
5416
5417impl<'v> Visitor<'v> for FindTypeParam {
5418 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
5419 }
5421
5422 fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
5423 match ty.kind {
5430 hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
5431 hir::TyKind::Path(hir::QPath::Resolved(None, path))
5432 if let [segment] = path.segments
5433 && segment.ident.name == self.param =>
5434 {
5435 if !self.nested {
5436 debug!(?ty, "FindTypeParam::visit_ty");
5437 self.invalid_spans.push(ty.span);
5438 }
5439 }
5440 hir::TyKind::Path(_) => {
5441 let prev = self.nested;
5442 self.nested = true;
5443 hir::intravisit::walk_ty(self, ty);
5444 self.nested = prev;
5445 }
5446 _ => {
5447 hir::intravisit::walk_ty(self, ty);
5448 }
5449 }
5450 }
5451}