1use std::borrow::Cow;
4use std::iter;
5use std::path::PathBuf;
6
7use itertools::{EitherOrBoth, Itertools};
8use rustc_abi::ExternAbi;
9use rustc_data_structures::debug_assert_matches;
10use rustc_data_structures::fx::FxHashSet;
11use rustc_data_structures::stack::ensure_sufficient_stack;
12use rustc_errors::codes::*;
13use rustc_errors::{
14 Applicability, Diag, EmissionGuarantee, MultiSpan, Style, SuggestionStyle, pluralize,
15 struct_span_code_err,
16};
17use rustc_hir::def::{CtorOf, DefKind, Res};
18use rustc_hir::def_id::DefId;
19use rustc_hir::intravisit::{Visitor, VisitorExt};
20use rustc_hir::lang_items::LangItem;
21use rustc_hir::{
22 self as hir, AmbigArg, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node,
23 expr_needs_parens,
24};
25use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk};
26use rustc_middle::middle::privacy::Level;
27use rustc_middle::traits::IsConstable;
28use rustc_middle::ty::error::TypeError;
29use rustc_middle::ty::print::{
30 PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _,
31 with_forced_trimmed_paths, with_no_trimmed_paths, with_types_for_suggestion,
32};
33use rustc_middle::ty::{
34 self, AdtKind, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder,
35 TypeSuperFoldable, TypeSuperVisitable, TypeVisitableExt, TypeVisitor, TypeckResults, Upcast,
36 suggest_arbitrary_trait_bound, suggest_constraining_type_param,
37};
38use rustc_middle::{bug, span_bug};
39use rustc_span::def_id::LocalDefId;
40use rustc_span::{
41 BytePos, DUMMY_SP, DesugaringKind, ExpnKind, Ident, MacroKind, Span, Symbol, kw, sym,
42};
43use tracing::{debug, instrument};
44
45use super::{
46 DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode,
47 PredicateObligation,
48};
49use crate::error_reporting::TypeErrCtxt;
50use crate::errors;
51use crate::infer::InferCtxtExt as _;
52use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
53use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt};
54
55#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CoroutineInteriorOrUpvar {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CoroutineInteriorOrUpvar::Interior(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Interior", __self_0, &__self_1),
CoroutineInteriorOrUpvar::Upvar(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Upvar",
&__self_0),
}
}
}Debug)]
56pub enum CoroutineInteriorOrUpvar {
57 Interior(Span, Option<(Span, Option<Span>)>),
59 Upvar(Span),
61}
62
63#[derive(#[automatically_derived]
impl<'a, 'tcx> ::core::fmt::Debug for CoroutineData<'a, 'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "CoroutineData",
&&self.0)
}
}Debug)]
66struct CoroutineData<'a, 'tcx>(&'a TypeckResults<'tcx>);
67
68impl<'a, 'tcx> CoroutineData<'a, 'tcx> {
69 fn try_get_upvar_span<F>(
73 &self,
74 infer_context: &InferCtxt<'tcx>,
75 coroutine_did: DefId,
76 ty_matches: F,
77 ) -> Option<CoroutineInteriorOrUpvar>
78 where
79 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
80 {
81 infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| {
82 upvars.iter().find_map(|(upvar_id, upvar)| {
83 let upvar_ty = self.0.node_type(*upvar_id);
84 let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty);
85 ty_matches(ty::Binder::dummy(upvar_ty))
86 .then(|| CoroutineInteriorOrUpvar::Upvar(upvar.span))
87 })
88 })
89 }
90
91 fn get_from_await_ty<F>(
95 &self,
96 visitor: AwaitsVisitor,
97 tcx: TyCtxt<'tcx>,
98 ty_matches: F,
99 ) -> Option<Span>
100 where
101 F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool,
102 {
103 visitor
104 .awaits
105 .into_iter()
106 .map(|id| tcx.hir_expect_expr(id))
107 .find(|await_expr| ty_matches(ty::Binder::dummy(self.0.expr_ty_adjusted(await_expr))))
108 .map(|expr| expr.span)
109 }
110}
111
112fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) {
113 (
114 generics.tail_span_for_predicate_suggestion(),
115 {
let _guard =
::rustc_middle::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSuggestion);
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
generics.add_where_or_trailing_comma(), pred))
})
}with_types_for_suggestion!(format!("{} {}", generics.add_where_or_trailing_comma(), pred)),
116 )
117}
118
119pub fn suggest_restriction<'tcx, G: EmissionGuarantee>(
123 tcx: TyCtxt<'tcx>,
124 item_id: LocalDefId,
125 hir_generics: &hir::Generics<'tcx>,
126 msg: &str,
127 err: &mut Diag<'_, G>,
128 fn_sig: Option<&hir::FnSig<'_>>,
129 projection: Option<ty::AliasTy<'_>>,
130 trait_pred: ty::PolyTraitPredicate<'tcx>,
131 super_traits: Option<(&Ident, &hir::GenericBounds<'_>)>,
137) {
138 if hir_generics.where_clause_span.from_expansion()
139 || hir_generics.where_clause_span.desugaring_kind().is_some()
140 || projection.is_some_and(|projection| {
141 (tcx.is_impl_trait_in_trait(projection.def_id)
142 && !tcx.features().return_type_notation())
143 || tcx.lookup_stability(projection.def_id).is_some_and(|stab| stab.is_unstable())
144 })
145 {
146 return;
147 }
148 let generics = tcx.generics_of(item_id);
149 if let Some((param, bound_str, fn_sig)) =
151 fn_sig.zip(projection).and_then(|(sig, p)| match *p.self_ty().kind() {
152 ty::Param(param) => {
154 let param_def = generics.type_param(param, tcx);
155 if param_def.kind.is_synthetic() {
156 let bound_str =
157 param_def.name.as_str().strip_prefix("impl ")?.trim_start().to_string();
158 return Some((param_def, bound_str, sig));
159 }
160 None
161 }
162 _ => None,
163 })
164 {
165 let type_param_name = hir_generics.params.next_type_param_name(Some(&bound_str));
166 let trait_pred = trait_pred.fold_with(&mut ReplaceImplTraitFolder {
167 tcx,
168 param,
169 replace_ty: ty::ParamTy::new(generics.count() as u32, Symbol::intern(&type_param_name))
170 .to_ty(tcx),
171 });
172 if !trait_pred.is_suggestable(tcx, false) {
173 return;
174 }
175 let mut ty_spans = ::alloc::vec::Vec::new()vec![];
183 for input in fn_sig.decl.inputs {
184 ReplaceImplTraitVisitor { ty_spans: &mut ty_spans, param_did: param.def_id }
185 .visit_ty_unambig(input);
186 }
187 let type_param = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", type_param_name,
bound_str))
})format!("{type_param_name}: {bound_str}");
189
190 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[if let Some(span) = hir_generics.span_for_param_suggestion() {
(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", type_param))
}))
} else {
(hir_generics.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", type_param))
}))
},
predicate_constraint(hir_generics, trait_pred.upcast(tcx))]))vec![
191 if let Some(span) = hir_generics.span_for_param_suggestion() {
192 (span, format!(", {type_param}"))
193 } else {
194 (hir_generics.span, format!("<{type_param}>"))
195 },
196 predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
199 ];
200 sugg.extend(ty_spans.into_iter().map(|s| (s, type_param_name.to_string())));
201
202 err.multipart_suggestion(
205 "introduce a type parameter with a trait bound instead of using `impl Trait`",
206 sugg,
207 Applicability::MaybeIncorrect,
208 );
209 } else {
210 if !trait_pred.is_suggestable(tcx, false) {
211 return;
212 }
213 let (sp, suggestion) = match (
215 hir_generics
216 .params
217 .iter()
218 .find(|p| !#[allow(non_exhaustive_omitted_patterns)] match p.kind {
hir::GenericParamKind::Type { synthetic: true, .. } => true,
_ => false,
}matches!(p.kind, hir::GenericParamKind::Type { synthetic: true, .. })),
219 super_traits,
220 ) {
221 (_, None) => predicate_constraint(hir_generics, trait_pred.upcast(tcx)),
222 (None, Some((ident, []))) => (
223 ident.span.shrink_to_hi(),
224 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}",
trait_pred.print_modifiers_and_trait_path()))
})format!(": {}", trait_pred.print_modifiers_and_trait_path()),
225 ),
226 (_, Some((_, [.., bounds]))) => (
227 bounds.span().shrink_to_hi(),
228 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}",
trait_pred.print_modifiers_and_trait_path()))
})format!(" + {}", trait_pred.print_modifiers_and_trait_path()),
229 ),
230 (Some(_), Some((_, []))) => (
231 hir_generics.span.shrink_to_hi(),
232 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}",
trait_pred.print_modifiers_and_trait_path()))
})format!(": {}", trait_pred.print_modifiers_and_trait_path()),
233 ),
234 };
235
236 err.span_suggestion_verbose(
237 sp,
238 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider further restricting {0}",
msg))
})format!("consider further restricting {msg}"),
239 suggestion,
240 Applicability::MachineApplicable,
241 );
242 }
243}
244
245impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
246 pub fn suggest_restricting_param_bound(
247 &self,
248 err: &mut Diag<'_>,
249 trait_pred: ty::PolyTraitPredicate<'tcx>,
250 associated_ty: Option<(&'static str, Ty<'tcx>)>,
251 mut body_id: LocalDefId,
252 ) {
253 if trait_pred.skip_binder().polarity != ty::PredicatePolarity::Positive {
254 return;
255 }
256
257 let trait_pred = self.resolve_numeric_literals_with_default(trait_pred);
258
259 let self_ty = trait_pred.skip_binder().self_ty();
260 let (param_ty, projection) = match *self_ty.kind() {
261 ty::Param(_) => (true, None),
262 ty::Alias(ty::Projection, projection) => (false, Some(projection)),
263 _ => (false, None),
264 };
265
266 let mut finder = ParamFinder { .. };
267 finder.visit_binder(&trait_pred);
268
269 loop {
272 let node = self.tcx.hir_node_by_def_id(body_id);
273 match node {
274 hir::Node::Item(hir::Item {
275 kind: hir::ItemKind::Trait(_, _, _, ident, generics, bounds, _),
276 ..
277 }) if self_ty == self.tcx.types.self_param => {
278 if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
279 suggest_restriction(
281 self.tcx,
282 body_id,
283 generics,
284 "`Self`",
285 err,
286 None,
287 projection,
288 trait_pred,
289 Some((&ident, bounds)),
290 );
291 return;
292 }
293
294 hir::Node::TraitItem(hir::TraitItem {
295 generics,
296 kind: hir::TraitItemKind::Fn(..),
297 ..
298 }) if self_ty == self.tcx.types.self_param => {
299 if !param_ty { ::core::panicking::panic("assertion failed: param_ty") };assert!(param_ty);
300 suggest_restriction(
302 self.tcx, body_id, generics, "`Self`", err, None, projection, trait_pred,
303 None,
304 );
305 return;
306 }
307
308 hir::Node::TraitItem(hir::TraitItem {
309 generics,
310 kind: hir::TraitItemKind::Fn(fn_sig, ..),
311 ..
312 })
313 | hir::Node::ImplItem(hir::ImplItem {
314 generics,
315 kind: hir::ImplItemKind::Fn(fn_sig, ..),
316 ..
317 })
318 | hir::Node::Item(hir::Item {
319 kind: hir::ItemKind::Fn { sig: fn_sig, generics, .. },
320 ..
321 }) if projection.is_some() => {
322 suggest_restriction(
324 self.tcx,
325 body_id,
326 generics,
327 "the associated type",
328 err,
329 Some(fn_sig),
330 projection,
331 trait_pred,
332 None,
333 );
334 return;
335 }
336 hir::Node::Item(hir::Item {
337 kind:
338 hir::ItemKind::Trait(_, _, _, _, generics, ..)
339 | hir::ItemKind::Impl(hir::Impl { generics, .. }),
340 ..
341 }) if projection.is_some() => {
342 suggest_restriction(
344 self.tcx,
345 body_id,
346 generics,
347 "the associated type",
348 err,
349 None,
350 projection,
351 trait_pred,
352 None,
353 );
354 return;
355 }
356
357 hir::Node::Item(hir::Item {
358 kind:
359 hir::ItemKind::Struct(_, generics, _)
360 | hir::ItemKind::Enum(_, generics, _)
361 | hir::ItemKind::Union(_, generics, _)
362 | hir::ItemKind::Trait(_, _, _, _, generics, ..)
363 | hir::ItemKind::Impl(hir::Impl { generics, .. })
364 | hir::ItemKind::Fn { generics, .. }
365 | hir::ItemKind::TyAlias(_, generics, _)
366 | hir::ItemKind::Const(_, generics, _, _)
367 | hir::ItemKind::TraitAlias(_, _, generics, _),
368 ..
369 })
370 | hir::Node::TraitItem(hir::TraitItem { generics, .. })
371 | hir::Node::ImplItem(hir::ImplItem { generics, .. })
372 if param_ty =>
373 {
374 if !trait_pred.skip_binder().trait_ref.args[1..]
383 .iter()
384 .all(|g| g.is_suggestable(self.tcx, false))
385 {
386 return;
387 }
388 let param_name = self_ty.to_string();
390 let mut constraint = {
let _guard = NoTrimmedGuard::new();
trait_pred.print_modifiers_and_trait_path().to_string()
}with_no_trimmed_paths!(
391 trait_pred.print_modifiers_and_trait_path().to_string()
392 );
393
394 if let Some((name, term)) = associated_ty {
395 if let Some(stripped) = constraint.strip_suffix('>') {
398 constraint = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, {1} = {2}>", stripped, name,
term))
})format!("{stripped}, {name} = {term}>");
399 } else {
400 constraint.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} = {1}>", name, term))
})format!("<{name} = {term}>"));
401 }
402 }
403
404 if suggest_constraining_type_param(
405 self.tcx,
406 generics,
407 err,
408 ¶m_name,
409 &constraint,
410 Some(trait_pred.def_id()),
411 None,
412 ) {
413 return;
414 }
415 }
416
417 hir::Node::TraitItem(hir::TraitItem {
418 generics,
419 kind: hir::TraitItemKind::Fn(..),
420 ..
421 })
422 | hir::Node::ImplItem(hir::ImplItem {
423 generics,
424 impl_kind: hir::ImplItemImplKind::Inherent { .. },
425 kind: hir::ImplItemKind::Fn(..),
426 ..
427 }) if finder.can_suggest_bound(generics) => {
428 suggest_arbitrary_trait_bound(
430 self.tcx,
431 generics,
432 err,
433 trait_pred,
434 associated_ty,
435 );
436 }
437 hir::Node::Item(hir::Item {
438 kind:
439 hir::ItemKind::Struct(_, generics, _)
440 | hir::ItemKind::Enum(_, generics, _)
441 | hir::ItemKind::Union(_, generics, _)
442 | hir::ItemKind::Trait(_, _, _, _, generics, ..)
443 | hir::ItemKind::Impl(hir::Impl { generics, .. })
444 | hir::ItemKind::Fn { generics, .. }
445 | hir::ItemKind::TyAlias(_, generics, _)
446 | hir::ItemKind::Const(_, generics, _, _)
447 | hir::ItemKind::TraitAlias(_, _, generics, _),
448 ..
449 }) if finder.can_suggest_bound(generics) => {
450 if suggest_arbitrary_trait_bound(
452 self.tcx,
453 generics,
454 err,
455 trait_pred,
456 associated_ty,
457 ) {
458 return;
459 }
460 }
461 hir::Node::Crate(..) => return,
462
463 _ => {}
464 }
465 body_id = self.tcx.local_parent(body_id);
466 }
467 }
468
469 pub(super) fn suggest_dereferences(
472 &self,
473 obligation: &PredicateObligation<'tcx>,
474 err: &mut Diag<'_>,
475 trait_pred: ty::PolyTraitPredicate<'tcx>,
476 ) -> bool {
477 let mut code = obligation.cause.code();
478 if let ObligationCauseCode::FunctionArg { arg_hir_id, call_hir_id, .. } = code
479 && let Some(typeck_results) = &self.typeck_results
480 && let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id)
481 && let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr)
482 {
483 let mut real_trait_pred = trait_pred;
487 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
488 code = parent_code;
489 if let Some(parent_trait_pred) = parent_trait_pred {
490 real_trait_pred = parent_trait_pred;
491 }
492 }
493
494 let real_ty = self.tcx.instantiate_bound_regions_with_erased(real_trait_pred.self_ty());
497 if !self.can_eq(obligation.param_env, real_ty, arg_ty) {
498 return false;
499 }
500
501 let (is_under_ref, base_ty, span) = match expr.kind {
508 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, subexpr)
509 if let &ty::Ref(region, base_ty, hir::Mutability::Not) = real_ty.kind() =>
510 {
511 (Some(region), base_ty, subexpr.span)
512 }
513 hir::ExprKind::AddrOf(..) => return false,
515 _ => (None, real_ty, obligation.cause.span),
516 };
517
518 let autoderef = (self.autoderef_steps)(base_ty);
519 let mut is_boxed = base_ty.is_box();
520 if let Some(steps) = autoderef.into_iter().position(|(mut ty, obligations)| {
521 let can_deref = is_under_ref.is_some()
524 || self.type_is_copy_modulo_regions(obligation.param_env, ty)
525 || ty.is_numeric() || is_boxed && self.type_is_sized_modulo_regions(obligation.param_env, ty);
527 is_boxed &= ty.is_box();
528
529 if let Some(region) = is_under_ref {
531 ty = Ty::new_ref(self.tcx, region, ty, hir::Mutability::Not);
532 }
533
534 let real_trait_pred_and_ty =
536 real_trait_pred.map_bound(|inner_trait_pred| (inner_trait_pred, ty));
537 let obligation = self.mk_trait_obligation_with_new_self_ty(
538 obligation.param_env,
539 real_trait_pred_and_ty,
540 );
541
542 can_deref
543 && obligations
544 .iter()
545 .chain([&obligation])
546 .all(|obligation| self.predicate_may_hold(obligation))
547 }) && steps > 0
548 {
549 let derefs = "*".repeat(steps);
550 let msg = "consider dereferencing here";
551 let call_node = self.tcx.hir_node(*call_hir_id);
552 let is_receiver = #[allow(non_exhaustive_omitted_patterns)] match call_node {
Node::Expr(hir::Expr {
kind: hir::ExprKind::MethodCall(_, receiver_expr, ..), .. }) if
receiver_expr.hir_id == *arg_hir_id => true,
_ => false,
}matches!(
553 call_node,
554 Node::Expr(hir::Expr {
555 kind: hir::ExprKind::MethodCall(_, receiver_expr, ..),
556 ..
557 })
558 if receiver_expr.hir_id == *arg_hir_id
559 );
560 if is_receiver {
561 err.multipart_suggestion(
562 msg,
563 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}", derefs))
})), (span.shrink_to_hi(), ")".to_string())]))vec![
564 (span.shrink_to_lo(), format!("({derefs}")),
565 (span.shrink_to_hi(), ")".to_string()),
566 ],
567 Applicability::MachineApplicable,
568 )
569 } else {
570 err.span_suggestion_verbose(
571 span.shrink_to_lo(),
572 msg,
573 derefs,
574 Applicability::MachineApplicable,
575 )
576 };
577 return true;
578 }
579 } else if let (
580 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, .. },
581 predicate,
582 ) = code.peel_derives_with_predicate()
583 && let Some(typeck_results) = &self.typeck_results
584 && let hir::Node::Expr(lhs) = self.tcx.hir_node(*lhs_hir_id)
585 && let hir::Node::Expr(rhs) = self.tcx.hir_node(*rhs_hir_id)
586 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs)
587 && let trait_pred = predicate.unwrap_or(trait_pred)
588 && hir::lang_items::BINARY_OPERATORS
590 .iter()
591 .filter_map(|&op| self.tcx.lang_items().get(op))
592 .any(|op| {
593 op == trait_pred.skip_binder().trait_ref.def_id
594 })
595 {
596 let trait_pred = predicate.unwrap_or(trait_pred);
599 let lhs_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
600 let lhs_autoderef = (self.autoderef_steps)(lhs_ty);
601 let rhs_autoderef = (self.autoderef_steps)(rhs_ty);
602 let first_lhs = lhs_autoderef.first().unwrap().clone();
603 let first_rhs = rhs_autoderef.first().unwrap().clone();
604 let mut autoderefs = lhs_autoderef
605 .into_iter()
606 .enumerate()
607 .rev()
608 .zip_longest(rhs_autoderef.into_iter().enumerate().rev())
609 .map(|t| match t {
610 EitherOrBoth::Both(a, b) => (a, b),
611 EitherOrBoth::Left(a) => (a, (0, first_rhs.clone())),
612 EitherOrBoth::Right(b) => ((0, first_lhs.clone()), b),
613 })
614 .rev();
615 if let Some((lsteps, rsteps)) =
616 autoderefs.find_map(|((lsteps, (l_ty, _)), (rsteps, (r_ty, _)))| {
617 let trait_pred_and_ty = trait_pred.map_bound(|inner| {
621 (
622 ty::TraitPredicate {
623 trait_ref: ty::TraitRef::new_from_args(
624 self.tcx,
625 inner.trait_ref.def_id,
626 self.tcx.mk_args(
627 &[&[l_ty.into(), r_ty.into()], &inner.trait_ref.args[2..]]
628 .concat(),
629 ),
630 ),
631 ..inner
632 },
633 l_ty,
634 )
635 });
636 let obligation = self.mk_trait_obligation_with_new_self_ty(
637 obligation.param_env,
638 trait_pred_and_ty,
639 );
640 self.predicate_may_hold(&obligation).then_some(match (lsteps, rsteps) {
641 (_, 0) => (Some(lsteps), None),
642 (0, _) => (None, Some(rsteps)),
643 _ => (Some(lsteps), Some(rsteps)),
644 })
645 })
646 {
647 let make_sugg = |mut expr: &Expr<'_>, mut steps| {
648 let mut prefix_span = expr.span.shrink_to_lo();
649 let mut msg = "consider dereferencing here";
650 if let hir::ExprKind::AddrOf(_, _, inner) = expr.kind {
651 msg = "consider removing the borrow and dereferencing instead";
652 if let hir::ExprKind::AddrOf(..) = inner.kind {
653 msg = "consider removing the borrows and dereferencing instead";
654 }
655 }
656 while let hir::ExprKind::AddrOf(_, _, inner) = expr.kind
657 && steps > 0
658 {
659 prefix_span = prefix_span.with_hi(inner.span.lo());
660 expr = inner;
661 steps -= 1;
662 }
663 if steps == 0 {
665 return (
666 msg.trim_end_matches(" and dereferencing instead"),
667 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(prefix_span, String::new())]))vec![(prefix_span, String::new())],
668 );
669 }
670 let derefs = "*".repeat(steps);
671 let needs_parens = steps > 0 && expr_needs_parens(expr);
672 let mut suggestion = if needs_parens {
673 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}(", derefs))
})), (expr.span.shrink_to_hi(), ")".to_string())]))vec![
674 (
675 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
676 format!("{derefs}("),
677 ),
678 (expr.span.shrink_to_hi(), ")".to_string()),
679 ]
680 } else {
681 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", derefs))
}))]))vec![(
682 expr.span.with_lo(prefix_span.hi()).shrink_to_lo(),
683 format!("{derefs}"),
684 )]
685 };
686 if !prefix_span.is_empty() {
688 suggestion.push((prefix_span, String::new()));
689 }
690 (msg, suggestion)
691 };
692
693 if let Some(lsteps) = lsteps
694 && let Some(rsteps) = rsteps
695 && lsteps > 0
696 && rsteps > 0
697 {
698 let mut suggestion = make_sugg(lhs, lsteps).1;
699 suggestion.append(&mut make_sugg(rhs, rsteps).1);
700 err.multipart_suggestion(
701 "consider dereferencing both sides of the expression",
702 suggestion,
703 Applicability::MachineApplicable,
704 );
705 return true;
706 } else if let Some(lsteps) = lsteps
707 && lsteps > 0
708 {
709 let (msg, suggestion) = make_sugg(lhs, lsteps);
710 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
711 return true;
712 } else if let Some(rsteps) = rsteps
713 && rsteps > 0
714 {
715 let (msg, suggestion) = make_sugg(rhs, rsteps);
716 err.multipart_suggestion(msg, suggestion, Applicability::MachineApplicable);
717 return true;
718 }
719 }
720 }
721 false
722 }
723
724 fn get_closure_name(
728 &self,
729 def_id: DefId,
730 err: &mut Diag<'_>,
731 msg: Cow<'static, str>,
732 ) -> Option<Symbol> {
733 let get_name = |err: &mut Diag<'_>, kind: &hir::PatKind<'_>| -> Option<Symbol> {
734 match &kind {
737 hir::PatKind::Binding(hir::BindingMode::NONE, _, ident, None) => Some(ident.name),
738 _ => {
739 err.note(msg);
740 None
741 }
742 }
743 };
744
745 let hir_id = self.tcx.local_def_id_to_hir_id(def_id.as_local()?);
746 match self.tcx.parent_hir_node(hir_id) {
747 hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(local), .. }) => {
748 get_name(err, &local.pat.kind)
749 }
750 hir::Node::LetStmt(local) => get_name(err, &local.pat.kind),
753 _ => None,
754 }
755 }
756
757 pub(super) fn suggest_fn_call(
761 &self,
762 obligation: &PredicateObligation<'tcx>,
763 err: &mut Diag<'_>,
764 trait_pred: ty::PolyTraitPredicate<'tcx>,
765 ) -> bool {
766 if self.typeck_results.is_none() {
769 return false;
770 }
771
772 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
773 obligation.predicate.kind().skip_binder()
774 && self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
775 {
776 return false;
778 }
779
780 let self_ty = self.instantiate_binder_with_fresh_vars(
781 DUMMY_SP,
782 BoundRegionConversionTime::FnCall,
783 trait_pred.self_ty(),
784 );
785
786 let Some((def_id_or_name, output, inputs)) =
787 self.extract_callable_info(obligation.cause.body_id, obligation.param_env, self_ty)
788 else {
789 return false;
790 };
791
792 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output));
794
795 let new_obligation =
796 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
797 if !self.predicate_must_hold_modulo_regions(&new_obligation) {
798 return false;
799 }
800
801 let msg = match def_id_or_name {
803 DefIdOrName::DefId(def_id) => match self.tcx.def_kind(def_id) {
804 DefKind::Ctor(CtorOf::Struct, _) => {
805 Cow::from("use parentheses to construct this tuple struct")
806 }
807 DefKind::Ctor(CtorOf::Variant, _) => {
808 Cow::from("use parentheses to construct this tuple variant")
809 }
810 kind => Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use parentheses to call this {0}",
self.tcx.def_kind_descr(kind, def_id)))
})format!(
811 "use parentheses to call this {}",
812 self.tcx.def_kind_descr(kind, def_id)
813 )),
814 },
815 DefIdOrName::Name(name) => Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use parentheses to call this {0}",
name))
})format!("use parentheses to call this {name}")),
816 };
817
818 let args = inputs
819 .into_iter()
820 .map(|ty| {
821 if ty.is_suggestable(self.tcx, false) {
822 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", ty))
})format!("/* {ty} */")
823 } else {
824 "/* value */".to_string()
825 }
826 })
827 .collect::<Vec<_>>()
828 .join(", ");
829
830 if #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
ObligationCauseCode::FunctionArg { .. } => true,
_ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. })
831 && obligation.cause.span.can_be_used_for_suggestions()
832 {
833 let (span, sugg) = if let Some(snippet) =
834 self.tcx.sess.source_map().span_to_snippet(obligation.cause.span).ok()
835 && snippet.starts_with("|")
836 {
837 (obligation.cause.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})({1})", snippet, args))
})format!("({snippet})({args})"))
838 } else {
839 (obligation.cause.span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", args))
})format!("({args})"))
840 };
841
842 err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
847 } else if let DefIdOrName::DefId(def_id) = def_id_or_name {
848 let name = match self.tcx.hir_get_if_local(def_id) {
849 Some(hir::Node::Expr(hir::Expr {
850 kind: hir::ExprKind::Closure(hir::Closure { fn_decl_span, .. }),
851 ..
852 })) => {
853 err.span_label(*fn_decl_span, "consider calling this closure");
854 let Some(name) = self.get_closure_name(def_id, err, msg.clone()) else {
855 return false;
856 };
857 name.to_string()
858 }
859 Some(hir::Node::Item(hir::Item {
860 kind: hir::ItemKind::Fn { ident, .. }, ..
861 })) => {
862 err.span_label(ident.span, "consider calling this function");
863 ident.to_string()
864 }
865 Some(hir::Node::Ctor(..)) => {
866 let name = self.tcx.def_path_str(def_id);
867 err.span_label(
868 self.tcx.def_span(def_id),
869 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling the constructor for `{0}`",
name))
})format!("consider calling the constructor for `{name}`"),
870 );
871 name
872 }
873 _ => return false,
874 };
875 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: `{1}({2})`", msg, name, args))
})format!("{msg}: `{name}({args})`"));
876 }
877 true
878 }
879
880 pub(super) fn check_for_binding_assigned_block_without_tail_expression(
881 &self,
882 obligation: &PredicateObligation<'tcx>,
883 err: &mut Diag<'_>,
884 trait_pred: ty::PolyTraitPredicate<'tcx>,
885 ) {
886 let mut span = obligation.cause.span;
887 while span.from_expansion() {
888 span.remove_mark();
890 }
891 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
892 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
893 return;
894 };
895 expr_finder.visit_expr(body.value);
896 let Some(expr) = expr_finder.result else {
897 return;
898 };
899 let Some(typeck) = &self.typeck_results else {
900 return;
901 };
902 let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else {
903 return;
904 };
905 if !ty.is_unit() {
906 return;
907 };
908 let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else {
909 return;
910 };
911 let Res::Local(hir_id) = path.res else {
912 return;
913 };
914 let hir::Node::Pat(pat) = self.tcx.hir_node(hir_id) else {
915 return;
916 };
917 let hir::Node::LetStmt(hir::LetStmt { ty: None, init: Some(init), .. }) =
918 self.tcx.parent_hir_node(pat.hir_id)
919 else {
920 return;
921 };
922 let hir::ExprKind::Block(block, None) = init.kind else {
923 return;
924 };
925 if block.expr.is_some() {
926 return;
927 }
928 let [.., stmt] = block.stmts else {
929 err.span_label(block.span, "this empty block is missing a tail expression");
930 return;
931 };
932 if stmt.span.from_expansion() {
935 return;
936 }
937 let hir::StmtKind::Semi(tail_expr) = stmt.kind else {
938 return;
939 };
940 let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
941 err.span_label(block.span, "this block is missing a tail expression");
942 return;
943 };
944 let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
945 let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
946
947 let new_obligation =
948 self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
949 if !#[allow(non_exhaustive_omitted_patterns)] match tail_expr.kind {
hir::ExprKind::Err(_) => true,
_ => false,
}matches!(tail_expr.kind, hir::ExprKind::Err(_))
950 && self.predicate_must_hold_modulo_regions(&new_obligation)
951 {
952 err.span_suggestion_short(
953 stmt.span.with_lo(tail_expr.span.hi()),
954 "remove this semicolon",
955 "",
956 Applicability::MachineApplicable,
957 );
958 } else {
959 err.span_label(block.span, "this block is missing a tail expression");
960 }
961 }
962
963 pub(super) fn suggest_add_clone_to_arg(
964 &self,
965 obligation: &PredicateObligation<'tcx>,
966 err: &mut Diag<'_>,
967 trait_pred: ty::PolyTraitPredicate<'tcx>,
968 ) -> bool {
969 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
970 self.enter_forall(self_ty, |ty: Ty<'_>| {
971 let Some(generics) = self.tcx.hir_get_generics(obligation.cause.body_id) else {
972 return false;
973 };
974 let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false };
975 let ty::Param(param) = inner_ty.kind() else { return false };
976 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
977 else {
978 return false;
979 };
980
981 let clone_trait = self.tcx.require_lang_item(LangItem::Clone, obligation.cause.span);
982 let has_clone = |ty| {
983 self.type_implements_trait(clone_trait, [ty], obligation.param_env)
984 .must_apply_modulo_regions()
985 };
986
987 let existing_clone_call = match self.tcx.hir_node(*arg_hir_id) {
988 Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) => None,
990 Node::Expr(Expr {
993 kind:
994 hir::ExprKind::MethodCall(
995 hir::PathSegment { ident, .. },
996 _receiver,
997 [],
998 call_span,
999 ),
1000 hir_id,
1001 ..
1002 }) if ident.name == sym::clone
1003 && !call_span.from_expansion()
1004 && !has_clone(*inner_ty) =>
1005 {
1006 let Some(typeck_results) = self.typeck_results.as_ref() else { return false };
1008 let Some((DefKind::AssocFn, did)) = typeck_results.type_dependent_def(*hir_id)
1009 else {
1010 return false;
1011 };
1012 if self.tcx.trait_of_assoc(did) != Some(clone_trait) {
1013 return false;
1014 }
1015 Some(ident.span)
1016 }
1017 _ => return false,
1018 };
1019
1020 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1021 obligation.param_env,
1022 trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)),
1023 );
1024
1025 if self.predicate_may_hold(&new_obligation) && has_clone(ty) {
1026 if !has_clone(param.to_ty(self.tcx)) {
1027 suggest_constraining_type_param(
1028 self.tcx,
1029 generics,
1030 err,
1031 param.name.as_str(),
1032 "Clone",
1033 Some(clone_trait),
1034 None,
1035 );
1036 }
1037 if let Some(existing_clone_call) = existing_clone_call {
1038 err.span_note(
1039 existing_clone_call,
1040 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this `clone()` copies the reference, which does not do anything, because `{0}` does not implement `Clone`",
inner_ty))
})format!(
1041 "this `clone()` copies the reference, \
1042 which does not do anything, \
1043 because `{inner_ty}` does not implement `Clone`"
1044 ),
1045 );
1046 } else {
1047 err.span_suggestion_verbose(
1048 obligation.cause.span.shrink_to_hi(),
1049 "consider using clone here",
1050 ".clone()".to_string(),
1051 Applicability::MaybeIncorrect,
1052 );
1053 }
1054 return true;
1055 }
1056 false
1057 })
1058 }
1059
1060 pub fn extract_callable_info(
1064 &self,
1065 body_id: LocalDefId,
1066 param_env: ty::ParamEnv<'tcx>,
1067 found: Ty<'tcx>,
1068 ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> {
1069 let Some((def_id_or_name, output, inputs)) =
1071 (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| match *found.kind() {
1072 ty::FnPtr(sig_tys, _) => Some((
1073 DefIdOrName::Name("function pointer"),
1074 sig_tys.output(),
1075 sig_tys.inputs(),
1076 )),
1077 ty::FnDef(def_id, _) => {
1078 let fn_sig = found.fn_sig(self.tcx);
1079 Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs()))
1080 }
1081 ty::Closure(def_id, args) => {
1082 let fn_sig = args.as_closure().sig();
1083 Some((
1084 DefIdOrName::DefId(def_id),
1085 fn_sig.output(),
1086 fn_sig.inputs().map_bound(|inputs| inputs[0].tuple_fields().as_slice()),
1087 ))
1088 }
1089 ty::CoroutineClosure(def_id, args) => {
1090 let sig_parts = args.as_coroutine_closure().coroutine_closure_sig();
1091 Some((
1092 DefIdOrName::DefId(def_id),
1093 sig_parts.map_bound(|sig| {
1094 sig.to_coroutine(
1095 self.tcx,
1096 args.as_coroutine_closure().parent_args(),
1097 self.next_ty_var(DUMMY_SP),
1100 self.tcx.coroutine_for_closure(def_id),
1101 self.next_ty_var(DUMMY_SP),
1102 )
1103 }),
1104 sig_parts.map_bound(|sig| sig.tupled_inputs_ty.tuple_fields().as_slice()),
1105 ))
1106 }
1107 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => {
1108 self.tcx.item_self_bounds(def_id).instantiate(self.tcx, args).iter().find_map(
1109 |pred| {
1110 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1111 && self
1112 .tcx
1113 .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1114 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1116 {
1117 Some((
1118 DefIdOrName::DefId(def_id),
1119 pred.kind().rebind(proj.term.expect_type()),
1120 pred.kind().rebind(args.as_slice()),
1121 ))
1122 } else {
1123 None
1124 }
1125 },
1126 )
1127 }
1128 ty::Dynamic(data, _) => data.iter().find_map(|pred| {
1129 if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder()
1130 && self.tcx.is_lang_item(proj.def_id, LangItem::FnOnceOutput)
1131 && let ty::Tuple(args) = proj.args.type_at(0).kind()
1133 {
1134 Some((
1135 DefIdOrName::Name("trait object"),
1136 pred.rebind(proj.term.expect_type()),
1137 pred.rebind(args.as_slice()),
1138 ))
1139 } else {
1140 None
1141 }
1142 }),
1143 ty::Param(param) => {
1144 let generics = self.tcx.generics_of(body_id);
1145 let name = if generics.count() > param.index as usize
1146 && let def = generics.param_at(param.index as usize, self.tcx)
1147 && #[allow(non_exhaustive_omitted_patterns)] match def.kind {
ty::GenericParamDefKind::Type { .. } => true,
_ => false,
}matches!(def.kind, ty::GenericParamDefKind::Type { .. })
1148 && def.name == param.name
1149 {
1150 DefIdOrName::DefId(def.def_id)
1151 } else {
1152 DefIdOrName::Name("type parameter")
1153 };
1154 param_env.caller_bounds().iter().find_map(|pred| {
1155 if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder()
1156 && self
1157 .tcx
1158 .is_lang_item(proj.projection_term.def_id, LangItem::FnOnceOutput)
1159 && proj.projection_term.self_ty() == found
1160 && let ty::Tuple(args) = proj.projection_term.args.type_at(1).kind()
1162 {
1163 Some((
1164 name,
1165 pred.kind().rebind(proj.term.expect_type()),
1166 pred.kind().rebind(args.as_slice()),
1167 ))
1168 } else {
1169 None
1170 }
1171 })
1172 }
1173 _ => None,
1174 })
1175 else {
1176 return None;
1177 };
1178
1179 let output = self.instantiate_binder_with_fresh_vars(
1180 DUMMY_SP,
1181 BoundRegionConversionTime::FnCall,
1182 output,
1183 );
1184 let inputs = inputs
1185 .skip_binder()
1186 .iter()
1187 .map(|ty| {
1188 self.instantiate_binder_with_fresh_vars(
1189 DUMMY_SP,
1190 BoundRegionConversionTime::FnCall,
1191 inputs.rebind(*ty),
1192 )
1193 })
1194 .collect();
1195
1196 let InferOk { value: output, obligations: _ } =
1200 self.at(&ObligationCause::dummy(), param_env).normalize(output);
1201
1202 if output.is_ty_var() { None } else { Some((def_id_or_name, output, inputs)) }
1203 }
1204
1205 pub(super) fn suggest_add_reference_to_arg(
1206 &self,
1207 obligation: &PredicateObligation<'tcx>,
1208 err: &mut Diag<'_>,
1209 poly_trait_pred: ty::PolyTraitPredicate<'tcx>,
1210 has_custom_message: bool,
1211 ) -> bool {
1212 let span = obligation.cause.span;
1213 let param_env = obligation.param_env;
1214
1215 let mk_result = |trait_pred_and_new_ty| {
1216 let obligation =
1217 self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty);
1218 self.predicate_must_hold_modulo_regions(&obligation)
1219 };
1220
1221 let code = match obligation.cause.code() {
1222 ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code,
1223 c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
1226 if self.tcx.hir_span(*hir_id).lo() == span.lo() =>
1227 {
1228 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id)
1232 && let hir::ExprKind::Call(base, _) = expr.kind
1233 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) = base.kind
1234 && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id)
1235 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind
1236 && ty.span == span
1237 {
1238 let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| {
1244 (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1245 });
1246 let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| {
1247 (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty()))
1248 });
1249
1250 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1251 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1252 let sugg_msg = |pre: &str| {
1253 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you likely meant to call the associated function `{0}` for type `&{2}{1}`, but the code as written calls associated function `{0}` on type `{1}`",
segment.ident, poly_trait_pred.self_ty(), pre))
})format!(
1254 "you likely meant to call the associated function `{FN}` for type \
1255 `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \
1256 type `{TY}`",
1257 FN = segment.ident,
1258 TY = poly_trait_pred.self_ty(),
1259 )
1260 };
1261 match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl) {
1262 (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => {
1263 err.multipart_suggestion(
1264 sugg_msg(mtbl.prefix_str()),
1265 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(outer.span.shrink_to_lo(), "<".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
1266 (outer.span.shrink_to_lo(), "<".to_string()),
1267 (span.shrink_to_hi(), ">".to_string()),
1268 ],
1269 Applicability::MachineApplicable,
1270 );
1271 }
1272 (true, _, hir::Mutability::Mut) => {
1273 err.multipart_suggestion(
1275 sugg_msg("mut "),
1276 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(outer.span.shrink_to_lo().until(span), "<&".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
1277 (outer.span.shrink_to_lo().until(span), "<&".to_string()),
1278 (span.shrink_to_hi(), ">".to_string()),
1279 ],
1280 Applicability::MachineApplicable,
1281 );
1282 }
1283 (_, true, hir::Mutability::Not) => {
1284 err.multipart_suggestion(
1285 sugg_msg(""),
1286 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(outer.span.shrink_to_lo().until(span), "<&mut ".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
1287 (outer.span.shrink_to_lo().until(span), "<&mut ".to_string()),
1288 (span.shrink_to_hi(), ">".to_string()),
1289 ],
1290 Applicability::MachineApplicable,
1291 );
1292 }
1293 _ => {}
1294 }
1295 return false;
1297 }
1298 c
1299 }
1300 c if #[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1301 span.ctxt().outer_expn_data().kind,
1302 ExpnKind::Desugaring(DesugaringKind::ForLoop)
1303 ) =>
1304 {
1305 c
1306 }
1307 _ => return false,
1308 };
1309
1310 let mut never_suggest_borrow: Vec<_> =
1314 [LangItem::Copy, LangItem::Clone, LangItem::Unpin, LangItem::Sized]
1315 .iter()
1316 .filter_map(|lang_item| self.tcx.lang_items().get(*lang_item))
1317 .collect();
1318
1319 if let Some(def_id) = self.tcx.get_diagnostic_item(sym::Send) {
1320 never_suggest_borrow.push(def_id);
1321 }
1322
1323 let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>,
1325 blacklist: &[DefId]|
1326 -> bool {
1327 if blacklist.contains(&old_pred.def_id()) {
1328 return false;
1329 }
1330 let trait_pred_and_imm_ref = old_pred.map_bound(|trait_pred| {
1332 (
1333 trait_pred,
1334 Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1335 )
1336 });
1337 let trait_pred_and_mut_ref = old_pred.map_bound(|trait_pred| {
1338 (
1339 trait_pred,
1340 Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, trait_pred.self_ty()),
1341 )
1342 });
1343
1344 let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref);
1345 let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref);
1346
1347 let (ref_inner_ty_satisfies_pred, ref_inner_ty_is_mut) =
1348 if let ObligationCauseCode::WhereClauseInExpr(..) = obligation.cause.code()
1349 && let ty::Ref(_, ty, mutability) = old_pred.self_ty().skip_binder().kind()
1350 {
1351 (
1352 mk_result(old_pred.map_bound(|trait_pred| (trait_pred, *ty))),
1353 mutability.is_mut(),
1354 )
1355 } else {
1356 (false, false)
1357 };
1358
1359 let is_immut = imm_ref_self_ty_satisfies_pred
1360 || (ref_inner_ty_satisfies_pred && !ref_inner_ty_is_mut);
1361 let is_mut = mut_ref_self_ty_satisfies_pred || ref_inner_ty_is_mut;
1362 if !is_immut && !is_mut {
1363 return false;
1364 }
1365 let Ok(_snippet) = self.tcx.sess.source_map().span_to_snippet(span) else {
1366 return false;
1367 };
1368 if !#[allow(non_exhaustive_omitted_patterns)] match span.ctxt().outer_expn_data().kind
{
ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => true,
_ => false,
}matches!(
1376 span.ctxt().outer_expn_data().kind,
1377 ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop)
1378 ) {
1379 return false;
1380 }
1381 let mut label = || {
1388 let is_sized = match obligation.predicate.kind().skip_binder() {
1391 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => {
1392 self.tcx.is_lang_item(trait_pred.def_id(), LangItem::Sized)
1393 }
1394 _ => false,
1395 };
1396
1397 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait bound `{0}` is not satisfied",
self.tcx.short_string(old_pred, err.long_ty_path())))
})format!(
1398 "the trait bound `{}` is not satisfied",
1399 self.tcx.short_string(old_pred, err.long_ty_path()),
1400 );
1401 let self_ty_str = self.tcx.short_string(old_pred.self_ty(), err.long_ty_path());
1402 let trait_path = self
1403 .tcx
1404 .short_string(old_pred.print_modifiers_and_trait_path(), err.long_ty_path());
1405
1406 if has_custom_message {
1407 let msg = if is_sized {
1408 "the trait bound `Sized` is not satisfied".into()
1409 } else {
1410 msg
1411 };
1412 err.note(msg);
1413 } else {
1414 err.messages = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(rustc_errors::DiagMessage::from(msg), Style::NoStyle)]))vec![(rustc_errors::DiagMessage::from(msg), Style::NoStyle)];
1415 }
1416 if is_sized {
1417 err.span_label(
1418 span,
1419 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `Sized` is not implemented for `{0}`",
self_ty_str))
})format!("the trait `Sized` is not implemented for `{self_ty_str}`"),
1420 );
1421 } else {
1422 err.span_label(
1423 span,
1424 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `{0}` is not implemented for `{1}`",
trait_path, self_ty_str))
})format!("the trait `{trait_path}` is not implemented for `{self_ty_str}`"),
1425 );
1426 }
1427 };
1428
1429 let mut sugg_prefixes = ::alloc::vec::Vec::new()vec![];
1430 if is_immut {
1431 sugg_prefixes.push("&");
1432 }
1433 if is_mut {
1434 sugg_prefixes.push("&mut ");
1435 }
1436 let sugg_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider{0} borrowing here",
if is_mut && !is_immut { " mutably" } else { "" }))
})format!(
1437 "consider{} borrowing here",
1438 if is_mut && !is_immut { " mutably" } else { "" },
1439 );
1440
1441 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
1445 return false;
1446 };
1447 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
1448 expr_finder.visit_expr(body.value);
1449
1450 if let Some(ty) = expr_finder.ty_result {
1451 if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(ty.hir_id)
1452 && let hir::ExprKind::Path(hir::QPath::TypeRelative(_, _)) = expr.kind
1453 && ty.span == span
1454 {
1455 label();
1458 err.multipart_suggestions(
1459 sugg_msg,
1460 sugg_prefixes.into_iter().map(|sugg_prefix| {
1461 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}", sugg_prefix))
})), (span.shrink_to_hi(), ">".to_string())]))vec![
1462 (span.shrink_to_lo(), format!("<{sugg_prefix}")),
1463 (span.shrink_to_hi(), ">".to_string()),
1464 ]
1465 }),
1466 Applicability::MaybeIncorrect,
1467 );
1468 return true;
1469 }
1470 return false;
1471 }
1472 let Some(expr) = expr_finder.result else {
1473 return false;
1474 };
1475 if let hir::ExprKind::AddrOf(_, _, _) = expr.kind {
1476 return false;
1477 }
1478 let needs_parens_post = expr_needs_parens(expr);
1479 let needs_parens_pre = match self.tcx.parent_hir_node(expr.hir_id) {
1480 Node::Expr(e)
1481 if let hir::ExprKind::MethodCall(_, base, _, _) = e.kind
1482 && base.hir_id == expr.hir_id =>
1483 {
1484 true
1485 }
1486 _ => false,
1487 };
1488
1489 label();
1490 let suggestions = sugg_prefixes.into_iter().map(|sugg_prefix| {
1491 match (needs_parens_pre, needs_parens_post) {
1492 (false, false) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), sugg_prefix.to_string())]))vec![(span.shrink_to_lo(), sugg_prefix.to_string())],
1493 (false, true) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}(", sugg_prefix))
})), (span.shrink_to_hi(), ")".to_string())]))vec![
1496 (span.shrink_to_lo(), format!("{sugg_prefix}(")),
1497 (span.shrink_to_hi(), ")".to_string()),
1498 ],
1499 (true, false) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}", sugg_prefix))
})), (span.shrink_to_hi(), ")".to_string())]))vec![
1502 (span.shrink_to_lo(), format!("({sugg_prefix}")),
1503 (span.shrink_to_hi(), ")".to_string()),
1504 ],
1505 (true, true) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}(", sugg_prefix))
})), (span.shrink_to_hi(), "))".to_string())]))vec![
1506 (span.shrink_to_lo(), format!("({sugg_prefix}(")),
1507 (span.shrink_to_hi(), "))".to_string()),
1508 ],
1509 }
1510 });
1511 err.multipart_suggestions(sugg_msg, suggestions, Applicability::MaybeIncorrect);
1512 return true;
1513 };
1514
1515 if let ObligationCauseCode::ImplDerived(cause) = &*code {
1516 try_borrowing(cause.derived.parent_trait_pred, &[])
1517 } else if let ObligationCauseCode::WhereClause(..)
1518 | ObligationCauseCode::WhereClauseInExpr(..) = code
1519 {
1520 try_borrowing(poly_trait_pred, &never_suggest_borrow)
1521 } else {
1522 false
1523 }
1524 }
1525
1526 pub(super) fn suggest_borrowing_for_object_cast(
1528 &self,
1529 err: &mut Diag<'_>,
1530 obligation: &PredicateObligation<'tcx>,
1531 self_ty: Ty<'tcx>,
1532 target_ty: Ty<'tcx>,
1533 ) {
1534 let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else {
1535 return;
1536 };
1537 let ty::Dynamic(predicates, _) = object_ty.kind() else {
1538 return;
1539 };
1540 let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty);
1541
1542 for predicate in predicates.iter() {
1543 if !self.predicate_must_hold_modulo_regions(
1544 &obligation.with(self.tcx, predicate.with_self_ty(self.tcx, self_ref_ty)),
1545 ) {
1546 return;
1547 }
1548 }
1549
1550 err.span_suggestion_verbose(
1551 obligation.cause.span.shrink_to_lo(),
1552 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider borrowing the value, since `&{0}` can be coerced into `{1}`",
self_ty, target_ty))
})format!(
1553 "consider borrowing the value, since `&{self_ty}` can be coerced into `{target_ty}`"
1554 ),
1555 "&",
1556 Applicability::MaybeIncorrect,
1557 );
1558 }
1559
1560 pub(super) fn suggest_remove_reference(
1563 &self,
1564 obligation: &PredicateObligation<'tcx>,
1565 err: &mut Diag<'_>,
1566 trait_pred: ty::PolyTraitPredicate<'tcx>,
1567 ) -> bool {
1568 let mut span = obligation.cause.span;
1569 let mut trait_pred = trait_pred;
1570 let mut code = obligation.cause.code();
1571 while let Some((c, Some(parent_trait_pred))) = code.parent_with_predicate() {
1572 code = c;
1575 trait_pred = parent_trait_pred;
1576 }
1577 while span.desugaring_kind().is_some() {
1578 span.remove_mark();
1580 }
1581 let mut expr_finder = super::FindExprBySpan::new(span, self.tcx);
1582 let Some(body) = self.tcx.hir_maybe_body_owned_by(obligation.cause.body_id) else {
1583 return false;
1584 };
1585 expr_finder.visit_expr(body.value);
1586 let mut maybe_suggest = |suggested_ty, count, suggestions| {
1587 let trait_pred_and_suggested_ty =
1589 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1590
1591 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1592 obligation.param_env,
1593 trait_pred_and_suggested_ty,
1594 );
1595
1596 if self.predicate_may_hold(&new_obligation) {
1597 let msg = if count == 1 {
1598 "consider removing the leading `&`-reference".to_string()
1599 } else {
1600 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing {0} leading `&`-references",
count))
})format!("consider removing {count} leading `&`-references")
1601 };
1602
1603 err.multipart_suggestion(msg, suggestions, Applicability::MachineApplicable);
1604 true
1605 } else {
1606 false
1607 }
1608 };
1609
1610 let mut count = 0;
1613 let mut suggestions = ::alloc::vec::Vec::new()vec![];
1614 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1616 if let Some(mut hir_ty) = expr_finder.ty_result {
1617 while let hir::TyKind::Ref(_, mut_ty) = &hir_ty.kind {
1618 count += 1;
1619 let span = hir_ty.span.until(mut_ty.ty.span);
1620 suggestions.push((span, String::new()));
1621
1622 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1623 break;
1624 };
1625 suggested_ty = *inner_ty;
1626
1627 hir_ty = mut_ty.ty;
1628
1629 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1630 return true;
1631 }
1632 }
1633 }
1634
1635 let Some(mut expr) = expr_finder.result else {
1637 return false;
1638 };
1639 let mut count = 0;
1640 let mut suggestions = ::alloc::vec::Vec::new()vec![];
1641 let mut suggested_ty = trait_pred.self_ty().skip_binder();
1643 'outer: loop {
1644 while let hir::ExprKind::AddrOf(_, _, borrowed) = expr.kind {
1645 count += 1;
1646 let span =
1647 if let Some(borrowed_span) = borrowed.span.find_ancestor_inside(expr.span) {
1648 expr.span.until(borrowed_span)
1649 } else {
1650 break 'outer;
1651 };
1652
1653 match self.tcx.sess.source_map().span_to_snippet(span) {
1656 Ok(snippet) if snippet.starts_with("&") => {}
1657 _ => break 'outer,
1658 }
1659
1660 suggestions.push((span, String::new()));
1661
1662 let ty::Ref(_, inner_ty, _) = suggested_ty.kind() else {
1663 break 'outer;
1664 };
1665 suggested_ty = *inner_ty;
1666
1667 expr = borrowed;
1668
1669 if maybe_suggest(suggested_ty, count, suggestions.clone()) {
1670 return true;
1671 }
1672 }
1673 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1674 && let Res::Local(hir_id) = path.res
1675 && let hir::Node::Pat(binding) = self.tcx.hir_node(hir_id)
1676 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
1677 && let None = local.ty
1678 && let Some(binding_expr) = local.init
1679 {
1680 expr = binding_expr;
1681 } else {
1682 break 'outer;
1683 }
1684 }
1685 false
1686 }
1687
1688 pub(super) fn suggest_remove_await(
1689 &self,
1690 obligation: &PredicateObligation<'tcx>,
1691 err: &mut Diag<'_>,
1692 ) {
1693 if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives()
1694 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1695 {
1696 if let Some((_, hir::Node::Expr(await_expr))) = self.tcx.hir_parent_iter(*hir_id).nth(1)
1703 && let Some(expr_span) = expr.span.find_ancestor_inside_same_ctxt(await_expr.span)
1704 {
1705 let removal_span = self
1706 .tcx
1707 .sess
1708 .source_map()
1709 .span_extend_while_whitespace(expr_span)
1710 .shrink_to_hi()
1711 .to(await_expr.span.shrink_to_hi());
1712 err.span_suggestion_verbose(
1713 removal_span,
1714 "remove the `.await`",
1715 "",
1716 Applicability::MachineApplicable,
1717 );
1718 } else {
1719 err.span_label(obligation.cause.span, "remove the `.await`");
1720 }
1721 if let hir::Expr { span, kind: hir::ExprKind::Call(base, _), .. } = expr {
1723 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
1724 obligation.predicate.kind().skip_binder()
1725 {
1726 err.span_label(*span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this call returns `{0}`",
pred.self_ty()))
})format!("this call returns `{}`", pred.self_ty()));
1727 }
1728 if let Some(typeck_results) = &self.typeck_results
1729 && let ty = typeck_results.expr_ty_adjusted(base)
1730 && let ty::FnDef(def_id, _args) = ty.kind()
1731 && let Some(hir::Node::Item(item)) = self.tcx.hir_get_if_local(*def_id)
1732 {
1733 let (ident, _, _, _) = item.expect_fn();
1734 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alternatively, consider making `fn {0}` asynchronous",
ident))
})format!("alternatively, consider making `fn {ident}` asynchronous");
1735 if item.vis_span.is_empty() {
1736 err.span_suggestion_verbose(
1737 item.span.shrink_to_lo(),
1738 msg,
1739 "async ",
1740 Applicability::MaybeIncorrect,
1741 );
1742 } else {
1743 err.span_suggestion_verbose(
1744 item.vis_span.shrink_to_hi(),
1745 msg,
1746 " async",
1747 Applicability::MaybeIncorrect,
1748 );
1749 }
1750 }
1751 }
1752 }
1753 }
1754
1755 pub(super) fn suggest_change_mut(
1758 &self,
1759 obligation: &PredicateObligation<'tcx>,
1760 err: &mut Diag<'_>,
1761 trait_pred: ty::PolyTraitPredicate<'tcx>,
1762 ) {
1763 let points_at_arg =
1764 #[allow(non_exhaustive_omitted_patterns)] match obligation.cause.code() {
ObligationCauseCode::FunctionArg { .. } => true,
_ => false,
}matches!(obligation.cause.code(), ObligationCauseCode::FunctionArg { .. },);
1765
1766 let span = obligation.cause.span;
1767 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1768 let refs_number =
1769 snippet.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c == '&').count();
1770 if let Some('\'') = snippet.chars().filter(|c| !c.is_whitespace()).nth(refs_number) {
1771 return;
1773 }
1774 let trait_pred = self.resolve_vars_if_possible(trait_pred);
1775 if trait_pred.has_non_region_infer() {
1776 return;
1779 }
1780
1781 if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind()
1783 {
1784 let suggested_ty = match mutability {
1785 hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type),
1786 hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type),
1787 };
1788
1789 let trait_pred_and_suggested_ty =
1791 trait_pred.map_bound(|trait_pred| (trait_pred, suggested_ty));
1792
1793 let new_obligation = self.mk_trait_obligation_with_new_self_ty(
1794 obligation.param_env,
1795 trait_pred_and_suggested_ty,
1796 );
1797 let suggested_ty_would_satisfy_obligation = self
1798 .evaluate_obligation_no_overflow(&new_obligation)
1799 .must_apply_modulo_regions();
1800 if suggested_ty_would_satisfy_obligation {
1801 let sp = self
1802 .tcx
1803 .sess
1804 .source_map()
1805 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
1806 if points_at_arg && mutability.is_not() && refs_number > 0 {
1807 if snippet
1809 .trim_start_matches(|c: char| c.is_whitespace() || c == '&')
1810 .starts_with("mut")
1811 {
1812 return;
1813 }
1814 err.span_suggestion_verbose(
1815 sp,
1816 "consider changing this borrow's mutability",
1817 "&mut ",
1818 Applicability::MachineApplicable,
1819 );
1820 } else {
1821 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is implemented for `{1}`, but not for `{2}`",
trait_pred.print_modifiers_and_trait_path(), suggested_ty,
trait_pred.skip_binder().self_ty()))
})format!(
1822 "`{}` is implemented for `{}`, but not for `{}`",
1823 trait_pred.print_modifiers_and_trait_path(),
1824 suggested_ty,
1825 trait_pred.skip_binder().self_ty(),
1826 ));
1827 }
1828 }
1829 }
1830 }
1831 }
1832
1833 pub(super) fn suggest_semicolon_removal(
1834 &self,
1835 obligation: &PredicateObligation<'tcx>,
1836 err: &mut Diag<'_>,
1837 span: Span,
1838 trait_pred: ty::PolyTraitPredicate<'tcx>,
1839 ) -> bool {
1840 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
1841 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn {sig, body: body_id, .. }, .. }) = node
1842 && let hir::ExprKind::Block(blk, _) = &self.tcx.hir_body(*body_id).value.kind
1843 && sig.decl.output.span().overlaps(span)
1844 && blk.expr.is_none()
1845 && trait_pred.self_ty().skip_binder().is_unit()
1846 && let Some(stmt) = blk.stmts.last()
1847 && let hir::StmtKind::Semi(expr) = stmt.kind
1848 && let Some(typeck_results) = &self.typeck_results
1850 && let Some(ty) = typeck_results.expr_ty_opt(expr)
1851 && self.predicate_may_hold(&self.mk_trait_obligation_with_new_self_ty(
1852 obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, ty))
1853 ))
1854 {
1855 err.span_label(
1856 expr.span,
1857 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this expression has type `{0}`, which implements `{1}`",
ty, trait_pred.print_modifiers_and_trait_path()))
})format!(
1858 "this expression has type `{}`, which implements `{}`",
1859 ty,
1860 trait_pred.print_modifiers_and_trait_path()
1861 ),
1862 );
1863 err.span_suggestion(
1864 self.tcx.sess.source_map().end_point(stmt.span),
1865 "remove this semicolon",
1866 "",
1867 Applicability::MachineApplicable,
1868 );
1869 return true;
1870 }
1871 false
1872 }
1873
1874 pub(super) fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> {
1875 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig, .. }, .. }) =
1876 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
1877 else {
1878 return None;
1879 };
1880
1881 if let hir::FnRetTy::Return(ret_ty) = sig.decl.output { Some(ret_ty.span) } else { None }
1882 }
1883
1884 pub(super) fn suggest_impl_trait(
1888 &self,
1889 err: &mut Diag<'_>,
1890 obligation: &PredicateObligation<'tcx>,
1891 trait_pred: ty::PolyTraitPredicate<'tcx>,
1892 ) -> bool {
1893 let ObligationCauseCode::SizedReturnType = obligation.cause.code() else {
1894 return false;
1895 };
1896 let ty::Dynamic(_, _) = trait_pred.self_ty().skip_binder().kind() else {
1897 return false;
1898 };
1899 if let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
1900 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
1901 | Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, _), .. }) =
1902 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
1903 && let hir::FnRetTy::Return(ty) = fn_sig.decl.output
1904 && let hir::TyKind::Path(qpath) = ty.kind
1905 && let hir::QPath::Resolved(None, path) = qpath
1906 && let Res::Def(DefKind::TyAlias, def_id) = path.res
1907 {
1908 err.span_note(self.tcx.def_span(def_id), "this type alias is unsized");
1912 err.multipart_suggestion(
1913 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider boxing the return type, and wrapping all of the returned values in `Box::new`"))
})format!(
1914 "consider boxing the return type, and wrapping all of the returned values in \
1915 `Box::new`",
1916 ),
1917 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ty.span.shrink_to_lo(), "Box<".to_string()),
(ty.span.shrink_to_hi(), ">".to_string())]))vec![
1918 (ty.span.shrink_to_lo(), "Box<".to_string()),
1919 (ty.span.shrink_to_hi(), ">".to_string()),
1920 ],
1921 Applicability::MaybeIncorrect,
1922 );
1923 return false;
1924 }
1925
1926 err.code(E0746);
1927 err.primary_message("return type cannot be a trait object without pointer indirection");
1928 err.children.clear();
1929
1930 let mut span = obligation.cause.span;
1931 if let DefKind::Closure = self.tcx.def_kind(obligation.cause.body_id)
1932 && let parent = self.tcx.parent(obligation.cause.body_id.into())
1933 && let DefKind::Fn | DefKind::AssocFn = self.tcx.def_kind(parent)
1934 && self.tcx.asyncness(parent).is_async()
1935 && let Some(parent) = parent.as_local()
1936 && let Node::Item(hir::Item { kind: hir::ItemKind::Fn { sig: fn_sig, .. }, .. })
1937 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(fn_sig, _), .. })
1938 | Node::TraitItem(hir::TraitItem {
1939 kind: hir::TraitItemKind::Fn(fn_sig, _), ..
1940 }) = self.tcx.hir_node_by_def_id(parent)
1941 {
1942 span = fn_sig.decl.output.span();
1947 err.span(span);
1948 }
1949 let body = self.tcx.hir_body_owned_by(obligation.cause.body_id);
1950
1951 let mut visitor = ReturnsVisitor::default();
1952 visitor.visit_body(&body);
1953
1954 let (pre, impl_span) = if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span)
1955 && snip.starts_with("dyn ")
1956 {
1957 ("", span.with_hi(span.lo() + BytePos(4)))
1958 } else {
1959 ("dyn ", span.shrink_to_lo())
1960 };
1961
1962 err.span_suggestion_verbose(
1963 impl_span,
1964 "consider returning an `impl Trait` instead of a `dyn Trait`",
1965 "impl ",
1966 Applicability::MaybeIncorrect,
1967 );
1968
1969 let mut sugg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Box<{0}", pre))
})), (span.shrink_to_hi(), ">".to_string())]))vec![
1970 (span.shrink_to_lo(), format!("Box<{pre}")),
1971 (span.shrink_to_hi(), ">".to_string()),
1972 ];
1973 sugg.extend(visitor.returns.into_iter().flat_map(|expr| {
1974 let span =
1975 expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span);
1976 if !span.can_be_used_for_suggestions() {
1977 ::alloc::vec::Vec::new()vec![]
1978 } else if let hir::ExprKind::Call(path, ..) = expr.kind
1979 && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind
1980 && method.ident.name == sym::new
1981 && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind
1982 && box_path
1983 .res
1984 .opt_def_id()
1985 .is_some_and(|def_id| self.tcx.is_lang_item(def_id, LangItem::OwnedBox))
1986 {
1987 ::alloc::vec::Vec::new()vec![]
1989 } else {
1990 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "Box::new(".to_string()),
(span.shrink_to_hi(), ")".to_string())]))vec![
1991 (span.shrink_to_lo(), "Box::new(".to_string()),
1992 (span.shrink_to_hi(), ")".to_string()),
1993 ]
1994 }
1995 }));
1996
1997 err.multipart_suggestion(
1998 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alternatively, box the return type, and wrap all of the returned values in `Box::new`"))
})format!(
1999 "alternatively, box the return type, and wrap all of the returned values in \
2000 `Box::new`",
2001 ),
2002 sugg,
2003 Applicability::MaybeIncorrect,
2004 );
2005
2006 true
2007 }
2008
2009 pub(super) fn report_closure_arg_mismatch(
2010 &self,
2011 span: Span,
2012 found_span: Option<Span>,
2013 found: ty::TraitRef<'tcx>,
2014 expected: ty::TraitRef<'tcx>,
2015 cause: &ObligationCauseCode<'tcx>,
2016 found_node: Option<Node<'_>>,
2017 param_env: ty::ParamEnv<'tcx>,
2018 ) -> Diag<'a> {
2019 pub(crate) fn build_fn_sig_ty<'tcx>(
2020 infcx: &InferCtxt<'tcx>,
2021 trait_ref: ty::TraitRef<'tcx>,
2022 ) -> Ty<'tcx> {
2023 let inputs = trait_ref.args.type_at(1);
2024 let sig = match inputs.kind() {
2025 ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id) => {
2026 infcx.tcx.mk_fn_sig(
2027 *inputs,
2028 infcx.next_ty_var(DUMMY_SP),
2029 false,
2030 hir::Safety::Safe,
2031 ExternAbi::Rust,
2032 )
2033 }
2034 _ => infcx.tcx.mk_fn_sig(
2035 [inputs],
2036 infcx.next_ty_var(DUMMY_SP),
2037 false,
2038 hir::Safety::Safe,
2039 ExternAbi::Rust,
2040 ),
2041 };
2042
2043 Ty::new_fn_ptr(infcx.tcx, ty::Binder::dummy(sig))
2044 }
2045
2046 let argument_kind = match expected.self_ty().kind() {
2047 ty::Closure(..) => "closure",
2048 ty::Coroutine(..) => "coroutine",
2049 _ => "function",
2050 };
2051 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type mismatch in {0} arguments",
argument_kind))
})).with_code(E0631)
}struct_span_code_err!(
2052 self.dcx(),
2053 span,
2054 E0631,
2055 "type mismatch in {argument_kind} arguments",
2056 );
2057
2058 err.span_label(span, "expected due to this");
2059
2060 let found_span = found_span.unwrap_or(span);
2061 err.span_label(found_span, "found signature defined here");
2062
2063 let expected = build_fn_sig_ty(self, expected);
2064 let found = build_fn_sig_ty(self, found);
2065
2066 let (expected_str, found_str) = self.cmp(expected, found);
2067
2068 let signature_kind = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} signature", argument_kind))
})format!("{argument_kind} signature");
2069 err.note_expected_found(&signature_kind, expected_str, &signature_kind, found_str);
2070
2071 self.note_conflicting_fn_args(&mut err, cause, expected, found, param_env);
2072 self.note_conflicting_closure_bounds(cause, &mut err);
2073
2074 if let Some(found_node) = found_node {
2075 hint_missing_borrow(self, param_env, span, found, expected, found_node, &mut err);
2076 }
2077
2078 err
2079 }
2080
2081 fn note_conflicting_fn_args(
2082 &self,
2083 err: &mut Diag<'_>,
2084 cause: &ObligationCauseCode<'tcx>,
2085 expected: Ty<'tcx>,
2086 found: Ty<'tcx>,
2087 param_env: ty::ParamEnv<'tcx>,
2088 ) {
2089 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = cause else {
2090 return;
2091 };
2092 let ty::FnPtr(sig_tys, hdr) = expected.kind() else {
2093 return;
2094 };
2095 let expected = sig_tys.with(*hdr);
2096 let ty::FnPtr(sig_tys, hdr) = found.kind() else {
2097 return;
2098 };
2099 let found = sig_tys.with(*hdr);
2100 let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) else {
2101 return;
2102 };
2103 let hir::ExprKind::Path(path) = arg.kind else {
2104 return;
2105 };
2106 let expected_inputs = self.tcx.instantiate_bound_regions_with_erased(expected).inputs();
2107 let found_inputs = self.tcx.instantiate_bound_regions_with_erased(found).inputs();
2108 let both_tys = expected_inputs.iter().copied().zip(found_inputs.iter().copied());
2109
2110 let arg_expr = |infcx: &InferCtxt<'tcx>, name, expected: Ty<'tcx>, found: Ty<'tcx>| {
2111 let (expected_ty, expected_refs) = get_deref_type_and_refs(expected);
2112 let (found_ty, found_refs) = get_deref_type_and_refs(found);
2113
2114 if infcx.can_eq(param_env, found_ty, expected_ty) {
2115 if found_refs.len() == expected_refs.len()
2116 && found_refs.iter().eq(expected_refs.iter())
2117 {
2118 name
2119 } else if found_refs.len() > expected_refs.len() {
2120 let refs = &found_refs[..found_refs.len() - expected_refs.len()];
2121 if found_refs[..expected_refs.len()].iter().eq(expected_refs.iter()) {
2122 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
refs.iter().map(|mutbl|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}",
mutbl.prefix_str()))
})).collect::<Vec<_>>().join(""), name))
})format!(
2123 "{}{name}",
2124 refs.iter()
2125 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2126 .collect::<Vec<_>>()
2127 .join(""),
2128 )
2129 } else {
2130 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}*{1}",
refs.iter().map(|mutbl|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}",
mutbl.prefix_str()))
})).collect::<Vec<_>>().join(""), name))
})format!(
2132 "{}*{name}",
2133 refs.iter()
2134 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2135 .collect::<Vec<_>>()
2136 .join(""),
2137 )
2138 }
2139 } else if expected_refs.len() > found_refs.len() {
2140 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
(0..(expected_refs.len() -
found_refs.len())).map(|_|
"*").collect::<Vec<_>>().join(""), name))
})format!(
2141 "{}{name}",
2142 (0..(expected_refs.len() - found_refs.len()))
2143 .map(|_| "*")
2144 .collect::<Vec<_>>()
2145 .join(""),
2146 )
2147 } else {
2148 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}",
found_refs.iter().map(|mutbl|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}",
mutbl.prefix_str()))
})).chain(found_refs.iter().map(|_|
"*".to_string())).collect::<Vec<_>>().join(""), name))
})format!(
2149 "{}{name}",
2150 found_refs
2151 .iter()
2152 .map(|mutbl| format!("&{}", mutbl.prefix_str()))
2153 .chain(found_refs.iter().map(|_| "*".to_string()))
2154 .collect::<Vec<_>>()
2155 .join(""),
2156 )
2157 }
2158 } else {
2159 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", found))
})format!("/* {found} */")
2160 }
2161 };
2162 let args_have_same_underlying_type = both_tys.clone().all(|(expected, found)| {
2163 let (expected_ty, _) = get_deref_type_and_refs(expected);
2164 let (found_ty, _) = get_deref_type_and_refs(found);
2165 self.can_eq(param_env, found_ty, expected_ty)
2166 });
2167 let (closure_names, call_names): (Vec<_>, Vec<_>) = if args_have_same_underlying_type
2168 && !expected_inputs.is_empty()
2169 && expected_inputs.len() == found_inputs.len()
2170 && let Some(typeck) = &self.typeck_results
2171 && let Res::Def(res_kind, fn_def_id) = typeck.qpath_res(&path, *arg_hir_id)
2172 && res_kind.is_fn_like()
2173 {
2174 let closure: Vec<_> = self
2175 .tcx
2176 .fn_arg_idents(fn_def_id)
2177 .iter()
2178 .enumerate()
2179 .map(|(i, ident)| {
2180 if let Some(ident) = ident
2181 && !#[allow(non_exhaustive_omitted_patterns)] match ident {
Ident { name: kw::Underscore | kw::SelfLower, .. } => true,
_ => false,
}matches!(ident, Ident { name: kw::Underscore | kw::SelfLower, .. })
2182 {
2183 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", ident))
})format!("{ident}")
2184 } else {
2185 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}")
2186 }
2187 })
2188 .collect();
2189 let args = closure
2190 .iter()
2191 .zip(both_tys)
2192 .map(|(name, (expected, found))| {
2193 arg_expr(self.infcx, name.to_owned(), expected, found)
2194 })
2195 .collect();
2196 (closure, args)
2197 } else {
2198 let closure_args = expected_inputs
2199 .iter()
2200 .enumerate()
2201 .map(|(i, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"))
2202 .collect::<Vec<_>>();
2203 let call_args = both_tys
2204 .enumerate()
2205 .map(|(i, (expected, found))| {
2206 arg_expr(self.infcx, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("arg{0}", i))
})format!("arg{i}"), expected, found)
2207 })
2208 .collect::<Vec<_>>();
2209 (closure_args, call_args)
2210 };
2211 let closure_names: Vec<_> = closure_names
2212 .into_iter()
2213 .zip(expected_inputs.iter())
2214 .map(|(name, ty)| {
2215 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}",
if ty.has_infer_types() {
String::new()
} else if ty.references_error() {
": /* type */".to_string()
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": {0}", ty))
})
}, name))
})format!(
2216 "{name}{}",
2217 if ty.has_infer_types() {
2218 String::new()
2219 } else if ty.references_error() {
2220 ": /* type */".to_string()
2221 } else {
2222 format!(": {ty}")
2223 }
2224 )
2225 })
2226 .collect();
2227 err.multipart_suggestion(
2228 "consider wrapping the function in a closure",
2229 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(arg.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}| ",
closure_names.join(", ")))
})),
(arg.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})",
call_names.join(", ")))
}))]))vec![
2230 (arg.span.shrink_to_lo(), format!("|{}| ", closure_names.join(", "))),
2231 (arg.span.shrink_to_hi(), format!("({})", call_names.join(", "))),
2232 ],
2233 Applicability::MaybeIncorrect,
2234 );
2235 }
2236
2237 fn note_conflicting_closure_bounds(
2240 &self,
2241 cause: &ObligationCauseCode<'tcx>,
2242 err: &mut Diag<'_>,
2243 ) {
2244 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = cause
2248 && let predicates = self.tcx.predicates_of(def_id).instantiate_identity(self.tcx)
2249 && let Some(pred) = predicates.predicates.get(*idx)
2250 && let ty::ClauseKind::Trait(trait_pred) = pred.kind().skip_binder()
2251 && self.tcx.is_fn_trait(trait_pred.def_id())
2252 {
2253 let expected_self =
2254 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty()));
2255 let expected_args =
2256 self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.args));
2257
2258 let other_pred = predicates.into_iter().enumerate().find(|(other_idx, (pred, _))| {
2261 match pred.kind().skip_binder() {
2262 ty::ClauseKind::Trait(trait_pred)
2263 if self.tcx.is_fn_trait(trait_pred.def_id())
2264 && other_idx != idx
2265 && expected_self
2268 == self.tcx.anonymize_bound_vars(
2269 pred.kind().rebind(trait_pred.self_ty()),
2270 )
2271 && expected_args
2273 != self.tcx.anonymize_bound_vars(
2274 pred.kind().rebind(trait_pred.trait_ref.args),
2275 ) =>
2276 {
2277 true
2278 }
2279 _ => false,
2280 }
2281 });
2282 if let Some((_, (_, other_pred_span))) = other_pred {
2284 err.span_note(
2285 other_pred_span,
2286 "closure inferred to have a different signature due to this bound",
2287 );
2288 }
2289 }
2290 }
2291
2292 pub(super) fn suggest_fully_qualified_path(
2293 &self,
2294 err: &mut Diag<'_>,
2295 item_def_id: DefId,
2296 span: Span,
2297 trait_ref: DefId,
2298 ) {
2299 if let Some(assoc_item) = self.tcx.opt_associated_item(item_def_id)
2300 && let ty::AssocKind::Const { .. } | ty::AssocKind::Type { .. } = assoc_item.kind
2301 {
2302 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}s cannot be accessed directly on a `trait`, they can only be accessed through a specific `impl`",
self.tcx.def_kind_descr(assoc_item.as_def_kind(),
item_def_id)))
})format!(
2303 "{}s cannot be accessed directly on a `trait`, they can only be \
2304 accessed through a specific `impl`",
2305 self.tcx.def_kind_descr(assoc_item.as_def_kind(), item_def_id)
2306 ));
2307
2308 if !assoc_item.is_impl_trait_in_trait() {
2309 err.span_suggestion_verbose(
2310 span,
2311 "use the fully qualified path to an implementation",
2312 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<Type as {0}>::{1}",
self.tcx.def_path_str(trait_ref), assoc_item.name()))
})format!(
2313 "<Type as {}>::{}",
2314 self.tcx.def_path_str(trait_ref),
2315 assoc_item.name()
2316 ),
2317 Applicability::HasPlaceholders,
2318 );
2319 }
2320 }
2321 }
2322
2323 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("maybe_note_obligation_cause_for_async_await",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2365u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["obligation.predicate",
"obligation.cause.span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&obligation.predicate)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&obligation.cause.span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
let (mut trait_ref, mut target_ty) =
match obligation.predicate.kind().skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) =>
(Some(p), Some(p.self_ty())),
_ => (None, None),
};
let mut coroutine = None;
let mut outer_coroutine = None;
let mut next_code = Some(obligation.cause.code());
let mut seen_upvar_tys_infer_tuple = false;
while let Some(code) = next_code {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2404",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2404u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["code"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&code) as
&dyn Value))])
});
} else { ; }
};
match code {
ObligationCauseCode::FunctionArg { parent_code, .. } => {
next_code = Some(parent_code);
}
ObligationCauseCode::ImplDerived(cause) => {
let ty =
cause.derived.parent_trait_pred.skip_binder().self_ty();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2411",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2411u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
"parent_trait_ref", "self_ty.kind"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("ImplDerived")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&cause.derived.parent_trait_pred)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty.kind())
as &dyn Value))])
});
} else { ; }
};
match *ty.kind() {
ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
coroutine = coroutine.or(Some(did));
outer_coroutine = Some(did);
}
ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
seen_upvar_tys_infer_tuple = true;
}
_ if coroutine.is_none() => {
trait_ref =
Some(cause.derived.parent_trait_pred.skip_binder());
target_ty = Some(ty);
}
_ => {}
}
next_code = Some(&cause.derived.parent_code);
}
ObligationCauseCode::WellFormedDerived(derived_obligation) |
ObligationCauseCode::BuiltinDerived(derived_obligation) => {
let ty =
derived_obligation.parent_trait_pred.skip_binder().self_ty();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2441",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2441u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["parent_trait_ref",
"self_ty.kind"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&derived_obligation.parent_trait_pred)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty.kind())
as &dyn Value))])
});
} else { ; }
};
match *ty.kind() {
ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
coroutine = coroutine.or(Some(did));
outer_coroutine = Some(did);
}
ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
seen_upvar_tys_infer_tuple = true;
}
_ if coroutine.is_none() => {
trait_ref =
Some(derived_obligation.parent_trait_pred.skip_binder());
target_ty = Some(ty);
}
_ => {}
}
next_code = Some(&derived_obligation.parent_code);
}
_ => break,
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2472",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2472u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["coroutine",
"trait_ref", "target_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_ref)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&target_ty)
as &dyn Value))])
});
} else { ; }
};
let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
(coroutine, trait_ref, target_ty) else { return false; };
let span = self.tcx.def_span(coroutine_did);
let coroutine_did_root =
self.tcx.typeck_root_def_id(coroutine_did);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2482",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2482u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["coroutine_did",
"coroutine_did_root", "typeck_results.hir_owner", "span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine_did)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine_did_root)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.typeck_results.as_ref().map(|t|
t.hir_owner)) as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&span) as
&dyn Value))])
});
} else { ; }
};
let coroutine_body =
coroutine_did.as_local().and_then(|def_id|
self.tcx.hir_maybe_body_owned_by(def_id));
let mut visitor = AwaitsVisitor::default();
if let Some(body) = coroutine_body { visitor.visit_body(&body); }
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2495",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2495u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["awaits"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&visitor.awaits)
as &dyn Value))])
});
} else { ; }
};
let target_ty_erased =
self.tcx.erase_and_anonymize_regions(target_ty);
let ty_matches =
|ty| -> bool
{
let ty_erased =
self.tcx.instantiate_bound_regions_with_erased(ty);
let ty_erased =
self.tcx.erase_and_anonymize_regions(ty_erased);
let eq = ty_erased == target_ty_erased;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2516",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2516u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["ty_erased",
"target_ty_erased", "eq"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty_erased)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&target_ty_erased)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&eq) as
&dyn Value))])
});
} else { ; }
};
eq
};
let coroutine_data =
match &self.typeck_results {
Some(t) if t.hir_owner.to_def_id() == coroutine_did_root =>
CoroutineData(t),
_ if coroutine_did.is_local() => {
CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
}
_ => return false,
};
let coroutine_within_in_progress_typeck =
match &self.typeck_results {
Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
_ => false,
};
let mut interior_or_upvar_span = None;
let from_awaited_ty =
coroutine_data.get_from_await_ty(visitor, self.tcx,
ty_matches);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2540",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2540u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["from_awaited_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&from_awaited_ty)
as &dyn Value))])
});
} else { ; }
};
if coroutine_did.is_local() &&
!coroutine_within_in_progress_typeck &&
let Some(coroutine_info) =
self.tcx.mir_coroutine_witnesses(coroutine_did) {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2548",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2548u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["coroutine_info"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&coroutine_info)
as &dyn Value))])
});
} else { ; }
};
'find_source:
for (variant, source_info) in
coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2552",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2552u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["variant"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&variant) as
&dyn Value))])
});
} else { ; }
};
for &local in variant {
let decl = &coroutine_info.field_tys[local];
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2555",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2555u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["decl"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&decl) as
&dyn Value))])
});
} else { ; }
};
if ty_matches(ty::Binder::dummy(decl.ty)) &&
!decl.ignore_for_traits {
interior_or_upvar_span =
Some(CoroutineInteriorOrUpvar::Interior(decl.source_info.span,
Some((source_info.span, from_awaited_ty))));
break 'find_source;
}
}
}
}
if interior_or_upvar_span.is_none() {
interior_or_upvar_span =
coroutine_data.try_get_upvar_span(self, coroutine_did,
ty_matches);
}
if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
interior_or_upvar_span =
Some(CoroutineInteriorOrUpvar::Interior(span, None));
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2576",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2576u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["interior_or_upvar_span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&interior_or_upvar_span)
as &dyn Value))])
});
} else { ; }
};
if let Some(interior_or_upvar_span) = interior_or_upvar_span {
let is_async = self.tcx.coroutine_is_async(coroutine_did);
self.note_obligation_cause_for_async_await(err,
interior_or_upvar_span, is_async, outer_coroutine,
trait_ref, target_ty, obligation, next_code);
true
} else { false }
}
}
}#[instrument(level = "debug", skip_all, fields(?obligation.predicate, ?obligation.cause.span))]
2366 pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2367 &self,
2368 err: &mut Diag<'_, G>,
2369 obligation: &PredicateObligation<'tcx>,
2370 ) -> bool {
2371 let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() {
2394 ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())),
2395 _ => (None, None),
2396 };
2397 let mut coroutine = None;
2398 let mut outer_coroutine = None;
2399 let mut next_code = Some(obligation.cause.code());
2400
2401 let mut seen_upvar_tys_infer_tuple = false;
2402
2403 while let Some(code) = next_code {
2404 debug!(?code);
2405 match code {
2406 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2407 next_code = Some(parent_code);
2408 }
2409 ObligationCauseCode::ImplDerived(cause) => {
2410 let ty = cause.derived.parent_trait_pred.skip_binder().self_ty();
2411 debug!(
2412 parent_trait_ref = ?cause.derived.parent_trait_pred,
2413 self_ty.kind = ?ty.kind(),
2414 "ImplDerived",
2415 );
2416
2417 match *ty.kind() {
2418 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => {
2419 coroutine = coroutine.or(Some(did));
2420 outer_coroutine = Some(did);
2421 }
2422 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2423 seen_upvar_tys_infer_tuple = true;
2428 }
2429 _ if coroutine.is_none() => {
2430 trait_ref = Some(cause.derived.parent_trait_pred.skip_binder());
2431 target_ty = Some(ty);
2432 }
2433 _ => {}
2434 }
2435
2436 next_code = Some(&cause.derived.parent_code);
2437 }
2438 ObligationCauseCode::WellFormedDerived(derived_obligation)
2439 | ObligationCauseCode::BuiltinDerived(derived_obligation) => {
2440 let ty = derived_obligation.parent_trait_pred.skip_binder().self_ty();
2441 debug!(
2442 parent_trait_ref = ?derived_obligation.parent_trait_pred,
2443 self_ty.kind = ?ty.kind(),
2444 );
2445
2446 match *ty.kind() {
2447 ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => {
2448 coroutine = coroutine.or(Some(did));
2449 outer_coroutine = Some(did);
2450 }
2451 ty::Tuple(_) if !seen_upvar_tys_infer_tuple => {
2452 seen_upvar_tys_infer_tuple = true;
2457 }
2458 _ if coroutine.is_none() => {
2459 trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder());
2460 target_ty = Some(ty);
2461 }
2462 _ => {}
2463 }
2464
2465 next_code = Some(&derived_obligation.parent_code);
2466 }
2467 _ => break,
2468 }
2469 }
2470
2471 debug!(?coroutine, ?trait_ref, ?target_ty);
2473 let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) =
2474 (coroutine, trait_ref, target_ty)
2475 else {
2476 return false;
2477 };
2478
2479 let span = self.tcx.def_span(coroutine_did);
2480
2481 let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did);
2482 debug!(
2483 ?coroutine_did,
2484 ?coroutine_did_root,
2485 typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner),
2486 ?span,
2487 );
2488
2489 let coroutine_body =
2490 coroutine_did.as_local().and_then(|def_id| self.tcx.hir_maybe_body_owned_by(def_id));
2491 let mut visitor = AwaitsVisitor::default();
2492 if let Some(body) = coroutine_body {
2493 visitor.visit_body(&body);
2494 }
2495 debug!(awaits = ?visitor.awaits);
2496
2497 let target_ty_erased = self.tcx.erase_and_anonymize_regions(target_ty);
2500 let ty_matches = |ty| -> bool {
2501 let ty_erased = self.tcx.instantiate_bound_regions_with_erased(ty);
2514 let ty_erased = self.tcx.erase_and_anonymize_regions(ty_erased);
2515 let eq = ty_erased == target_ty_erased;
2516 debug!(?ty_erased, ?target_ty_erased, ?eq);
2517 eq
2518 };
2519
2520 let coroutine_data = match &self.typeck_results {
2525 Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(t),
2526 _ if coroutine_did.is_local() => {
2527 CoroutineData(self.tcx.typeck(coroutine_did.expect_local()))
2528 }
2529 _ => return false,
2530 };
2531
2532 let coroutine_within_in_progress_typeck = match &self.typeck_results {
2533 Some(t) => t.hir_owner.to_def_id() == coroutine_did_root,
2534 _ => false,
2535 };
2536
2537 let mut interior_or_upvar_span = None;
2538
2539 let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, self.tcx, ty_matches);
2540 debug!(?from_awaited_ty);
2541
2542 if coroutine_did.is_local()
2544 && !coroutine_within_in_progress_typeck
2546 && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did)
2547 {
2548 debug!(?coroutine_info);
2549 'find_source: for (variant, source_info) in
2550 coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info)
2551 {
2552 debug!(?variant);
2553 for &local in variant {
2554 let decl = &coroutine_info.field_tys[local];
2555 debug!(?decl);
2556 if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits {
2557 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(
2558 decl.source_info.span,
2559 Some((source_info.span, from_awaited_ty)),
2560 ));
2561 break 'find_source;
2562 }
2563 }
2564 }
2565 }
2566
2567 if interior_or_upvar_span.is_none() {
2568 interior_or_upvar_span =
2569 coroutine_data.try_get_upvar_span(self, coroutine_did, ty_matches);
2570 }
2571
2572 if interior_or_upvar_span.is_none() && !coroutine_did.is_local() {
2573 interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None));
2574 }
2575
2576 debug!(?interior_or_upvar_span);
2577 if let Some(interior_or_upvar_span) = interior_or_upvar_span {
2578 let is_async = self.tcx.coroutine_is_async(coroutine_did);
2579 self.note_obligation_cause_for_async_await(
2580 err,
2581 interior_or_upvar_span,
2582 is_async,
2583 outer_coroutine,
2584 trait_ref,
2585 target_ty,
2586 obligation,
2587 next_code,
2588 );
2589 true
2590 } else {
2591 false
2592 }
2593 }
2594
2595 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("note_obligation_cause_for_async_await",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2597u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let source_map = self.tcx.sess.source_map();
let (await_or_yield, an_await_or_yield) =
if is_async {
("await", "an await")
} else { ("yield", "a yield") };
let future_or_coroutine =
if is_async { "future" } else { "coroutine" };
let trait_explanation =
if let Some(name @ (sym::Send | sym::Sync)) =
self.tcx.get_diagnostic_name(trait_pred.def_id()) {
let (trait_name, trait_verb) =
if name == sym::Send {
("`Send`", "sent")
} else { ("`Sync`", "shared") };
err.code = None;
err.primary_message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} cannot be {1} between threads safely",
future_or_coroutine, trait_verb))
}));
let original_span = err.span.primary_span().unwrap();
let mut span = MultiSpan::from_span(original_span);
let message =
outer_coroutine.and_then(|coroutine_did|
{
Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
CoroutineKind::Coroutine(_) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("coroutine is not {0}",
trait_name))
}),
CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Fn) =>
self.tcx.parent(coroutine_did).as_local().map(|parent_did|
self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
self.tcx.hir_opt_name(parent_hir_id)).map(|name|
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future returned by `{0}` is not {1}",
name, trait_name))
})
})?,
CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Block) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future created by async block is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::Async,
CoroutineSource::Closure) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future created by async closure is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
CoroutineSource::Fn) =>
self.tcx.parent(coroutine_did).as_local().map(|parent_did|
self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
self.tcx.hir_opt_name(parent_hir_id)).map(|name|
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("async iterator returned by `{0}` is not {1}",
name, trait_name))
})
})?,
CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
CoroutineSource::Block) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("async iterator created by async gen block is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen,
CoroutineSource::Closure) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("async iterator created by async gen closure is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::Gen,
CoroutineSource::Fn) => {
self.tcx.parent(coroutine_did).as_local().map(|parent_did|
self.tcx.local_def_id_to_hir_id(parent_did)).and_then(|parent_hir_id|
self.tcx.hir_opt_name(parent_hir_id)).map(|name|
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("iterator returned by `{0}` is not {1}",
name, trait_name))
})
})?
}
CoroutineKind::Desugared(CoroutineDesugaring::Gen,
CoroutineSource::Block) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("iterator created by gen block is not {0}",
trait_name))
})
}
CoroutineKind::Desugared(CoroutineDesugaring::Gen,
CoroutineSource::Closure) => {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("iterator created by gen closure is not {0}",
trait_name))
})
}
})
}).unwrap_or_else(||
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not {1}",
future_or_coroutine, trait_name))
}));
span.push_span_label(original_span, message);
err.span(span);
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("is not {0}", trait_name))
})
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("does not implement `{0}`",
trait_pred.print_modifiers_and_trait_path()))
})
};
let mut explain_yield =
|interior_span: Span, yield_span: Span|
{
let mut span = MultiSpan::from_span(yield_span);
let snippet =
match source_map.span_to_snippet(interior_span) {
Ok(snippet) if !snippet.contains('\n') =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", snippet))
}),
_ => "the value".to_string(),
};
span.push_span_label(yield_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} occurs here, with {1} maybe used later",
await_or_yield, snippet))
}));
span.push_span_label(interior_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}` which {1}",
target_ty, trait_explanation))
}));
err.span_note(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1} as this value is used across {2}",
future_or_coroutine, trait_explanation, an_await_or_yield))
}));
};
match interior_or_upvar_span {
CoroutineInteriorOrUpvar::Interior(interior_span,
interior_extra_info) => {
if let Some((yield_span, from_awaited_ty)) =
interior_extra_info {
if let Some(await_span) = from_awaited_ty {
let mut span = MultiSpan::from_span(await_span);
span.push_span_label(await_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("await occurs here on type `{0}`, which {1}",
target_ty, trait_explanation))
}));
err.span_note(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("future {0} as it awaits another future which {0}",
trait_explanation))
}));
} else { explain_yield(interior_span, yield_span); }
}
}
CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
let non_send =
match target_ty.kind() {
ty::Ref(_, ref_ty, mutability) =>
match self.evaluate_obligation(obligation) {
Ok(eval) if !eval.may_apply() =>
Some((ref_ty, mutability.is_mut())),
_ => None,
},
_ => None,
};
let (span_label, span_note) =
match non_send {
Some((ref_ty, is_mut)) => {
let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
let ref_kind = if is_mut { "&mut" } else { "&" };
(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}` which {1}, because `{2}` is not `{3}`",
target_ty, trait_explanation, ref_ty, ref_ty_trait))
}),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("captured value {0} because `{1}` references cannot be sent unless their referent is `{2}`",
trait_explanation, ref_kind, ref_ty_trait))
}))
}
None =>
(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("has type `{0}` which {1}",
target_ty, trait_explanation))
}),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("captured value {0}",
trait_explanation))
})),
};
let mut span = MultiSpan::from_span(upvar_span);
span.push_span_label(upvar_span, span_label);
err.span_note(span, span_note);
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:2820",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(2820u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["next_code"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&next_code)
as &dyn Value))])
});
} else { ; }
};
self.note_obligation_cause_code(obligation.cause.body_id, err,
obligation.predicate, obligation.param_env,
next_code.unwrap(), &mut Vec::new(), &mut Default::default());
}
}
}#[instrument(level = "debug", skip_all)]
2598 fn note_obligation_cause_for_async_await<G: EmissionGuarantee>(
2599 &self,
2600 err: &mut Diag<'_, G>,
2601 interior_or_upvar_span: CoroutineInteriorOrUpvar,
2602 is_async: bool,
2603 outer_coroutine: Option<DefId>,
2604 trait_pred: ty::TraitPredicate<'tcx>,
2605 target_ty: Ty<'tcx>,
2606 obligation: &PredicateObligation<'tcx>,
2607 next_code: Option<&ObligationCauseCode<'tcx>>,
2608 ) {
2609 let source_map = self.tcx.sess.source_map();
2610
2611 let (await_or_yield, an_await_or_yield) =
2612 if is_async { ("await", "an await") } else { ("yield", "a yield") };
2613 let future_or_coroutine = if is_async { "future" } else { "coroutine" };
2614
2615 let trait_explanation = if let Some(name @ (sym::Send | sym::Sync)) =
2618 self.tcx.get_diagnostic_name(trait_pred.def_id())
2619 {
2620 let (trait_name, trait_verb) =
2621 if name == sym::Send { ("`Send`", "sent") } else { ("`Sync`", "shared") };
2622
2623 err.code = None;
2624 err.primary_message(format!(
2625 "{future_or_coroutine} cannot be {trait_verb} between threads safely"
2626 ));
2627
2628 let original_span = err.span.primary_span().unwrap();
2629 let mut span = MultiSpan::from_span(original_span);
2630
2631 let message = outer_coroutine
2632 .and_then(|coroutine_did| {
2633 Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() {
2634 CoroutineKind::Coroutine(_) => format!("coroutine is not {trait_name}"),
2635 CoroutineKind::Desugared(
2636 CoroutineDesugaring::Async,
2637 CoroutineSource::Fn,
2638 ) => self
2639 .tcx
2640 .parent(coroutine_did)
2641 .as_local()
2642 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2643 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2644 .map(|name| {
2645 format!("future returned by `{name}` is not {trait_name}")
2646 })?,
2647 CoroutineKind::Desugared(
2648 CoroutineDesugaring::Async,
2649 CoroutineSource::Block,
2650 ) => {
2651 format!("future created by async block is not {trait_name}")
2652 }
2653 CoroutineKind::Desugared(
2654 CoroutineDesugaring::Async,
2655 CoroutineSource::Closure,
2656 ) => {
2657 format!("future created by async closure is not {trait_name}")
2658 }
2659 CoroutineKind::Desugared(
2660 CoroutineDesugaring::AsyncGen,
2661 CoroutineSource::Fn,
2662 ) => self
2663 .tcx
2664 .parent(coroutine_did)
2665 .as_local()
2666 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2667 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2668 .map(|name| {
2669 format!("async iterator returned by `{name}` is not {trait_name}")
2670 })?,
2671 CoroutineKind::Desugared(
2672 CoroutineDesugaring::AsyncGen,
2673 CoroutineSource::Block,
2674 ) => {
2675 format!("async iterator created by async gen block is not {trait_name}")
2676 }
2677 CoroutineKind::Desugared(
2678 CoroutineDesugaring::AsyncGen,
2679 CoroutineSource::Closure,
2680 ) => {
2681 format!(
2682 "async iterator created by async gen closure is not {trait_name}"
2683 )
2684 }
2685 CoroutineKind::Desugared(CoroutineDesugaring::Gen, CoroutineSource::Fn) => {
2686 self.tcx
2687 .parent(coroutine_did)
2688 .as_local()
2689 .map(|parent_did| self.tcx.local_def_id_to_hir_id(parent_did))
2690 .and_then(|parent_hir_id| self.tcx.hir_opt_name(parent_hir_id))
2691 .map(|name| {
2692 format!("iterator returned by `{name}` is not {trait_name}")
2693 })?
2694 }
2695 CoroutineKind::Desugared(
2696 CoroutineDesugaring::Gen,
2697 CoroutineSource::Block,
2698 ) => {
2699 format!("iterator created by gen block is not {trait_name}")
2700 }
2701 CoroutineKind::Desugared(
2702 CoroutineDesugaring::Gen,
2703 CoroutineSource::Closure,
2704 ) => {
2705 format!("iterator created by gen closure is not {trait_name}")
2706 }
2707 })
2708 })
2709 .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}"));
2710
2711 span.push_span_label(original_span, message);
2712 err.span(span);
2713
2714 format!("is not {trait_name}")
2715 } else {
2716 format!("does not implement `{}`", trait_pred.print_modifiers_and_trait_path())
2717 };
2718
2719 let mut explain_yield = |interior_span: Span, yield_span: Span| {
2720 let mut span = MultiSpan::from_span(yield_span);
2721 let snippet = match source_map.span_to_snippet(interior_span) {
2722 Ok(snippet) if !snippet.contains('\n') => format!("`{snippet}`"),
2725 _ => "the value".to_string(),
2726 };
2727 span.push_span_label(
2744 yield_span,
2745 format!("{await_or_yield} occurs here, with {snippet} maybe used later"),
2746 );
2747 span.push_span_label(
2748 interior_span,
2749 format!("has type `{target_ty}` which {trait_explanation}"),
2750 );
2751 err.span_note(
2752 span,
2753 format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"),
2754 );
2755 };
2756 match interior_or_upvar_span {
2757 CoroutineInteriorOrUpvar::Interior(interior_span, interior_extra_info) => {
2758 if let Some((yield_span, from_awaited_ty)) = interior_extra_info {
2759 if let Some(await_span) = from_awaited_ty {
2760 let mut span = MultiSpan::from_span(await_span);
2762 span.push_span_label(
2763 await_span,
2764 format!(
2765 "await occurs here on type `{target_ty}`, which {trait_explanation}"
2766 ),
2767 );
2768 err.span_note(
2769 span,
2770 format!(
2771 "future {trait_explanation} as it awaits another future which {trait_explanation}"
2772 ),
2773 );
2774 } else {
2775 explain_yield(interior_span, yield_span);
2777 }
2778 }
2779 }
2780 CoroutineInteriorOrUpvar::Upvar(upvar_span) => {
2781 let non_send = match target_ty.kind() {
2783 ty::Ref(_, ref_ty, mutability) => match self.evaluate_obligation(obligation) {
2784 Ok(eval) if !eval.may_apply() => Some((ref_ty, mutability.is_mut())),
2785 _ => None,
2786 },
2787 _ => None,
2788 };
2789
2790 let (span_label, span_note) = match non_send {
2791 Some((ref_ty, is_mut)) => {
2795 let ref_ty_trait = if is_mut { "Send" } else { "Sync" };
2796 let ref_kind = if is_mut { "&mut" } else { "&" };
2797 (
2798 format!(
2799 "has type `{target_ty}` which {trait_explanation}, because `{ref_ty}` is not `{ref_ty_trait}`"
2800 ),
2801 format!(
2802 "captured value {trait_explanation} because `{ref_kind}` references cannot be sent unless their referent is `{ref_ty_trait}`"
2803 ),
2804 )
2805 }
2806 None => (
2807 format!("has type `{target_ty}` which {trait_explanation}"),
2808 format!("captured value {trait_explanation}"),
2809 ),
2810 };
2811
2812 let mut span = MultiSpan::from_span(upvar_span);
2813 span.push_span_label(upvar_span, span_label);
2814 err.span_note(span, span_note);
2815 }
2816 }
2817
2818 debug!(?next_code);
2821 self.note_obligation_cause_code(
2822 obligation.cause.body_id,
2823 err,
2824 obligation.predicate,
2825 obligation.param_env,
2826 next_code.unwrap(),
2827 &mut Vec::new(),
2828 &mut Default::default(),
2829 );
2830 }
2831
2832 pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>(
2833 &self,
2834 body_id: LocalDefId,
2835 err: &mut Diag<'_, G>,
2836 predicate: T,
2837 param_env: ty::ParamEnv<'tcx>,
2838 cause_code: &ObligationCauseCode<'tcx>,
2839 obligated_types: &mut Vec<Ty<'tcx>>,
2840 seen_requirements: &mut FxHashSet<DefId>,
2841 ) where
2842 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
2843 {
2844 let tcx = self.tcx;
2845 let predicate = predicate.upcast(tcx);
2846 let suggest_remove_deref = |err: &mut Diag<'_, G>, expr: &hir::Expr<'_>| {
2847 if let Some(pred) = predicate.as_trait_clause()
2848 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2849 && let hir::ExprKind::Unary(hir::UnOp::Deref, inner) = expr.kind
2850 {
2851 err.span_suggestion_verbose(
2852 expr.span.until(inner.span),
2853 "references are always `Sized`, even if they point to unsized data; consider \
2854 not dereferencing the expression",
2855 String::new(),
2856 Applicability::MaybeIncorrect,
2857 );
2858 }
2859 };
2860 match *cause_code {
2861 ObligationCauseCode::ExprAssignable
2862 | ObligationCauseCode::MatchExpressionArm { .. }
2863 | ObligationCauseCode::Pattern { .. }
2864 | ObligationCauseCode::IfExpression { .. }
2865 | ObligationCauseCode::IfExpressionWithNoElse
2866 | ObligationCauseCode::MainFunctionType
2867 | ObligationCauseCode::LangFunctionType(_)
2868 | ObligationCauseCode::IntrinsicType
2869 | ObligationCauseCode::MethodReceiver
2870 | ObligationCauseCode::ReturnNoExpression
2871 | ObligationCauseCode::Misc
2872 | ObligationCauseCode::WellFormed(..)
2873 | ObligationCauseCode::MatchImpl(..)
2874 | ObligationCauseCode::ReturnValue(_)
2875 | ObligationCauseCode::BlockTailExpression(..)
2876 | ObligationCauseCode::AwaitableExpr(_)
2877 | ObligationCauseCode::ForLoopIterator
2878 | ObligationCauseCode::QuestionMark
2879 | ObligationCauseCode::CheckAssociatedTypeBounds { .. }
2880 | ObligationCauseCode::LetElse
2881 | ObligationCauseCode::UnOp { .. }
2882 | ObligationCauseCode::BinOp { .. }
2883 | ObligationCauseCode::AscribeUserTypeProvePredicate(..)
2884 | ObligationCauseCode::AlwaysApplicableImpl
2885 | ObligationCauseCode::ConstParam(_)
2886 | ObligationCauseCode::ReferenceOutlivesReferent(..)
2887 | ObligationCauseCode::ObjectTypeBound(..) => {}
2888 ObligationCauseCode::RustCall => {
2889 if let Some(pred) = predicate.as_trait_clause()
2890 && tcx.is_lang_item(pred.def_id(), LangItem::Sized)
2891 {
2892 err.note("argument required to be sized due to `extern \"rust-call\"` ABI");
2893 }
2894 }
2895 ObligationCauseCode::SliceOrArrayElem => {
2896 err.note("slice and array elements must have `Sized` type");
2897 }
2898 ObligationCauseCode::ArrayLen(array_ty) => {
2899 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the length of array `{0}` must be type `usize`",
array_ty))
})format!("the length of array `{array_ty}` must be type `usize`"));
2900 }
2901 ObligationCauseCode::TupleElem => {
2902 err.note("only the last element of a tuple may have a dynamically sized type");
2903 }
2904 ObligationCauseCode::DynCompatible(span) => {
2905 err.multipart_suggestion(
2906 "you might have meant to use `Self` to refer to the implementing type",
2907 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, "Self".into())]))vec![(span, "Self".into())],
2908 Applicability::MachineApplicable,
2909 );
2910 }
2911 ObligationCauseCode::WhereClause(item_def_id, span)
2912 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)
2913 | ObligationCauseCode::HostEffectInExpr(item_def_id, span, ..)
2914 if !span.is_dummy() =>
2915 {
2916 if let ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, pos) = &cause_code {
2917 if let Node::Expr(expr) = tcx.parent_hir_node(*hir_id)
2918 && let hir::ExprKind::Call(_, args) = expr.kind
2919 && let Some(expr) = args.get(*pos)
2920 {
2921 suggest_remove_deref(err, &expr);
2922 } else if let Node::Expr(expr) = self.tcx.hir_node(*hir_id)
2923 && let hir::ExprKind::MethodCall(_, _, args, _) = expr.kind
2924 && let Some(expr) = args.get(*pos)
2925 {
2926 suggest_remove_deref(err, &expr);
2927 }
2928 }
2929 let item_name = tcx.def_path_str(item_def_id);
2930 let short_item_name = { let _guard = ForceTrimmedGuard::new(); tcx.def_path_str(item_def_id) }with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
2931 let mut multispan = MultiSpan::from(span);
2932 let sm = tcx.sess.source_map();
2933 if let Some(ident) = tcx.opt_item_ident(item_def_id) {
2934 let same_line =
2935 match (sm.lookup_line(ident.span.hi()), sm.lookup_line(span.lo())) {
2936 (Ok(l), Ok(r)) => l.line == r.line,
2937 _ => true,
2938 };
2939 if ident.span.is_visible(sm) && !ident.span.overlaps(span) && !same_line {
2940 multispan.push_span_label(
2941 ident.span,
2942 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by a bound in this {0}",
tcx.def_kind(item_def_id).descr(item_def_id)))
})format!(
2943 "required by a bound in this {}",
2944 tcx.def_kind(item_def_id).descr(item_def_id)
2945 ),
2946 );
2947 }
2948 }
2949 let mut a = "a";
2950 let mut this = "this bound";
2951 let mut note = None;
2952 let mut help = None;
2953 if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
2954 match clause {
2955 ty::ClauseKind::Trait(trait_pred) => {
2956 let def_id = trait_pred.def_id();
2957 let visible_item = if let Some(local) = def_id.as_local() {
2958 let ty = trait_pred.self_ty();
2959 if let ty::Adt(adt, _) = ty.kind() {
2963 let visibilities = &tcx.resolutions(()).effective_visibilities;
2964 visibilities.effective_vis(local).is_none_or(|v| {
2965 v.at_level(Level::Reexported)
2966 .is_accessible_from(adt.did(), tcx)
2967 })
2968 } else {
2969 true
2971 }
2972 } else {
2973 tcx.visible_parent_map(()).get(&def_id).is_some()
2975 };
2976 if tcx.is_lang_item(def_id, LangItem::Sized) {
2977 if tcx
2979 .generics_of(item_def_id)
2980 .own_params
2981 .iter()
2982 .any(|param| tcx.def_span(param.def_id) == span)
2983 {
2984 a = "an implicit `Sized`";
2985 this =
2986 "the implicit `Sized` requirement on this type parameter";
2987 }
2988 if let Some(hir::Node::TraitItem(hir::TraitItem {
2989 generics,
2990 kind: hir::TraitItemKind::Type(bounds, None),
2991 ..
2992 })) = tcx.hir_get_if_local(item_def_id)
2993 && !bounds.iter()
2995 .filter_map(|bound| bound.trait_ref())
2996 .any(|tr| tr.trait_def_id().is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Sized)))
2997 {
2998 let (span, separator) = if let [.., last] = bounds {
2999 (last.span().shrink_to_hi(), " +")
3000 } else {
3001 (generics.span.shrink_to_hi(), ":")
3002 };
3003 err.span_suggestion_verbose(
3004 span,
3005 "consider relaxing the implicit `Sized` restriction",
3006 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ?Sized", separator))
})format!("{separator} ?Sized"),
3007 Applicability::MachineApplicable,
3008 );
3009 }
3010 }
3011 if let DefKind::Trait = tcx.def_kind(item_def_id)
3012 && !visible_item
3013 {
3014 note = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` is a \"sealed trait\", because to implement it you also need to implement `{0}`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it",
{
let _guard = NoTrimmedGuard::new();
tcx.def_path_str(def_id)
}, short_item_name))
})format!(
3015 "`{short_item_name}` is a \"sealed trait\", because to implement it \
3016 you also need to implement `{}`, which is not accessible; this is \
3017 usually done to force you to use one of the provided types that \
3018 already implement it",
3019 with_no_trimmed_paths!(tcx.def_path_str(def_id)),
3020 ));
3021 let impls_of = tcx.trait_impls_of(def_id);
3022 let impls = impls_of
3023 .non_blanket_impls()
3024 .values()
3025 .flatten()
3026 .chain(impls_of.blanket_impls().iter())
3027 .collect::<Vec<_>>();
3028 if !impls.is_empty() {
3029 let len = impls.len();
3030 let mut types = impls
3031 .iter()
3032 .map(|t| {
3033 {
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}",
tcx.type_of(*t).instantiate_identity()))
})
}with_no_trimmed_paths!(format!(
3034 " {}",
3035 tcx.type_of(*t).instantiate_identity(),
3036 ))
3037 })
3038 .collect::<Vec<_>>();
3039 let post = if types.len() > 9 {
3040 types.truncate(8);
3041 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others", len - 8))
})format!("\nand {} others", len - 8)
3042 } else {
3043 String::new()
3044 };
3045 help = Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following type{0} implement{1} the trait:\n{2}{3}",
if len == 1 { "" } else { "s" },
if len == 1 { "s" } else { "" }, types.join("\n"), post))
})format!(
3046 "the following type{} implement{} the trait:\n{}{post}",
3047 pluralize!(len),
3048 if len == 1 { "s" } else { "" },
3049 types.join("\n"),
3050 ));
3051 }
3052 }
3053 }
3054 ty::ClauseKind::ConstArgHasType(..) => {
3055 let descr =
3056 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by a const generic parameter in `{0}`",
item_name))
})format!("required by a const generic parameter in `{item_name}`");
3057 if span.is_visible(sm) {
3058 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by this const generic parameter in `{0}`",
short_item_name))
})format!(
3059 "required by this const generic parameter in `{short_item_name}`"
3060 );
3061 multispan.push_span_label(span, msg);
3062 err.span_note(multispan, descr);
3063 } else {
3064 err.span_note(tcx.def_span(item_def_id), descr);
3065 }
3066 return;
3067 }
3068 _ => (),
3069 }
3070 }
3071
3072 let is_in_fmt_lit = if let Some(s) = err.span.primary_span() {
3075 #[allow(non_exhaustive_omitted_patterns)] match s.desugaring_kind() {
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(s.desugaring_kind(), Some(DesugaringKind::FormatLiteral { .. }))
3076 } else {
3077 false
3078 };
3079 if !is_in_fmt_lit {
3080 let descr = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by {0} bound in `{1}`", a,
item_name))
})format!("required by {a} bound in `{item_name}`");
3081 if span.is_visible(sm) {
3082 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by {0} in `{1}`", this,
short_item_name))
})format!("required by {this} in `{short_item_name}`");
3083 multispan.push_span_label(span, msg);
3084 err.span_note(multispan, descr);
3085 } else {
3086 err.span_note(tcx.def_span(item_def_id), descr);
3087 }
3088 }
3089 if let Some(note) = note {
3090 err.note(note);
3091 }
3092 if let Some(help) = help {
3093 err.help(help);
3094 }
3095 }
3096 ObligationCauseCode::WhereClause(..)
3097 | ObligationCauseCode::WhereClauseInExpr(..)
3098 | ObligationCauseCode::HostEffectInExpr(..) => {
3099 }
3102 ObligationCauseCode::OpaqueTypeBound(span, definition_def_id) => {
3103 err.span_note(span, "required by a bound in an opaque type");
3104 if let Some(definition_def_id) = definition_def_id
3105 && self.tcx.typeck(definition_def_id).coroutine_stalled_predicates.is_empty()
3109 {
3110 err.span_note(
3113 tcx.def_span(definition_def_id),
3114 "this definition site has more where clauses than the opaque type",
3115 );
3116 }
3117 }
3118 ObligationCauseCode::Coercion { source, target } => {
3119 let source =
3120 tcx.short_string(self.resolve_vars_if_possible(source), err.long_ty_path());
3121 let target =
3122 tcx.short_string(self.resolve_vars_if_possible(target), err.long_ty_path());
3123 err.note({
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for the cast from `{0}` to `{1}`",
source, target))
})
}with_forced_trimmed_paths!(format!(
3124 "required for the cast from `{source}` to `{target}`",
3125 )));
3126 }
3127 ObligationCauseCode::RepeatElementCopy { is_constable, elt_span } => {
3128 err.note(
3129 "the `Copy` trait is required because this value will be copied for each element of the array",
3130 );
3131 let sm = tcx.sess.source_map();
3132 if #[allow(non_exhaustive_omitted_patterns)] match is_constable {
IsConstable::Fn | IsConstable::Ctor => true,
_ => false,
}matches!(is_constable, IsConstable::Fn | IsConstable::Ctor)
3133 && let Ok(_) = sm.span_to_snippet(elt_span)
3134 {
3135 err.multipart_suggestion(
3136 "create an inline `const` block",
3137 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(elt_span.shrink_to_lo(), "const { ".to_string()),
(elt_span.shrink_to_hi(), " }".to_string())]))vec![
3138 (elt_span.shrink_to_lo(), "const { ".to_string()),
3139 (elt_span.shrink_to_hi(), " }".to_string()),
3140 ],
3141 Applicability::MachineApplicable,
3142 );
3143 } else {
3144 err.help("consider using `core::array::from_fn` to initialize the array");
3146 err.help("see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html for more information");
3147 }
3148 }
3149 ObligationCauseCode::VariableType(hir_id) => {
3150 if let Some(typeck_results) = &self.typeck_results
3151 && let Some(ty) = typeck_results.node_type_opt(hir_id)
3152 && let ty::Error(_) = ty.kind()
3153 {
3154 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` isn\'t satisfied, but the type of this pattern is `{{type error}}`",
predicate))
})format!(
3155 "`{predicate}` isn't satisfied, but the type of this pattern is \
3156 `{{type error}}`",
3157 ));
3158 err.downgrade_to_delayed_bug();
3159 }
3160 let mut local = true;
3161 match tcx.parent_hir_node(hir_id) {
3162 Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }) => {
3163 err.span_suggestion_verbose(
3164 ty.span.shrink_to_lo(),
3165 "consider borrowing here",
3166 "&",
3167 Applicability::MachineApplicable,
3168 );
3169 }
3170 Node::LetStmt(hir::LetStmt {
3171 init: Some(hir::Expr { kind: hir::ExprKind::Index(..), span, .. }),
3172 ..
3173 }) => {
3174 err.span_suggestion_verbose(
3178 span.shrink_to_lo(),
3179 "consider borrowing here",
3180 "&",
3181 Applicability::MachineApplicable,
3182 );
3183 }
3184 Node::LetStmt(hir::LetStmt { init: Some(expr), .. }) => {
3185 suggest_remove_deref(err, &expr);
3188 }
3189 Node::Param(param) => {
3190 err.span_suggestion_verbose(
3191 param.ty_span.shrink_to_lo(),
3192 "function arguments must have a statically known size, borrowed types \
3193 always have a known size",
3194 "&",
3195 Applicability::MachineApplicable,
3196 );
3197 local = false;
3198 }
3199 _ => {}
3200 }
3201 if local {
3202 err.note("all local variables must have a statically known size");
3203 }
3204 }
3205 ObligationCauseCode::SizedArgumentType(hir_id) => {
3206 let mut ty = None;
3207 let borrowed_msg = "function arguments must have a statically known size, borrowed \
3208 types always have a known size";
3209 if let Some(hir_id) = hir_id
3210 && let hir::Node::Param(param) = self.tcx.hir_node(hir_id)
3211 && let Some(decl) = self.tcx.parent_hir_node(hir_id).fn_decl()
3212 && let Some(t) = decl.inputs.iter().find(|t| param.ty_span.contains(t.span))
3213 {
3214 ty = Some(t);
3222 } else if let Some(hir_id) = hir_id
3223 && let hir::Node::Ty(t) = self.tcx.hir_node(hir_id)
3224 {
3225 ty = Some(t);
3226 }
3227 if let Some(ty) = ty {
3228 match ty.kind {
3229 hir::TyKind::TraitObject(traits, _) => {
3230 let (span, kw) = match traits {
3231 [first, ..] if first.span.lo() == ty.span.lo() => {
3232 (ty.span.shrink_to_lo(), "dyn ")
3234 }
3235 [first, ..] => (ty.span.until(first.span), ""),
3236 [] => ::rustc_middle::util::bug::span_bug_fmt(ty.span,
format_args!("trait object with no traits: {0:?}", ty))span_bug!(ty.span, "trait object with no traits: {ty:?}"),
3237 };
3238 let needs_parens = traits.len() != 1;
3239 if let Some(hir_id) = hir_id
3241 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.parent_hir_node(hir_id)
{
hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. }) => true,
_ => false,
}matches!(
3242 self.tcx.parent_hir_node(hir_id),
3243 hir::Node::Item(hir::Item {
3244 kind: hir::ItemKind::Fn { .. },
3245 ..
3246 })
3247 )
3248 {
3249 err.span_suggestion_verbose(
3250 span,
3251 "you can use `impl Trait` as the argument type",
3252 "impl ",
3253 Applicability::MaybeIncorrect,
3254 );
3255 }
3256 let sugg = if !needs_parens {
3257 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", kw))
}))]))vec![(span.shrink_to_lo(), format!("&{kw}"))]
3258 } else {
3259 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&({0}", kw))
})), (ty.span.shrink_to_hi(), ")".to_string())]))vec![
3260 (span.shrink_to_lo(), format!("&({kw}")),
3261 (ty.span.shrink_to_hi(), ")".to_string()),
3262 ]
3263 };
3264 err.multipart_suggestion(
3265 borrowed_msg,
3266 sugg,
3267 Applicability::MachineApplicable,
3268 );
3269 }
3270 hir::TyKind::Slice(_ty) => {
3271 err.span_suggestion_verbose(
3272 ty.span.shrink_to_lo(),
3273 "function arguments must have a statically known size, borrowed \
3274 slices always have a known size",
3275 "&",
3276 Applicability::MachineApplicable,
3277 );
3278 }
3279 hir::TyKind::Path(_) => {
3280 err.span_suggestion_verbose(
3281 ty.span.shrink_to_lo(),
3282 borrowed_msg,
3283 "&",
3284 Applicability::MachineApplicable,
3285 );
3286 }
3287 _ => {}
3288 }
3289 } else {
3290 err.note("all function arguments must have a statically known size");
3291 }
3292 if tcx.sess.opts.unstable_features.is_nightly_build()
3293 && !tcx.features().unsized_fn_params()
3294 {
3295 err.help("unsized fn params are gated as an unstable feature");
3296 }
3297 }
3298 ObligationCauseCode::SizedReturnType | ObligationCauseCode::SizedCallReturnType => {
3299 err.note("the return type of a function must have a statically known size");
3300 }
3301 ObligationCauseCode::SizedYieldType => {
3302 err.note("the yield type of a coroutine must have a statically known size");
3303 }
3304 ObligationCauseCode::AssignmentLhsSized => {
3305 err.note("the left-hand-side of an assignment must have a statically known size");
3306 }
3307 ObligationCauseCode::TupleInitializerSized => {
3308 err.note("tuples must have a statically known size to be initialized");
3309 }
3310 ObligationCauseCode::StructInitializerSized => {
3311 err.note("structs must have a statically known size to be initialized");
3312 }
3313 ObligationCauseCode::FieldSized { adt_kind: ref item, last, span } => {
3314 match *item {
3315 AdtKind::Struct => {
3316 if last {
3317 err.note(
3318 "the last field of a packed struct may only have a \
3319 dynamically sized type if it does not need drop to be run",
3320 );
3321 } else {
3322 err.note(
3323 "only the last field of a struct may have a dynamically sized type",
3324 );
3325 }
3326 }
3327 AdtKind::Union => {
3328 err.note("no field of a union may have a dynamically sized type");
3329 }
3330 AdtKind::Enum => {
3331 err.note("no field of an enum variant may have a dynamically sized type");
3332 }
3333 }
3334 err.help("change the field's type to have a statically known size");
3335 err.span_suggestion_verbose(
3336 span.shrink_to_lo(),
3337 "borrowed types always have a statically known size",
3338 "&",
3339 Applicability::MachineApplicable,
3340 );
3341 err.multipart_suggestion(
3342 "the `Box` type always has a statically known size and allocates its contents \
3343 in the heap",
3344 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "Box<".to_string()),
(span.shrink_to_hi(), ">".to_string())]))vec![
3345 (span.shrink_to_lo(), "Box<".to_string()),
3346 (span.shrink_to_hi(), ">".to_string()),
3347 ],
3348 Applicability::MachineApplicable,
3349 );
3350 }
3351 ObligationCauseCode::SizedConstOrStatic => {
3352 err.note("statics and constants must have a statically known size");
3353 }
3354 ObligationCauseCode::InlineAsmSized => {
3355 err.note("all inline asm arguments must have a statically known size");
3356 }
3357 ObligationCauseCode::SizedClosureCapture(closure_def_id) => {
3358 err.note(
3359 "all values captured by value by a closure must have a statically known size",
3360 );
3361 let hir::ExprKind::Closure(closure) =
3362 tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind
3363 else {
3364 ::rustc_middle::util::bug::bug_fmt(format_args!("expected closure in SizedClosureCapture obligation"));bug!("expected closure in SizedClosureCapture obligation");
3365 };
3366 if let hir::CaptureBy::Value { .. } = closure.capture_clause
3367 && let Some(span) = closure.fn_arg_span
3368 {
3369 err.span_label(span, "this closure captures all values by move");
3370 }
3371 }
3372 ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => {
3373 let what = match tcx.coroutine_kind(coroutine_def_id) {
3374 None
3375 | Some(hir::CoroutineKind::Coroutine(_))
3376 | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => {
3377 "yield"
3378 }
3379 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3380 "await"
3381 }
3382 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => {
3383 "yield`/`await"
3384 }
3385 };
3386 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("all values live across `{0}` must have a statically known size",
what))
})format!(
3387 "all values live across `{what}` must have a statically known size"
3388 ));
3389 }
3390 ObligationCauseCode::SharedStatic => {
3391 err.note("shared static variables must have a type that implements `Sync`");
3392 }
3393 ObligationCauseCode::BuiltinDerived(ref data) => {
3394 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3395 let ty = parent_trait_ref.skip_binder().self_ty();
3396 if parent_trait_ref.references_error() {
3397 err.downgrade_to_delayed_bug();
3400 return;
3401 }
3402
3403 let is_upvar_tys_infer_tuple = if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(ty.kind(), ty::Tuple(..)) {
3406 false
3407 } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
3408 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3409 let nested_ty = parent_trait_ref.skip_binder().self_ty();
3410 #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Coroutine(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Coroutine(..))
3411 || #[allow(non_exhaustive_omitted_patterns)] match nested_ty.kind() {
ty::Closure(..) => true,
_ => false,
}matches!(nested_ty.kind(), ty::Closure(..))
3412 } else {
3413 false
3414 };
3415
3416 let is_builtin_async_fn_trait =
3417 tcx.async_fn_trait_kind_from_def_id(data.parent_trait_pred.def_id()).is_some();
3418
3419 if !is_upvar_tys_infer_tuple && !is_builtin_async_fn_trait {
3420 let mut msg = || {
3421 let ty_str = tcx.short_string(ty, err.long_ty_path());
3422 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required because it appears within the type `{0}`",
ty_str))
})format!("required because it appears within the type `{ty_str}`")
3423 };
3424 match ty.kind() {
3425 ty::Adt(def, _) => {
3426 let msg = msg();
3427 match tcx.opt_item_ident(def.did()) {
3428 Some(ident) => {
3429 err.span_note(ident.span, msg);
3430 }
3431 None => {
3432 err.note(msg);
3433 }
3434 }
3435 }
3436 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
3437 let is_future = tcx.ty_is_opaque_future(ty);
3440 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3440",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3440u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message",
"obligated_types", "is_future"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("note_obligation_cause_code: check for async fn")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&obligated_types)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&is_future)
as &dyn Value))])
});
} else { ; }
};debug!(
3441 ?obligated_types,
3442 ?is_future,
3443 "note_obligation_cause_code: check for async fn"
3444 );
3445 if is_future
3446 && obligated_types.last().is_some_and(|ty| match ty.kind() {
3447 ty::Coroutine(last_def_id, ..) => {
3448 tcx.coroutine_is_async(*last_def_id)
3449 }
3450 _ => false,
3451 })
3452 {
3453 } else {
3455 let msg = msg();
3456 err.span_note(tcx.def_span(def_id), msg);
3457 }
3458 }
3459 ty::Coroutine(def_id, _) => {
3460 let sp = tcx.def_span(def_id);
3461
3462 let kind = tcx.coroutine_kind(def_id).unwrap();
3464 err.span_note(
3465 sp,
3466 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required because it\'s used within this {0:#}",
kind))
})
}with_forced_trimmed_paths!(format!(
3467 "required because it's used within this {kind:#}",
3468 )),
3469 );
3470 }
3471 ty::CoroutineWitness(..) => {
3472 }
3475 ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _) => {
3476 err.span_note(
3477 tcx.def_span(def_id),
3478 "required because it's used within this closure",
3479 );
3480 }
3481 ty::Str => {
3482 err.note("`str` is considered to contain a `[u8]` slice for auto trait purposes");
3483 }
3484 _ => {
3485 let msg = msg();
3486 err.note(msg);
3487 }
3488 };
3489 }
3490
3491 obligated_types.push(ty);
3492
3493 let parent_predicate = parent_trait_ref;
3494 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
3495 ensure_sufficient_stack(|| {
3497 self.note_obligation_cause_code(
3498 body_id,
3499 err,
3500 parent_predicate,
3501 param_env,
3502 &data.parent_code,
3503 obligated_types,
3504 seen_requirements,
3505 )
3506 });
3507 } else {
3508 ensure_sufficient_stack(|| {
3509 self.note_obligation_cause_code(
3510 body_id,
3511 err,
3512 parent_predicate,
3513 param_env,
3514 cause_code.peel_derives(),
3515 obligated_types,
3516 seen_requirements,
3517 )
3518 });
3519 }
3520 }
3521 ObligationCauseCode::ImplDerived(ref data) => {
3522 let mut parent_trait_pred =
3523 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3524 let parent_def_id = parent_trait_pred.def_id();
3525 if tcx.is_diagnostic_item(sym::FromResidual, parent_def_id)
3526 && !tcx.features().enabled(sym::try_trait_v2)
3527 {
3528 return;
3532 }
3533 if tcx.is_diagnostic_item(sym::PinDerefMutHelper, parent_def_id) {
3534 let parent_predicate =
3535 self.resolve_vars_if_possible(data.derived.parent_trait_pred);
3536
3537 ensure_sufficient_stack(|| {
3539 self.note_obligation_cause_code(
3540 body_id,
3541 err,
3542 parent_predicate,
3543 param_env,
3544 &data.derived.parent_code,
3545 obligated_types,
3546 seen_requirements,
3547 )
3548 });
3549 return;
3550 }
3551 let self_ty_str =
3552 tcx.short_string(parent_trait_pred.skip_binder().self_ty(), err.long_ty_path());
3553 let trait_name = tcx.short_string(
3554 parent_trait_pred.print_modifiers_and_trait_path(),
3555 err.long_ty_path(),
3556 );
3557 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for `{0}` to implement `{1}`",
self_ty_str, trait_name))
})format!("required for `{self_ty_str}` to implement `{trait_name}`");
3558 let mut is_auto_trait = false;
3559 match tcx.hir_get_if_local(data.impl_or_alias_def_id) {
3560 Some(Node::Item(hir::Item {
3561 kind: hir::ItemKind::Trait(_, is_auto, _, ident, ..),
3562 ..
3563 })) => {
3564 is_auto_trait = #[allow(non_exhaustive_omitted_patterns)] match is_auto {
hir::IsAuto::Yes => true,
_ => false,
}matches!(is_auto, hir::IsAuto::Yes);
3567 err.span_note(ident.span, msg);
3568 }
3569 Some(Node::Item(hir::Item {
3570 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, generics, .. }),
3571 ..
3572 })) => {
3573 let mut spans = Vec::with_capacity(2);
3574 if let Some(of_trait) = of_trait
3575 && !of_trait.trait_ref.path.span.in_derive_expansion()
3576 {
3577 spans.push(of_trait.trait_ref.path.span);
3578 }
3579 spans.push(self_ty.span);
3580 let mut spans: MultiSpan = spans.into();
3581 let mut derived = false;
3582 if #[allow(non_exhaustive_omitted_patterns)] match self_ty.span.ctxt().outer_expn_data().kind
{
ExpnKind::Macro(MacroKind::Derive, _) => true,
_ => false,
}matches!(
3583 self_ty.span.ctxt().outer_expn_data().kind,
3584 ExpnKind::Macro(MacroKind::Derive, _)
3585 ) || #[allow(non_exhaustive_omitted_patterns)] match of_trait.map(|t|
t.trait_ref.path.span.ctxt().outer_expn_data().kind) {
Some(ExpnKind::Macro(MacroKind::Derive, _)) => true,
_ => false,
}matches!(
3586 of_trait.map(|t| t.trait_ref.path.span.ctxt().outer_expn_data().kind),
3587 Some(ExpnKind::Macro(MacroKind::Derive, _))
3588 ) {
3589 derived = true;
3590 spans.push_span_label(
3591 data.span,
3592 if data.span.in_derive_expansion() {
3593 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter would need to implement `{0}`",
trait_name))
})format!("type parameter would need to implement `{trait_name}`")
3594 } else {
3595 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied trait bound"))
})format!("unsatisfied trait bound")
3596 },
3597 );
3598 } else if !data.span.is_dummy() && !data.span.overlaps(self_ty.span) {
3599 if let Some(pred) = predicate.as_trait_clause()
3602 && self.tcx.is_lang_item(pred.def_id(), LangItem::Sized)
3603 && self
3604 .tcx
3605 .generics_of(data.impl_or_alias_def_id)
3606 .own_params
3607 .iter()
3608 .any(|param| self.tcx.def_span(param.def_id) == data.span)
3609 {
3610 spans.push_span_label(
3611 data.span,
3612 "unsatisfied trait bound implicitly introduced here",
3613 );
3614 } else {
3615 spans.push_span_label(
3616 data.span,
3617 "unsatisfied trait bound introduced here",
3618 );
3619 }
3620 }
3621 err.span_note(spans, msg);
3622 if derived && trait_name != "Copy" {
3623 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider manually implementing `{0}` to avoid undesired bounds",
trait_name))
})format!(
3624 "consider manually implementing `{trait_name}` to avoid undesired \
3625 bounds",
3626 ));
3627 }
3628 point_at_assoc_type_restriction(
3629 tcx,
3630 err,
3631 &self_ty_str,
3632 &trait_name,
3633 predicate,
3634 &generics,
3635 &data,
3636 );
3637 }
3638 _ => {
3639 err.note(msg);
3640 }
3641 };
3642
3643 let mut parent_predicate = parent_trait_pred;
3644 let mut data = &data.derived;
3645 let mut count = 0;
3646 seen_requirements.insert(parent_def_id);
3647 if is_auto_trait {
3648 while let ObligationCauseCode::BuiltinDerived(derived) = &*data.parent_code {
3651 let child_trait_ref =
3652 self.resolve_vars_if_possible(derived.parent_trait_pred);
3653 let child_def_id = child_trait_ref.def_id();
3654 if seen_requirements.insert(child_def_id) {
3655 break;
3656 }
3657 data = derived;
3658 parent_predicate = child_trait_ref.upcast(tcx);
3659 parent_trait_pred = child_trait_ref;
3660 }
3661 }
3662 while let ObligationCauseCode::ImplDerived(child) = &*data.parent_code {
3663 let child_trait_pred =
3665 self.resolve_vars_if_possible(child.derived.parent_trait_pred);
3666 let child_def_id = child_trait_pred.def_id();
3667 if seen_requirements.insert(child_def_id) {
3668 break;
3669 }
3670 count += 1;
3671 data = &child.derived;
3672 parent_predicate = child_trait_pred.upcast(tcx);
3673 parent_trait_pred = child_trait_pred;
3674 }
3675 if count > 0 {
3676 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} redundant requirement{1} hidden",
count, if count == 1 { "" } else { "s" }))
})format!(
3677 "{} redundant requirement{} hidden",
3678 count,
3679 pluralize!(count)
3680 ));
3681 let self_ty = tcx.short_string(
3682 parent_trait_pred.skip_binder().self_ty(),
3683 err.long_ty_path(),
3684 );
3685 let trait_path = tcx.short_string(
3686 parent_trait_pred.print_modifiers_and_trait_path(),
3687 err.long_ty_path(),
3688 );
3689 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for `{0}` to implement `{1}`",
self_ty, trait_path))
})format!("required for `{self_ty}` to implement `{trait_path}`"));
3690 }
3691 ensure_sufficient_stack(|| {
3693 self.note_obligation_cause_code(
3694 body_id,
3695 err,
3696 parent_predicate,
3697 param_env,
3698 &data.parent_code,
3699 obligated_types,
3700 seen_requirements,
3701 )
3702 });
3703 }
3704 ObligationCauseCode::ImplDerivedHost(ref data) => {
3705 let self_ty = tcx.short_string(
3706 self.resolve_vars_if_possible(data.derived.parent_host_pred.self_ty()),
3707 err.long_ty_path(),
3708 );
3709 let trait_path = tcx.short_string(
3710 data.derived
3711 .parent_host_pred
3712 .map_bound(|pred| pred.trait_ref)
3713 .print_only_trait_path(),
3714 err.long_ty_path(),
3715 );
3716 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required for `{1}` to implement `{0} {2}`",
data.derived.parent_host_pred.skip_binder().constness,
self_ty, trait_path))
})format!(
3717 "required for `{self_ty}` to implement `{} {trait_path}`",
3718 data.derived.parent_host_pred.skip_binder().constness,
3719 );
3720 match tcx.hir_get_if_local(data.impl_def_id) {
3721 Some(Node::Item(hir::Item {
3722 kind: hir::ItemKind::Impl(hir::Impl { of_trait, self_ty, .. }),
3723 ..
3724 })) => {
3725 let mut spans = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self_ty.span]))vec![self_ty.span];
3726 spans.extend(of_trait.map(|t| t.trait_ref.path.span));
3727 let mut spans: MultiSpan = spans.into();
3728 spans.push_span_label(data.span, "unsatisfied trait bound introduced here");
3729 err.span_note(spans, msg);
3730 }
3731 _ => {
3732 err.note(msg);
3733 }
3734 }
3735 ensure_sufficient_stack(|| {
3736 self.note_obligation_cause_code(
3737 body_id,
3738 err,
3739 data.derived.parent_host_pred,
3740 param_env,
3741 &data.derived.parent_code,
3742 obligated_types,
3743 seen_requirements,
3744 )
3745 });
3746 }
3747 ObligationCauseCode::BuiltinDerivedHost(ref data) => {
3748 ensure_sufficient_stack(|| {
3749 self.note_obligation_cause_code(
3750 body_id,
3751 err,
3752 data.parent_host_pred,
3753 param_env,
3754 &data.parent_code,
3755 obligated_types,
3756 seen_requirements,
3757 )
3758 });
3759 }
3760 ObligationCauseCode::WellFormedDerived(ref data) => {
3761 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3762 let parent_predicate = parent_trait_ref;
3763 ensure_sufficient_stack(|| {
3765 self.note_obligation_cause_code(
3766 body_id,
3767 err,
3768 parent_predicate,
3769 param_env,
3770 &data.parent_code,
3771 obligated_types,
3772 seen_requirements,
3773 )
3774 });
3775 }
3776 ObligationCauseCode::TypeAlias(ref nested, span, def_id) => {
3777 ensure_sufficient_stack(|| {
3779 self.note_obligation_cause_code(
3780 body_id,
3781 err,
3782 predicate,
3783 param_env,
3784 nested,
3785 obligated_types,
3786 seen_requirements,
3787 )
3788 });
3789 let mut multispan = MultiSpan::from(span);
3790 multispan.push_span_label(span, "required by this bound");
3791 err.span_note(
3792 multispan,
3793 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required by a bound on the type alias `{0}`",
tcx.item_name(def_id)))
})format!("required by a bound on the type alias `{}`", tcx.item_name(def_id)),
3794 );
3795 }
3796 ObligationCauseCode::FunctionArg {
3797 arg_hir_id, call_hir_id, ref parent_code, ..
3798 } => {
3799 self.note_function_argument_obligation(
3800 body_id,
3801 err,
3802 arg_hir_id,
3803 parent_code,
3804 param_env,
3805 predicate,
3806 call_hir_id,
3807 );
3808 ensure_sufficient_stack(|| {
3809 self.note_obligation_cause_code(
3810 body_id,
3811 err,
3812 predicate,
3813 param_env,
3814 parent_code,
3815 obligated_types,
3816 seen_requirements,
3817 )
3818 });
3819 }
3820 ObligationCauseCode::CompareImplItem { trait_item_def_id, .. }
3823 if tcx.is_impl_trait_in_trait(trait_item_def_id) => {}
3824 ObligationCauseCode::CompareImplItem { trait_item_def_id, kind, .. } => {
3825 let item_name = tcx.item_name(trait_item_def_id);
3826 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the requirement `{0}` appears on the `impl`\'s {1} `{2}` but not on the corresponding trait\'s {1}",
predicate, kind, item_name))
})format!(
3827 "the requirement `{predicate}` appears on the `impl`'s {kind} \
3828 `{item_name}` but not on the corresponding trait's {kind}",
3829 );
3830 let sp = tcx
3831 .opt_item_ident(trait_item_def_id)
3832 .map(|i| i.span)
3833 .unwrap_or_else(|| tcx.def_span(trait_item_def_id));
3834 let mut assoc_span: MultiSpan = sp.into();
3835 assoc_span.push_span_label(
3836 sp,
3837 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this trait\'s {0} doesn\'t have the requirement `{1}`",
kind, predicate))
})format!("this trait's {kind} doesn't have the requirement `{predicate}`"),
3838 );
3839 if let Some(ident) = tcx
3840 .opt_associated_item(trait_item_def_id)
3841 .and_then(|i| tcx.opt_item_ident(i.container_id(tcx)))
3842 {
3843 assoc_span.push_span_label(ident.span, "in this trait");
3844 }
3845 err.span_note(assoc_span, msg);
3846 }
3847 ObligationCauseCode::TrivialBound => {
3848 err.help("see issue #48214");
3849 tcx.disabled_nightly_features(err, [(String::new(), sym::trivial_bounds)]);
3850 }
3851 ObligationCauseCode::OpaqueReturnType(expr_info) => {
3852 let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info {
3853 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3854 let expr = tcx.hir_expect_expr(hir_id);
3855 (expr_ty, expr)
3856 } else if let Some(body_id) = tcx.hir_node_by_def_id(body_id).body_id()
3857 && let body = tcx.hir_body(body_id)
3858 && let hir::ExprKind::Block(block, _) = body.value.kind
3859 && let Some(expr) = block.expr
3860 && let Some(expr_ty) = self
3861 .typeck_results
3862 .as_ref()
3863 .and_then(|typeck| typeck.node_type_opt(expr.hir_id))
3864 && let Some(pred) = predicate.as_clause()
3865 && let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder()
3866 && self.can_eq(param_env, pred.self_ty(), expr_ty)
3867 {
3868 let expr_ty = tcx.short_string(expr_ty, err.long_ty_path());
3869 (expr_ty, expr)
3870 } else {
3871 return;
3872 };
3873 err.span_label(
3874 expr.span,
3875 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("return type was inferred to be `{0}` here",
expr_ty))
})
}with_forced_trimmed_paths!(format!(
3876 "return type was inferred to be `{expr_ty}` here",
3877 )),
3878 );
3879 suggest_remove_deref(err, &expr);
3880 }
3881 ObligationCauseCode::UnsizedNonPlaceExpr(span) => {
3882 err.span_note(
3883 span,
3884 "unsized values must be place expressions and cannot be put in temporaries",
3885 );
3886 }
3887 ObligationCauseCode::CompareEii { .. } => {
3888 {
::core::panicking::panic_fmt(format_args!("trait bounds on EII not yet supported "));
}panic!("trait bounds on EII not yet supported ")
3889 }
3890 }
3891 }
3892
3893 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_await_before_try",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3893u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["obligation",
"trait_pred", "span", "trait_pred.self_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_pred.self_ty())
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let future_trait =
self.tcx.require_lang_item(LangItem::Future, span);
let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
let impls_future =
self.type_implements_trait(future_trait,
[self.tcx.instantiate_bound_regions_with_erased(self_ty)],
obligation.param_env);
if !impls_future.must_apply_modulo_regions() { return; }
let item_def_id =
self.tcx.associated_item_def_ids(future_trait)[0];
let projection_ty =
trait_pred.map_bound(|trait_pred|
{
Ty::new_projection(self.tcx, item_def_id,
[trait_pred.self_ty()])
});
let InferOk { value: projection_ty, .. } =
self.at(&obligation.cause,
obligation.param_env).normalize(projection_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3928",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3928u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["normalized_projection_type"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self.resolve_vars_if_possible(projection_ty))
as &dyn Value))])
});
} else { ; }
};
let try_obligation =
self.mk_trait_obligation_with_new_self_ty(obligation.param_env,
trait_pred.map_bound(|trait_pred|
(trait_pred, projection_ty.skip_binder())));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:3935",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(3935u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["try_trait_obligation"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&try_obligation)
as &dyn Value))])
});
} else { ; }
};
if self.predicate_may_hold(&try_obligation) &&
let Ok(snippet) =
self.tcx.sess.source_map().span_to_snippet(span) &&
snippet.ends_with('?') {
match self.tcx.coroutine_kind(obligation.cause.body_id) {
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
_)) => {
err.span_suggestion_verbose(span.with_hi(span.hi() -
BytePos(1)).shrink_to_hi(),
"consider `await`ing on the `Future`", ".await",
Applicability::MaybeIncorrect);
}
_ => {
let mut span: MultiSpan =
span.with_lo(span.hi() - BytePos(1)).into();
span.push_span_label(self.tcx.def_span(obligation.cause.body_id),
"this is not `async`");
err.span_note(span,
"this implements `Future` and its output type supports \
`?`, but the future cannot be awaited in a synchronous function");
}
}
}
}
}
}#[instrument(
3894 level = "debug", skip(self, err), fields(trait_pred.self_ty = ?trait_pred.self_ty())
3895 )]
3896 pub(super) fn suggest_await_before_try(
3897 &self,
3898 err: &mut Diag<'_>,
3899 obligation: &PredicateObligation<'tcx>,
3900 trait_pred: ty::PolyTraitPredicate<'tcx>,
3901 span: Span,
3902 ) {
3903 let future_trait = self.tcx.require_lang_item(LangItem::Future, span);
3904
3905 let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty());
3906 let impls_future = self.type_implements_trait(
3907 future_trait,
3908 [self.tcx.instantiate_bound_regions_with_erased(self_ty)],
3909 obligation.param_env,
3910 );
3911 if !impls_future.must_apply_modulo_regions() {
3912 return;
3913 }
3914
3915 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
3916 let projection_ty = trait_pred.map_bound(|trait_pred| {
3918 Ty::new_projection(
3919 self.tcx,
3920 item_def_id,
3921 [trait_pred.self_ty()],
3923 )
3924 });
3925 let InferOk { value: projection_ty, .. } =
3926 self.at(&obligation.cause, obligation.param_env).normalize(projection_ty);
3927
3928 debug!(
3929 normalized_projection_type = ?self.resolve_vars_if_possible(projection_ty)
3930 );
3931 let try_obligation = self.mk_trait_obligation_with_new_self_ty(
3932 obligation.param_env,
3933 trait_pred.map_bound(|trait_pred| (trait_pred, projection_ty.skip_binder())),
3934 );
3935 debug!(try_trait_obligation = ?try_obligation);
3936 if self.predicate_may_hold(&try_obligation)
3937 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
3938 && snippet.ends_with('?')
3939 {
3940 match self.tcx.coroutine_kind(obligation.cause.body_id) {
3941 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3942 err.span_suggestion_verbose(
3943 span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),
3944 "consider `await`ing on the `Future`",
3945 ".await",
3946 Applicability::MaybeIncorrect,
3947 );
3948 }
3949 _ => {
3950 let mut span: MultiSpan = span.with_lo(span.hi() - BytePos(1)).into();
3951 span.push_span_label(
3952 self.tcx.def_span(obligation.cause.body_id),
3953 "this is not `async`",
3954 );
3955 err.span_note(
3956 span,
3957 "this implements `Future` and its output type supports \
3958 `?`, but the future cannot be awaited in a synchronous function",
3959 );
3960 }
3961 }
3962 }
3963 }
3964
3965 pub(super) fn suggest_floating_point_literal(
3966 &self,
3967 obligation: &PredicateObligation<'tcx>,
3968 err: &mut Diag<'_>,
3969 trait_pred: ty::PolyTraitPredicate<'tcx>,
3970 ) {
3971 let rhs_span = match obligation.cause.code() {
3972 ObligationCauseCode::BinOp { rhs_span, rhs_is_lit, .. } if *rhs_is_lit => rhs_span,
3973 _ => return,
3974 };
3975 if let ty::Float(_) = trait_pred.skip_binder().self_ty().kind()
3976 && let ty::Infer(InferTy::IntVar(_)) =
3977 trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
3978 {
3979 err.span_suggestion_verbose(
3980 rhs_span.shrink_to_hi(),
3981 "consider using a floating-point literal by writing it with `.0`",
3982 ".0",
3983 Applicability::MaybeIncorrect,
3984 );
3985 }
3986 }
3987
3988 pub fn can_suggest_derive(
3989 &self,
3990 obligation: &PredicateObligation<'tcx>,
3991 trait_pred: ty::PolyTraitPredicate<'tcx>,
3992 ) -> bool {
3993 if trait_pred.polarity() == ty::PredicatePolarity::Negative {
3994 return false;
3995 }
3996 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
3997 return false;
3998 };
3999 let (adt, args) = match trait_pred.skip_binder().self_ty().kind() {
4000 ty::Adt(adt, args) if adt.did().is_local() => (adt, args),
4001 _ => return false,
4002 };
4003 let is_derivable_trait = match diagnostic_name {
4004 sym::Default => !adt.is_enum(),
4005 sym::PartialEq | sym::PartialOrd => {
4006 let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
4007 trait_pred.skip_binder().self_ty() == rhs_ty
4008 }
4009 sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true,
4010 _ => false,
4011 };
4012 is_derivable_trait &&
4013 adt.all_fields().all(|field| {
4015 let field_ty = ty::GenericArg::from(field.ty(self.tcx, args));
4016 let trait_args = match diagnostic_name {
4017 sym::PartialEq | sym::PartialOrd => {
4018 Some(field_ty)
4019 }
4020 _ => None,
4021 };
4022 let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate {
4023 trait_ref: ty::TraitRef::new(self.tcx,
4024 trait_pred.def_id(),
4025 [field_ty].into_iter().chain(trait_args),
4026 ),
4027 ..*tr
4028 });
4029 let field_obl = Obligation::new(
4030 self.tcx,
4031 obligation.cause.clone(),
4032 obligation.param_env,
4033 trait_pred,
4034 );
4035 self.predicate_must_hold_modulo_regions(&field_obl)
4036 })
4037 }
4038
4039 pub fn suggest_derive(
4040 &self,
4041 obligation: &PredicateObligation<'tcx>,
4042 err: &mut Diag<'_>,
4043 trait_pred: ty::PolyTraitPredicate<'tcx>,
4044 ) {
4045 let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else {
4046 return;
4047 };
4048 let adt = match trait_pred.skip_binder().self_ty().kind() {
4049 ty::Adt(adt, _) if adt.did().is_local() => adt,
4050 _ => return,
4051 };
4052 if self.can_suggest_derive(obligation, trait_pred) {
4053 err.span_suggestion_verbose(
4054 self.tcx.def_span(adt.did()).shrink_to_lo(),
4055 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider annotating `{0}` with `#[derive({1})]`",
trait_pred.skip_binder().self_ty(), diagnostic_name))
})format!(
4056 "consider annotating `{}` with `#[derive({})]`",
4057 trait_pred.skip_binder().self_ty(),
4058 diagnostic_name,
4059 ),
4060 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[derive({0})]\n",
diagnostic_name))
})format!("#[derive({diagnostic_name})]\n"),
4062 Applicability::MaybeIncorrect,
4063 );
4064 }
4065 }
4066
4067 pub(super) fn suggest_dereferencing_index(
4068 &self,
4069 obligation: &PredicateObligation<'tcx>,
4070 err: &mut Diag<'_>,
4071 trait_pred: ty::PolyTraitPredicate<'tcx>,
4072 ) {
4073 if let ObligationCauseCode::ImplDerived(_) = obligation.cause.code()
4074 && self
4075 .tcx
4076 .is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id)
4077 && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
4078 && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind()
4079 && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind()
4080 {
4081 err.span_suggestion_verbose(
4082 obligation.cause.span.shrink_to_lo(),
4083 "dereference this index",
4084 '*',
4085 Applicability::MachineApplicable,
4086 );
4087 }
4088 }
4089
4090 fn note_function_argument_obligation<G: EmissionGuarantee>(
4091 &self,
4092 body_id: LocalDefId,
4093 err: &mut Diag<'_, G>,
4094 arg_hir_id: HirId,
4095 parent_code: &ObligationCauseCode<'tcx>,
4096 param_env: ty::ParamEnv<'tcx>,
4097 failed_pred: ty::Predicate<'tcx>,
4098 call_hir_id: HirId,
4099 ) {
4100 let tcx = self.tcx;
4101 if let Node::Expr(expr) = tcx.hir_node(arg_hir_id)
4102 && let Some(typeck_results) = &self.typeck_results
4103 {
4104 if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr
4105 && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id)
4106 && let Some(failed_pred) = failed_pred.as_trait_clause()
4107 && let pred = failed_pred.map_bound(|pred| pred.with_replaced_self_ty(tcx, ty))
4108 && self.predicate_must_hold_modulo_regions(&Obligation::misc(
4109 tcx, expr.span, body_id, param_env, pred,
4110 ))
4111 && expr.span.hi() != rcvr.span.hi()
4112 {
4113 let should_sugg = match tcx.hir_node(call_hir_id) {
4114 Node::Expr(hir::Expr {
4115 kind: hir::ExprKind::MethodCall(_, call_receiver, _, _),
4116 ..
4117 }) if let Some((DefKind::AssocFn, did)) =
4118 typeck_results.type_dependent_def(call_hir_id)
4119 && call_receiver.hir_id == arg_hir_id =>
4120 {
4121 if tcx.inherent_impl_of_assoc(did).is_some() {
4125 Some(ty) == typeck_results.node_type_opt(arg_hir_id)
4127 } else {
4128 let trait_id = tcx
4130 .trait_of_assoc(did)
4131 .unwrap_or_else(|| tcx.impl_trait_id(tcx.parent(did)));
4132 let args = typeck_results.node_args(call_hir_id);
4133 let tr = ty::TraitRef::from_assoc(tcx, trait_id, args)
4134 .with_replaced_self_ty(tcx, ty);
4135 self.type_implements_trait(tr.def_id, tr.args, param_env)
4136 .must_apply_modulo_regions()
4137 }
4138 }
4139 _ => true,
4140 };
4141
4142 if should_sugg {
4143 err.span_suggestion_verbose(
4144 expr.span.with_lo(rcvr.span.hi()),
4145 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider removing this method call, as the receiver has type `{0}` and `{1}` trivially holds",
ty, pred))
})format!(
4146 "consider removing this method call, as the receiver has type `{ty}` and \
4147 `{pred}` trivially holds",
4148 ),
4149 "",
4150 Applicability::MaybeIncorrect,
4151 );
4152 }
4153 }
4154 if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr {
4155 let inner_expr = expr.peel_blocks();
4156 let ty = typeck_results
4157 .expr_ty_adjusted_opt(inner_expr)
4158 .unwrap_or(Ty::new_misc_error(tcx));
4159 let span = inner_expr.span;
4160 if Some(span) != err.span.primary_span()
4161 && !span.in_external_macro(tcx.sess.source_map())
4162 {
4163 err.span_label(
4164 span,
4165 if ty.references_error() {
4166 String::new()
4167 } else {
4168 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4169 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this tail expression is of type `{0}`",
ty))
})format!("this tail expression is of type `{ty}`")
4170 },
4171 );
4172 if let ty::PredicateKind::Clause(clause) = failed_pred.kind().skip_binder()
4173 && let ty::ClauseKind::Trait(pred) = clause
4174 && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()
4175 {
4176 if let [stmt, ..] = block.stmts
4177 && let hir::StmtKind::Semi(value) = stmt.kind
4178 && let hir::ExprKind::Closure(hir::Closure {
4179 body, fn_decl_span, ..
4180 }) = value.kind
4181 && let body = tcx.hir_body(*body)
4182 && !#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(body.value.kind, hir::ExprKind::Block(..))
4183 {
4184 err.multipart_suggestion(
4187 "you might have meant to open the closure body instead of placing \
4188 a closure within a block",
4189 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.with_hi(value.span.lo()), String::new()),
(fn_decl_span.shrink_to_hi(), " {".to_string())]))vec![
4190 (expr.span.with_hi(value.span.lo()), String::new()),
4191 (fn_decl_span.shrink_to_hi(), " {".to_string()),
4192 ],
4193 Applicability::MaybeIncorrect,
4194 );
4195 } else {
4196 err.span_suggestion_verbose(
4198 expr.span.shrink_to_lo(),
4199 "you might have meant to create the closure instead of a block",
4200 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}| ",
(0..pred.trait_ref.args.len() -
1).map(|_| "_").collect::<Vec<_>>().join(", ")))
})format!(
4201 "|{}| ",
4202 (0..pred.trait_ref.args.len() - 1)
4203 .map(|_| "_")
4204 .collect::<Vec<_>>()
4205 .join(", ")
4206 ),
4207 Applicability::MaybeIncorrect,
4208 );
4209 }
4210 }
4211 }
4212 }
4213
4214 let mut type_diffs = ::alloc::vec::Vec::new()vec![];
4219 if let ObligationCauseCode::WhereClauseInExpr(def_id, _, _, idx) = parent_code
4220 && let Some(node_args) = typeck_results.node_args_opt(call_hir_id)
4221 && let where_clauses =
4222 self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args)
4223 && let Some(where_pred) = where_clauses.predicates.get(*idx)
4224 {
4225 if let Some(where_pred) = where_pred.as_trait_clause()
4226 && let Some(failed_pred) = failed_pred.as_trait_clause()
4227 && where_pred.def_id() == failed_pred.def_id()
4228 {
4229 self.enter_forall(where_pred, |where_pred| {
4230 let failed_pred = self.instantiate_binder_with_fresh_vars(
4231 expr.span,
4232 BoundRegionConversionTime::FnCall,
4233 failed_pred,
4234 );
4235
4236 let zipped =
4237 iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args);
4238 for (expected, actual) in zipped {
4239 self.probe(|_| {
4240 match self
4241 .at(&ObligationCause::misc(expr.span, body_id), param_env)
4242 .eq(DefineOpaqueTypes::Yes, expected, actual)
4245 {
4246 Ok(_) => (), Err(err) => type_diffs.push(err),
4248 }
4249 })
4250 }
4251 })
4252 } else if let Some(where_pred) = where_pred.as_projection_clause()
4253 && let Some(failed_pred) = failed_pred.as_projection_clause()
4254 && let Some(found) = failed_pred.skip_binder().term.as_type()
4255 {
4256 type_diffs = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TypeError::Sorts(ty::error::ExpectedFound {
expected: where_pred.skip_binder().projection_term.expect_ty(self.tcx).to_ty(self.tcx),
found,
})]))vec![TypeError::Sorts(ty::error::ExpectedFound {
4257 expected: where_pred
4258 .skip_binder()
4259 .projection_term
4260 .expect_ty(self.tcx)
4261 .to_ty(self.tcx),
4262 found,
4263 })];
4264 }
4265 }
4266 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4267 && let hir::Path { res: Res::Local(hir_id), .. } = path
4268 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4269 && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(binding.hir_id)
4270 && let Some(binding_expr) = local.init
4271 {
4272 self.point_at_chain(binding_expr, typeck_results, type_diffs, param_env, err);
4276 } else {
4277 self.point_at_chain(expr, typeck_results, type_diffs, param_env, err);
4278 }
4279 }
4280 let call_node = tcx.hir_node(call_hir_id);
4281 if let Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. }) =
4282 call_node
4283 {
4284 if Some(rcvr.span) == err.span.primary_span() {
4285 err.replace_span_with(path.ident.span, true);
4286 }
4287 }
4288
4289 if let Node::Expr(expr) = call_node {
4290 if let hir::ExprKind::Call(hir::Expr { span, .. }, _)
4291 | hir::ExprKind::MethodCall(
4292 hir::PathSegment { ident: Ident { span, .. }, .. },
4293 ..,
4294 ) = expr.kind
4295 {
4296 if Some(*span) != err.span.primary_span() {
4297 let msg = if span.is_desugaring(DesugaringKind::FormatLiteral { source: true })
4298 {
4299 "required by this formatting parameter"
4300 } else if span.is_desugaring(DesugaringKind::FormatLiteral { source: false }) {
4301 "required by a formatting parameter in this expression"
4302 } else {
4303 "required by a bound introduced by this call"
4304 };
4305 err.span_label(*span, msg);
4306 }
4307 }
4308
4309 if let hir::ExprKind::MethodCall(_, expr, ..) = expr.kind {
4310 self.suggest_option_method_if_applicable(failed_pred, param_env, err, expr);
4311 }
4312 }
4313 }
4314
4315 fn suggest_option_method_if_applicable<G: EmissionGuarantee>(
4316 &self,
4317 failed_pred: ty::Predicate<'tcx>,
4318 param_env: ty::ParamEnv<'tcx>,
4319 err: &mut Diag<'_, G>,
4320 expr: &hir::Expr<'_>,
4321 ) {
4322 let tcx = self.tcx;
4323 let infcx = self.infcx;
4324 let Some(typeck_results) = self.typeck_results.as_ref() else { return };
4325
4326 let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else {
4328 return;
4329 };
4330 if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) {
4331 return;
4332 }
4333
4334 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. }))
4337 = failed_pred.kind().skip_binder()
4338 && tcx.is_fn_trait(trait_ref.def_id)
4339 && let [self_ty, found_ty] = trait_ref.args.as_slice()
4340 && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn())
4341 && let fn_sig @ ty::FnSig {
4342 abi: ExternAbi::Rust,
4343 c_variadic: false,
4344 safety: hir::Safety::Safe,
4345 ..
4346 } = fn_ty.fn_sig(tcx).skip_binder()
4347
4348 && let Some(&ty::Ref(_, target_ty, needs_mut)) = fn_sig.inputs().first().map(|t| t.kind())
4350 && !target_ty.has_escaping_bound_vars()
4351
4352 && let Some(ty::Tuple(tys)) = found_ty.as_type().map(Ty::kind)
4354 && let &[found_ty] = tys.as_slice()
4355 && !found_ty.has_escaping_bound_vars()
4356
4357 && let Some(deref_target_did) = tcx.lang_items().deref_target()
4359 && let projection = Ty::new_projection_from_args(tcx,deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)]))
4360 && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(projection)
4361 && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation))
4362 && infcx.can_eq(param_env, deref_target, target_ty)
4363 {
4364 let help = if let hir::Mutability::Mut = needs_mut
4365 && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait()
4366 && infcx
4367 .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env)
4368 .must_apply_modulo_regions()
4369 {
4370 Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()"))
4371 } else if let hir::Mutability::Not = needs_mut {
4372 Some(("call `Option::as_deref()` first", ".as_deref()"))
4373 } else {
4374 None
4375 };
4376
4377 if let Some((msg, sugg)) = help {
4378 err.span_suggestion_with_style(
4379 expr.span.shrink_to_hi(),
4380 msg,
4381 sugg,
4382 Applicability::MaybeIncorrect,
4383 SuggestionStyle::ShowAlways,
4384 );
4385 }
4386 }
4387 }
4388
4389 fn look_for_iterator_item_mistakes<G: EmissionGuarantee>(
4390 &self,
4391 assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>],
4392 typeck_results: &TypeckResults<'tcx>,
4393 type_diffs: &[TypeError<'tcx>],
4394 param_env: ty::ParamEnv<'tcx>,
4395 path_segment: &hir::PathSegment<'_>,
4396 args: &[hir::Expr<'_>],
4397 prev_ty: Ty<'_>,
4398 err: &mut Diag<'_, G>,
4399 ) {
4400 let tcx = self.tcx;
4401 for entry in assocs_in_this_method {
4404 let Some((_span, (def_id, ty))) = entry else {
4405 continue;
4406 };
4407 for diff in type_diffs {
4408 let TypeError::Sorts(expected_found) = diff else {
4409 continue;
4410 };
4411 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
4412 && path_segment.ident.name == sym::iter
4413 && self.can_eq(
4414 param_env,
4415 Ty::new_ref(
4416 tcx,
4417 tcx.lifetimes.re_erased,
4418 expected_found.found,
4419 ty::Mutability::Not,
4420 ),
4421 *ty,
4422 )
4423 && let [] = args
4424 {
4425 err.span_suggestion_verbose(
4427 path_segment.ident.span,
4428 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider consuming the `{0}` to construct the `Iterator`",
prev_ty))
})format!("consider consuming the `{prev_ty}` to construct the `Iterator`"),
4429 "into_iter".to_string(),
4430 Applicability::MachineApplicable,
4431 );
4432 }
4433 if tcx.is_diagnostic_item(sym::IntoIteratorItem, *def_id)
4434 && path_segment.ident.name == sym::into_iter
4435 && self.can_eq(
4436 param_env,
4437 expected_found.found,
4438 Ty::new_ref(tcx, tcx.lifetimes.re_erased, *ty, ty::Mutability::Not),
4439 )
4440 && let [] = args
4441 {
4442 err.span_suggestion_verbose(
4444 path_segment.ident.span,
4445 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider not consuming the `{0}` to construct the `Iterator`",
prev_ty))
})format!(
4446 "consider not consuming the `{prev_ty}` to construct the `Iterator`"
4447 ),
4448 "iter".to_string(),
4449 Applicability::MachineApplicable,
4450 );
4451 }
4452 if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
4453 && path_segment.ident.name == sym::map
4454 && self.can_eq(param_env, expected_found.found, *ty)
4455 && let [arg] = args
4456 && let hir::ExprKind::Closure(closure) = arg.kind
4457 {
4458 let body = tcx.hir_body(closure.body);
4459 if let hir::ExprKind::Block(block, None) = body.value.kind
4460 && let None = block.expr
4461 && let [.., stmt] = block.stmts
4462 && let hir::StmtKind::Semi(expr) = stmt.kind
4463 && expected_found.found.is_unit()
4467 && expr.span.hi() != stmt.span.hi()
4472 {
4473 err.span_suggestion_verbose(
4474 expr.span.shrink_to_hi().with_hi(stmt.span.hi()),
4475 "consider removing this semicolon",
4476 String::new(),
4477 Applicability::MachineApplicable,
4478 );
4479 }
4480 let expr = if let hir::ExprKind::Block(block, None) = body.value.kind
4481 && let Some(expr) = block.expr
4482 {
4483 expr
4484 } else {
4485 body.value
4486 };
4487 if let hir::ExprKind::MethodCall(path_segment, rcvr, [], span) = expr.kind
4488 && path_segment.ident.name == sym::clone
4489 && let Some(expr_ty) = typeck_results.expr_ty_opt(expr)
4490 && let Some(rcvr_ty) = typeck_results.expr_ty_opt(rcvr)
4491 && self.can_eq(param_env, expr_ty, rcvr_ty)
4492 && let ty::Ref(_, ty, _) = expr_ty.kind()
4493 {
4494 err.span_label(
4495 span,
4496 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this method call is cloning the reference `{0}`, not `{1}` which doesn\'t implement `Clone`",
expr_ty, ty))
})format!(
4497 "this method call is cloning the reference `{expr_ty}`, not \
4498 `{ty}` which doesn't implement `Clone`",
4499 ),
4500 );
4501 let ty::Param(..) = ty.kind() else {
4502 continue;
4503 };
4504 let node =
4505 tcx.hir_node_by_def_id(tcx.hir_get_parent_item(expr.hir_id).def_id);
4506
4507 let pred = ty::Binder::dummy(ty::TraitPredicate {
4508 trait_ref: ty::TraitRef::new(
4509 tcx,
4510 tcx.require_lang_item(LangItem::Clone, span),
4511 [*ty],
4512 ),
4513 polarity: ty::PredicatePolarity::Positive,
4514 });
4515 let Some(generics) = node.generics() else {
4516 continue;
4517 };
4518 let Some(body_id) = node.body_id() else {
4519 continue;
4520 };
4521 suggest_restriction(
4522 tcx,
4523 tcx.hir_body_owner_def_id(body_id),
4524 generics,
4525 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter `{0}`", ty))
})format!("type parameter `{ty}`"),
4526 err,
4527 node.fn_sig(),
4528 None,
4529 pred,
4530 None,
4531 );
4532 }
4533 }
4534 }
4535 }
4536 }
4537
4538 fn point_at_chain<G: EmissionGuarantee>(
4539 &self,
4540 expr: &hir::Expr<'_>,
4541 typeck_results: &TypeckResults<'tcx>,
4542 type_diffs: Vec<TypeError<'tcx>>,
4543 param_env: ty::ParamEnv<'tcx>,
4544 err: &mut Diag<'_, G>,
4545 ) {
4546 let mut primary_spans = ::alloc::vec::Vec::new()vec![];
4547 let mut span_labels = ::alloc::vec::Vec::new()vec![];
4548
4549 let tcx = self.tcx;
4550
4551 let mut print_root_expr = true;
4552 let mut assocs = ::alloc::vec::Vec::new()vec![];
4553 let mut expr = expr;
4554 let mut prev_ty = self.resolve_vars_if_possible(
4555 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4556 );
4557 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
4558 expr = rcvr_expr;
4562 let assocs_in_this_method =
4563 self.probe_assoc_types_at_expr(&type_diffs, span, prev_ty, expr.hir_id, param_env);
4564 prev_ty = self.resolve_vars_if_possible(
4565 typeck_results.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(tcx)),
4566 );
4567 self.look_for_iterator_item_mistakes(
4568 &assocs_in_this_method,
4569 typeck_results,
4570 &type_diffs,
4571 param_env,
4572 path_segment,
4573 args,
4574 prev_ty,
4575 err,
4576 );
4577 assocs.push(assocs_in_this_method);
4578
4579 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
4580 && let hir::Path { res: Res::Local(hir_id), .. } = path
4581 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
4582 {
4583 let parent = self.tcx.parent_hir_node(binding.hir_id);
4584 if let hir::Node::LetStmt(local) = parent
4586 && let Some(binding_expr) = local.init
4587 {
4588 expr = binding_expr;
4590 }
4591 if let hir::Node::Param(param) = parent {
4592 let prev_ty = self.resolve_vars_if_possible(
4594 typeck_results
4595 .node_type_opt(param.hir_id)
4596 .unwrap_or(Ty::new_misc_error(tcx)),
4597 );
4598 let assocs_in_this_method = self.probe_assoc_types_at_expr(
4599 &type_diffs,
4600 param.ty_span,
4601 prev_ty,
4602 param.hir_id,
4603 param_env,
4604 );
4605 if assocs_in_this_method.iter().any(|a| a.is_some()) {
4606 assocs.push(assocs_in_this_method);
4607 print_root_expr = false;
4608 }
4609 break;
4610 }
4611 }
4612 }
4613 if let Some(ty) = typeck_results.expr_ty_opt(expr)
4616 && print_root_expr
4617 {
4618 let ty = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4619 span_labels.push((expr.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this expression has type `{0}`",
ty))
})format!("this expression has type `{ty}`")));
4623 };
4624 let mut assocs = assocs.into_iter().peekable();
4627 while let Some(assocs_in_method) = assocs.next() {
4628 let Some(prev_assoc_in_method) = assocs.peek() else {
4629 for entry in assocs_in_method {
4630 let Some((span, (assoc, ty))) = entry else {
4631 continue;
4632 };
4633 if primary_spans.is_empty()
4634 || type_diffs.iter().any(|diff| {
4635 let TypeError::Sorts(expected_found) = diff else {
4636 return false;
4637 };
4638 self.can_eq(param_env, expected_found.found, ty)
4639 })
4640 {
4641 primary_spans.push(span);
4647 }
4648 span_labels.push((
4649 span,
4650 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is `{1}` here",
self.tcx.def_path_str(assoc), ty))
})
}with_forced_trimmed_paths!(format!(
4651 "`{}` is `{ty}` here",
4652 self.tcx.def_path_str(assoc),
4653 )),
4654 ));
4655 }
4656 break;
4657 };
4658 for (entry, prev_entry) in
4659 assocs_in_method.into_iter().zip(prev_assoc_in_method.into_iter())
4660 {
4661 match (entry, prev_entry) {
4662 (Some((span, (assoc, ty))), Some((_, (_, prev_ty)))) => {
4663 let ty_str = { let _guard = ForceTrimmedGuard::new(); self.ty_to_string(ty) }with_forced_trimmed_paths!(self.ty_to_string(ty));
4664
4665 let assoc = { let _guard = ForceTrimmedGuard::new(); self.tcx.def_path_str(assoc) }with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
4666 if !self.can_eq(param_env, ty, *prev_ty) {
4667 if type_diffs.iter().any(|diff| {
4668 let TypeError::Sorts(expected_found) = diff else {
4669 return false;
4670 };
4671 self.can_eq(param_env, expected_found.found, ty)
4672 }) {
4673 primary_spans.push(span);
4674 }
4675 span_labels
4676 .push((span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` changed to `{1}` here",
assoc, ty_str))
})format!("`{assoc}` changed to `{ty_str}` here")));
4677 } else {
4678 span_labels.push((span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` remains `{1}` here", assoc,
ty_str))
})format!("`{assoc}` remains `{ty_str}` here")));
4679 }
4680 }
4681 (Some((span, (assoc, ty))), None) => {
4682 span_labels.push((
4683 span,
4684 {
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is `{1}` here",
self.tcx.def_path_str(assoc), self.ty_to_string(ty)))
})
}with_forced_trimmed_paths!(format!(
4685 "`{}` is `{}` here",
4686 self.tcx.def_path_str(assoc),
4687 self.ty_to_string(ty),
4688 )),
4689 ));
4690 }
4691 (None, Some(_)) | (None, None) => {}
4692 }
4693 }
4694 }
4695 if !primary_spans.is_empty() {
4696 let mut multi_span: MultiSpan = primary_spans.into();
4697 for (span, label) in span_labels {
4698 multi_span.push_span_label(span, label);
4699 }
4700 err.span_note(
4701 multi_span,
4702 "the method call chain might not have had the expected associated types",
4703 );
4704 }
4705 }
4706
4707 fn probe_assoc_types_at_expr(
4708 &self,
4709 type_diffs: &[TypeError<'tcx>],
4710 span: Span,
4711 prev_ty: Ty<'tcx>,
4712 body_id: HirId,
4713 param_env: ty::ParamEnv<'tcx>,
4714 ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>> {
4715 let ocx = ObligationCtxt::new(self.infcx);
4716 let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
4717 for diff in type_diffs {
4718 let TypeError::Sorts(expected_found) = diff else {
4719 continue;
4720 };
4721 let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else {
4722 continue;
4723 };
4724
4725 let args = GenericArgs::for_item(self.tcx, proj.def_id, |param, _| {
4729 if param.index == 0 {
4730 if true {
match param.kind {
ty::GenericParamDefKind::Type { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"ty::GenericParamDefKind::Type { .. }",
::core::option::Option::None);
}
};
};debug_assert_matches!(param.kind, ty::GenericParamDefKind::Type { .. });
4731 return prev_ty.into();
4732 }
4733 self.var_for_def(span, param)
4734 });
4735 let ty = self.infcx.next_ty_var(span);
4739 let projection = ty::Binder::dummy(ty::PredicateKind::Clause(
4741 ty::ClauseKind::Projection(ty::ProjectionPredicate {
4742 projection_term: ty::AliasTerm::new_from_args(self.tcx, proj.def_id, args),
4743 term: ty.into(),
4744 }),
4745 ));
4746 let body_def_id = self.tcx.hir_enclosing_body_owner(body_id);
4747 ocx.register_obligation(Obligation::misc(
4749 self.tcx,
4750 span,
4751 body_def_id,
4752 param_env,
4753 projection,
4754 ));
4755 if ocx.try_evaluate_obligations().is_empty()
4756 && let ty = self.resolve_vars_if_possible(ty)
4757 && !ty.is_ty_var()
4758 {
4759 assocs_in_this_method.push(Some((span, (proj.def_id, ty))));
4760 } else {
4761 assocs_in_this_method.push(None);
4766 }
4767 }
4768 assocs_in_this_method
4769 }
4770
4771 pub(super) fn suggest_convert_to_slice(
4775 &self,
4776 err: &mut Diag<'_>,
4777 obligation: &PredicateObligation<'tcx>,
4778 trait_pred: ty::PolyTraitPredicate<'tcx>,
4779 candidate_impls: &[ImplCandidate<'tcx>],
4780 span: Span,
4781 ) {
4782 let (ObligationCauseCode::BinOp { .. } | ObligationCauseCode::FunctionArg { .. }) =
4785 obligation.cause.code()
4786 else {
4787 return;
4788 };
4789
4790 let (element_ty, mut mutability) = match *trait_pred.skip_binder().self_ty().kind() {
4795 ty::Array(element_ty, _) => (element_ty, None),
4796
4797 ty::Ref(_, pointee_ty, mutability) => match *pointee_ty.kind() {
4798 ty::Array(element_ty, _) => (element_ty, Some(mutability)),
4799 _ => return,
4800 },
4801
4802 _ => return,
4803 };
4804
4805 let mut is_slice = |candidate: Ty<'tcx>| match *candidate.kind() {
4808 ty::RawPtr(t, m) | ty::Ref(_, t, m) => {
4809 if let ty::Slice(e) = *t.kind()
4810 && e == element_ty
4811 && m == mutability.unwrap_or(m)
4812 {
4813 mutability = Some(m);
4815 true
4816 } else {
4817 false
4818 }
4819 }
4820 _ => false,
4821 };
4822
4823 if let Some(slice_ty) = candidate_impls
4825 .iter()
4826 .map(|trait_ref| trait_ref.trait_ref.self_ty())
4827 .find(|t| is_slice(*t))
4828 {
4829 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("convert the array to a `{0}` slice instead",
slice_ty))
})format!("convert the array to a `{slice_ty}` slice instead");
4830
4831 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
4832 let mut suggestions = ::alloc::vec::Vec::new()vec![];
4833 if snippet.starts_with('&') {
4834 } else if let Some(hir::Mutability::Mut) = mutability {
4835 suggestions.push((span.shrink_to_lo(), "&mut ".into()));
4836 } else {
4837 suggestions.push((span.shrink_to_lo(), "&".into()));
4838 }
4839 suggestions.push((span.shrink_to_hi(), "[..]".into()));
4840 err.multipart_suggestion(msg, suggestions, Applicability::MaybeIncorrect);
4841 } else {
4842 err.span_help(span, msg);
4843 }
4844 }
4845 }
4846
4847 pub(super) fn suggest_tuple_wrapping(
4852 &self,
4853 err: &mut Diag<'_>,
4854 root_obligation: &PredicateObligation<'tcx>,
4855 obligation: &PredicateObligation<'tcx>,
4856 ) {
4857 let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() else {
4858 return;
4859 };
4860
4861 let Some(root_pred) = root_obligation.predicate.as_trait_clause() else { return };
4862
4863 let trait_ref = root_pred.map_bound(|root_pred| {
4864 root_pred.trait_ref.with_replaced_self_ty(
4865 self.tcx,
4866 Ty::new_tup(self.tcx, &[root_pred.trait_ref.self_ty()]),
4867 )
4868 });
4869
4870 let obligation =
4871 Obligation::new(self.tcx, obligation.cause.clone(), obligation.param_env, trait_ref);
4872
4873 if self.predicate_must_hold_modulo_regions(&obligation) {
4874 let arg_span = self.tcx.hir_span(*arg_hir_id);
4875 err.multipart_suggestion(
4876 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use a unary tuple instead"))
})format!("use a unary tuple instead"),
4877 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(arg_span.shrink_to_lo(), "(".into()),
(arg_span.shrink_to_hi(), ",)".into())]))vec![(arg_span.shrink_to_lo(), "(".into()), (arg_span.shrink_to_hi(), ",)".into())],
4878 Applicability::MaybeIncorrect,
4879 );
4880 }
4881 }
4882
4883 pub(super) fn explain_hrtb_projection(
4884 &self,
4885 diag: &mut Diag<'_>,
4886 pred: ty::PolyTraitPredicate<'tcx>,
4887 param_env: ty::ParamEnv<'tcx>,
4888 cause: &ObligationCause<'tcx>,
4889 ) {
4890 if pred.skip_binder().has_escaping_bound_vars() && pred.skip_binder().has_non_region_infer()
4891 {
4892 self.probe(|_| {
4893 let ocx = ObligationCtxt::new(self);
4894 self.enter_forall(pred, |pred| {
4895 let pred = ocx.normalize(&ObligationCause::dummy(), param_env, pred);
4896 ocx.register_obligation(Obligation::new(
4897 self.tcx,
4898 ObligationCause::dummy(),
4899 param_env,
4900 pred,
4901 ));
4902 });
4903 if !ocx.try_evaluate_obligations().is_empty() {
4904 return;
4906 }
4907
4908 if let ObligationCauseCode::FunctionArg {
4909 call_hir_id,
4910 arg_hir_id,
4911 parent_code: _,
4912 } = cause.code()
4913 {
4914 let arg_span = self.tcx.hir_span(*arg_hir_id);
4915 let mut sp: MultiSpan = arg_span.into();
4916
4917 sp.push_span_label(
4918 arg_span,
4919 "the trait solver is unable to infer the \
4920 generic types that should be inferred from this argument",
4921 );
4922 sp.push_span_label(
4923 self.tcx.hir_span(*call_hir_id),
4924 "add turbofish arguments to this call to \
4925 specify the types manually, even if it's redundant",
4926 );
4927 diag.span_note(
4928 sp,
4929 "this is a known limitation of the trait solver that \
4930 will be lifted in the future",
4931 );
4932 } else {
4933 let mut sp: MultiSpan = cause.span.into();
4934 sp.push_span_label(
4935 cause.span,
4936 "try adding turbofish arguments to this expression to \
4937 specify the types manually, even if it's redundant",
4938 );
4939 diag.span_note(
4940 sp,
4941 "this is a known limitation of the trait solver that \
4942 will be lifted in the future",
4943 );
4944 }
4945 });
4946 }
4947 }
4948
4949 pub(super) fn suggest_desugaring_async_fn_in_trait(
4950 &self,
4951 err: &mut Diag<'_>,
4952 trait_pred: ty::PolyTraitPredicate<'tcx>,
4953 ) {
4954 if self.tcx.features().return_type_notation() {
4956 return;
4957 }
4958
4959 let trait_def_id = trait_pred.def_id();
4960
4961 if !self.tcx.trait_is_auto(trait_def_id) {
4963 return;
4964 }
4965
4966 let ty::Alias(ty::Projection, alias_ty) = trait_pred.self_ty().skip_binder().kind() else {
4968 return;
4969 };
4970 let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, opaque_def_id }) =
4971 self.tcx.opt_rpitit_info(alias_ty.def_id)
4972 else {
4973 return;
4974 };
4975
4976 let auto_trait = self.tcx.def_path_str(trait_def_id);
4977 let Some(fn_def_id) = fn_def_id.as_local() else {
4979 if self.tcx.asyncness(fn_def_id).is_async() {
4981 err.span_note(
4982 self.tcx.def_span(fn_def_id),
4983 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` is an `async fn` in trait, which does not automatically imply that its future is `{2}`",
alias_ty.trait_ref(self.tcx), self.tcx.item_name(fn_def_id),
auto_trait))
})format!(
4984 "`{}::{}` is an `async fn` in trait, which does not \
4985 automatically imply that its future is `{auto_trait}`",
4986 alias_ty.trait_ref(self.tcx),
4987 self.tcx.item_name(fn_def_id)
4988 ),
4989 );
4990 }
4991 return;
4992 };
4993 let hir::Node::TraitItem(item) = self.tcx.hir_node_by_def_id(fn_def_id) else {
4994 return;
4995 };
4996
4997 let (sig, body) = item.expect_fn();
4999 let hir::FnRetTy::Return(hir::Ty { kind: hir::TyKind::OpaqueDef(opaq_def, ..), .. }) =
5000 sig.decl.output
5001 else {
5002 return;
5004 };
5005
5006 if opaq_def.def_id.to_def_id() != opaque_def_id {
5009 return;
5010 }
5011
5012 let Some(sugg) = suggest_desugaring_async_fn_to_impl_future_in_trait(
5013 self.tcx,
5014 *sig,
5015 *body,
5016 opaque_def_id.expect_local(),
5017 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" + {0}", auto_trait))
})format!(" + {auto_trait}"),
5018 ) else {
5019 return;
5020 };
5021
5022 let function_name = self.tcx.def_path_str(fn_def_id);
5023 err.multipart_suggestion(
5024 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` can be made part of the associated future\'s guarantees for all implementations of `{1}`",
auto_trait, function_name))
})format!(
5025 "`{auto_trait}` can be made part of the associated future's \
5026 guarantees for all implementations of `{function_name}`"
5027 ),
5028 sugg,
5029 Applicability::MachineApplicable,
5030 );
5031 }
5032
5033 pub fn ty_kind_suggestion(
5034 &self,
5035 param_env: ty::ParamEnv<'tcx>,
5036 ty: Ty<'tcx>,
5037 ) -> Option<String> {
5038 let tcx = self.infcx.tcx;
5039 let implements_default = |ty| {
5040 let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
5041 return false;
5042 };
5043 self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
5044 };
5045
5046 Some(match *ty.kind() {
5047 ty::Never | ty::Error(_) => return None,
5048 ty::Bool => "false".to_string(),
5049 ty::Char => "\'x\'".to_string(),
5050 ty::Int(_) | ty::Uint(_) => "42".into(),
5051 ty::Float(_) => "3.14159".into(),
5052 ty::Slice(_) => "[]".to_string(),
5053 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
5054 "vec![]".to_string()
5055 }
5056 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
5057 "String::new()".to_string()
5058 }
5059 ty::Adt(def, args) if def.is_box() => {
5060 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Box::new({0})",
self.ty_kind_suggestion(param_env, args[0].expect_ty())?))
})format!("Box::new({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
5061 }
5062 ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
5063 "None".to_string()
5064 }
5065 ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
5066 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("Ok({0})",
self.ty_kind_suggestion(param_env, args[0].expect_ty())?))
})format!("Ok({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
5067 }
5068 ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
5069 ty::Ref(_, ty, mutability) => {
5070 if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
5071 "\"\"".to_string()
5072 } else {
5073 let ty = self.ty_kind_suggestion(param_env, ty)?;
5074 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}{1}", mutability.prefix_str(),
ty))
})format!("&{}{ty}", mutability.prefix_str())
5075 }
5076 }
5077 ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => {
5078 if len == 0 {
5079 "[]".to_string()
5080 } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 {
5081 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[{0}; {1}]",
self.ty_kind_suggestion(param_env, ty)?, len))
})format!("[{}; {}]", self.ty_kind_suggestion(param_env, ty)?, len)
5083 } else {
5084 "/* value */".to_string()
5085 }
5086 }
5087 ty::Tuple(tys) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0}{1})",
tys.iter().map(|ty|
self.ty_kind_suggestion(param_env,
ty)).collect::<Option<Vec<String>>>()?.join(", "),
if tys.len() == 1 { "," } else { "" }))
})format!(
5088 "({}{})",
5089 tys.iter()
5090 .map(|ty| self.ty_kind_suggestion(param_env, ty))
5091 .collect::<Option<Vec<String>>>()?
5092 .join(", "),
5093 if tys.len() == 1 { "," } else { "" }
5094 ),
5095 _ => "/* value */".to_string(),
5096 })
5097 }
5098
5099 pub(super) fn suggest_add_result_as_return_type(
5103 &self,
5104 obligation: &PredicateObligation<'tcx>,
5105 err: &mut Diag<'_>,
5106 trait_pred: ty::PolyTraitPredicate<'tcx>,
5107 ) {
5108 if ObligationCauseCode::QuestionMark != *obligation.cause.code().peel_derives() {
5109 return;
5110 }
5111
5112 fn choose_suggest_items<'tcx, 'hir>(
5119 tcx: TyCtxt<'tcx>,
5120 node: hir::Node<'hir>,
5121 ) -> Option<(&'hir hir::FnDecl<'hir>, hir::BodyId)> {
5122 match node {
5123 hir::Node::Item(item)
5124 if let hir::ItemKind::Fn { sig, body: body_id, .. } = item.kind =>
5125 {
5126 Some((sig.decl, body_id))
5127 }
5128 hir::Node::ImplItem(item)
5129 if let hir::ImplItemKind::Fn(sig, body_id) = item.kind =>
5130 {
5131 let parent = tcx.parent_hir_node(item.hir_id());
5132 if let hir::Node::Item(item) = parent
5133 && let hir::ItemKind::Impl(imp) = item.kind
5134 && imp.of_trait.is_none()
5135 {
5136 return Some((sig.decl, body_id));
5137 }
5138 None
5139 }
5140 _ => None,
5141 }
5142 }
5143
5144 let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id);
5145 if let Some((fn_decl, body_id)) = choose_suggest_items(self.tcx, node)
5146 && let hir::FnRetTy::DefaultReturn(ret_span) = fn_decl.output
5147 && self.tcx.is_diagnostic_item(sym::FromResidual, trait_pred.def_id())
5148 && trait_pred.skip_binder().trait_ref.args.type_at(0).is_unit()
5149 && let ty::Adt(def, _) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind()
5150 && self.tcx.is_diagnostic_item(sym::Result, def.did())
5151 {
5152 let mut sugg_spans =
5153 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ret_span,
" -> Result<(), Box<dyn std::error::Error>>".to_string())]))vec![(ret_span, " -> Result<(), Box<dyn std::error::Error>>".to_string())];
5154 let body = self.tcx.hir_body(body_id);
5155 if let hir::ExprKind::Block(b, _) = body.value.kind
5156 && b.expr.is_none()
5157 {
5158 let span = self.tcx.sess.source_map().end_point(b.span);
5160 sugg_spans.push((
5161 span.shrink_to_lo(),
5162 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", " Ok(())\n",
self.tcx.sess.source_map().indentation_before(span).unwrap_or_default()))
})format!(
5163 "{}{}",
5164 " Ok(())\n",
5165 self.tcx.sess.source_map().indentation_before(span).unwrap_or_default(),
5166 ),
5167 ));
5168 }
5169 err.multipart_suggestion(
5170 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider adding return type"))
})format!("consider adding return type"),
5171 sugg_spans,
5172 Applicability::MaybeIncorrect,
5173 );
5174 }
5175 }
5176
5177 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("suggest_unsized_bound_if_applicable",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5177u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
obligation.predicate.kind().skip_binder() else { return; };
let (ObligationCauseCode::WhereClause(item_def_id, span) |
ObligationCauseCode::WhereClauseInExpr(item_def_id, span,
..)) =
*obligation.cause.code().peel_derives() else { return; };
if span.is_dummy() { return; }
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5197",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5197u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["pred",
"item_def_id", "span"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&pred) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&item_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&span) as
&dyn Value))])
});
} else { ; }
};
let (Some(node), true) =
(self.tcx.hir_get_if_local(item_def_id),
self.tcx.is_lang_item(pred.def_id(),
LangItem::Sized)) else { return; };
let Some(generics) = node.generics() else { return; };
let sized_trait = self.tcx.lang_items().sized_trait();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5210",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5210u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["generics.params"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&generics.params)
as &dyn Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5211",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5211u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["generics.predicates"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&generics.predicates)
as &dyn Value))])
});
} else { ; }
};
let Some(param) =
generics.params.iter().find(|param|
param.span == span) else { return; };
let explicitly_sized =
generics.bounds_for_param(param.def_id).flat_map(|bp|
bp.bounds).any(|bound|
bound.trait_ref().and_then(|tr| tr.trait_def_id()) ==
sized_trait);
if explicitly_sized { return; }
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5224",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5224u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["param"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(¶m) as
&dyn Value))])
});
} else { ; }
};
match node {
hir::Node::Item(item @ hir::Item {
kind: hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) |
hir::ItemKind::Union(..), .. }) => {
if self.suggest_indirection_for_unsized(err, item, param) {
return;
}
}
_ => {}
};
let (span, separator, open_paren_sp) =
if let Some((s, open_paren_sp)) =
generics.bounds_span_for_suggestions(param.def_id) {
(s, " +", open_paren_sp)
} else {
(param.name.ident().span.shrink_to_hi(), ":", None)
};
let mut suggs = ::alloc::vec::Vec::new();
let suggestion =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ?Sized", separator))
});
if let Some(open_paren_sp) = open_paren_sp {
suggs.push((open_paren_sp, "(".to_string()));
suggs.push((span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("){0}", suggestion))
})));
} else { suggs.push((span, suggestion)); }
err.multipart_suggestion("consider relaxing the implicit `Sized` restriction",
suggs, Applicability::MachineApplicable);
}
}
}#[instrument(level = "debug", skip_all)]
5178 pub(super) fn suggest_unsized_bound_if_applicable(
5179 &self,
5180 err: &mut Diag<'_>,
5181 obligation: &PredicateObligation<'tcx>,
5182 ) {
5183 let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) =
5184 obligation.predicate.kind().skip_binder()
5185 else {
5186 return;
5187 };
5188 let (ObligationCauseCode::WhereClause(item_def_id, span)
5189 | ObligationCauseCode::WhereClauseInExpr(item_def_id, span, ..)) =
5190 *obligation.cause.code().peel_derives()
5191 else {
5192 return;
5193 };
5194 if span.is_dummy() {
5195 return;
5196 }
5197 debug!(?pred, ?item_def_id, ?span);
5198
5199 let (Some(node), true) = (
5200 self.tcx.hir_get_if_local(item_def_id),
5201 self.tcx.is_lang_item(pred.def_id(), LangItem::Sized),
5202 ) else {
5203 return;
5204 };
5205
5206 let Some(generics) = node.generics() else {
5207 return;
5208 };
5209 let sized_trait = self.tcx.lang_items().sized_trait();
5210 debug!(?generics.params);
5211 debug!(?generics.predicates);
5212 let Some(param) = generics.params.iter().find(|param| param.span == span) else {
5213 return;
5214 };
5215 let explicitly_sized = generics
5218 .bounds_for_param(param.def_id)
5219 .flat_map(|bp| bp.bounds)
5220 .any(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) == sized_trait);
5221 if explicitly_sized {
5222 return;
5223 }
5224 debug!(?param);
5225 match node {
5226 hir::Node::Item(
5227 item @ hir::Item {
5228 kind:
5230 hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
5231 ..
5232 },
5233 ) => {
5234 if self.suggest_indirection_for_unsized(err, item, param) {
5235 return;
5236 }
5237 }
5238 _ => {}
5239 };
5240
5241 let (span, separator, open_paren_sp) =
5243 if let Some((s, open_paren_sp)) = generics.bounds_span_for_suggestions(param.def_id) {
5244 (s, " +", open_paren_sp)
5245 } else {
5246 (param.name.ident().span.shrink_to_hi(), ":", None)
5247 };
5248
5249 let mut suggs = vec![];
5250 let suggestion = format!("{separator} ?Sized");
5251
5252 if let Some(open_paren_sp) = open_paren_sp {
5253 suggs.push((open_paren_sp, "(".to_string()));
5254 suggs.push((span, format!("){suggestion}")));
5255 } else {
5256 suggs.push((span, suggestion));
5257 }
5258
5259 err.multipart_suggestion(
5260 "consider relaxing the implicit `Sized` restriction",
5261 suggs,
5262 Applicability::MachineApplicable,
5263 );
5264 }
5265
5266 fn suggest_indirection_for_unsized(
5267 &self,
5268 err: &mut Diag<'_>,
5269 item: &hir::Item<'tcx>,
5270 param: &hir::GenericParam<'tcx>,
5271 ) -> bool {
5272 let mut visitor = FindTypeParam { param: param.name.ident().name, .. };
5276 visitor.visit_item(item);
5277 if visitor.invalid_spans.is_empty() {
5278 return false;
5279 }
5280 let mut multispan: MultiSpan = param.span.into();
5281 multispan.push_span_label(
5282 param.span,
5283 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this could be changed to `{0}: ?Sized`...",
param.name.ident()))
})format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
5284 );
5285 for sp in visitor.invalid_spans {
5286 multispan.push_span_label(
5287 sp,
5288 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...if indirection were used here: `Box<{0}>`",
param.name.ident()))
})format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
5289 );
5290 }
5291 err.span_help(
5292 multispan,
5293 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you could relax the implicit `Sized` bound on `{0}` if it were used through indirection like `&{0}` or `Box<{0}>`",
param.name.ident()))
})format!(
5294 "you could relax the implicit `Sized` bound on `{T}` if it were \
5295 used through indirection like `&{T}` or `Box<{T}>`",
5296 T = param.name.ident(),
5297 ),
5298 );
5299 true
5300 }
5301 pub(crate) fn suggest_swapping_lhs_and_rhs<T>(
5302 &self,
5303 err: &mut Diag<'_>,
5304 predicate: T,
5305 param_env: ty::ParamEnv<'tcx>,
5306 cause_code: &ObligationCauseCode<'tcx>,
5307 ) where
5308 T: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
5309 {
5310 let tcx = self.tcx;
5311 let predicate = predicate.upcast(tcx);
5312 match *cause_code {
5313 ObligationCauseCode::BinOp { lhs_hir_id, rhs_hir_id, rhs_span, .. }
5314 if let Some(typeck_results) = &self.typeck_results
5315 && let hir::Node::Expr(lhs) = tcx.hir_node(lhs_hir_id)
5316 && let hir::Node::Expr(rhs) = tcx.hir_node(rhs_hir_id)
5317 && let Some(lhs_ty) = typeck_results.expr_ty_opt(lhs)
5318 && let Some(rhs_ty) = typeck_results.expr_ty_opt(rhs) =>
5319 {
5320 if let Some(pred) = predicate.as_trait_clause()
5321 && tcx.is_lang_item(pred.def_id(), LangItem::PartialEq)
5322 && self
5323 .infcx
5324 .type_implements_trait(pred.def_id(), [rhs_ty, lhs_ty], param_env)
5325 .must_apply_modulo_regions()
5326 {
5327 let lhs_span = tcx.hir_span(lhs_hir_id);
5328 let sm = tcx.sess.source_map();
5329 if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_span)
5330 && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_span)
5331 {
5332 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `PartialEq<{1}>`",
rhs_ty, lhs_ty))
})format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
5333 err.multipart_suggestion(
5334 "consider swapping the equality",
5335 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(lhs_span, rhs_snippet), (rhs_span, lhs_snippet)]))vec![(lhs_span, rhs_snippet), (rhs_span, lhs_snippet)],
5336 Applicability::MaybeIncorrect,
5337 );
5338 }
5339 }
5340 }
5341 _ => {}
5342 }
5343 }
5344}
5345
5346fn hint_missing_borrow<'tcx>(
5348 infcx: &InferCtxt<'tcx>,
5349 param_env: ty::ParamEnv<'tcx>,
5350 span: Span,
5351 found: Ty<'tcx>,
5352 expected: Ty<'tcx>,
5353 found_node: Node<'_>,
5354 err: &mut Diag<'_>,
5355) {
5356 if #[allow(non_exhaustive_omitted_patterns)] match found_node {
Node::TraitItem(..) => true,
_ => false,
}matches!(found_node, Node::TraitItem(..)) {
5357 return;
5358 }
5359
5360 let found_args = match found.kind() {
5361 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
5362 kind => {
5363 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("found was converted to a FnPtr above but is now {0:?}",
kind))span_bug!(span, "found was converted to a FnPtr above but is now {:?}", kind)
5364 }
5365 };
5366 let expected_args = match expected.kind() {
5367 ty::FnPtr(sig_tys, _) => infcx.enter_forall(*sig_tys, |sig_tys| sig_tys.inputs().iter()),
5368 kind => {
5369 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("expected was converted to a FnPtr above but is now {0:?}",
kind))span_bug!(span, "expected was converted to a FnPtr above but is now {:?}", kind)
5370 }
5371 };
5372
5373 let Some(fn_decl) = found_node.fn_decl() else {
5375 return;
5376 };
5377
5378 let args = fn_decl.inputs.iter();
5379
5380 let mut to_borrow = Vec::new();
5381 let mut remove_borrow = Vec::new();
5382
5383 for ((found_arg, expected_arg), arg) in found_args.zip(expected_args).zip(args) {
5384 let (found_ty, found_refs) = get_deref_type_and_refs(*found_arg);
5385 let (expected_ty, expected_refs) = get_deref_type_and_refs(*expected_arg);
5386
5387 if infcx.can_eq(param_env, found_ty, expected_ty) {
5388 if found_refs.len() < expected_refs.len()
5390 && found_refs[..] == expected_refs[expected_refs.len() - found_refs.len()..]
5391 {
5392 to_borrow.push((
5393 arg.span.shrink_to_lo(),
5394 expected_refs[..expected_refs.len() - found_refs.len()]
5395 .iter()
5396 .map(|mutbl| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", mutbl.prefix_str()))
})format!("&{}", mutbl.prefix_str()))
5397 .collect::<Vec<_>>()
5398 .join(""),
5399 ));
5400 } else if found_refs.len() > expected_refs.len() {
5401 let mut span = arg.span.shrink_to_lo();
5402 let mut left = found_refs.len() - expected_refs.len();
5403 let mut ty = arg;
5404 while let hir::TyKind::Ref(_, mut_ty) = &ty.kind
5405 && left > 0
5406 {
5407 span = span.with_hi(mut_ty.ty.span.lo());
5408 ty = mut_ty.ty;
5409 left -= 1;
5410 }
5411 if left == 0 {
5412 remove_borrow.push((span, String::new()));
5413 }
5414 }
5415 }
5416 }
5417
5418 if !to_borrow.is_empty() {
5419 err.subdiagnostic(errors::AdjustSignatureBorrow::Borrow { to_borrow });
5420 }
5421
5422 if !remove_borrow.is_empty() {
5423 err.subdiagnostic(errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
5424 }
5425}
5426
5427#[derive(#[automatically_derived]
impl<'v> ::core::fmt::Debug for SelfVisitor<'v> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "SelfVisitor",
"paths", &self.paths, "name", &&self.name)
}
}Debug)]
5430pub struct SelfVisitor<'v> {
5431 pub paths: Vec<&'v hir::Ty<'v>> = Vec::new(),
5432 pub name: Option<Symbol>,
5433}
5434
5435impl<'v> Visitor<'v> for SelfVisitor<'v> {
5436 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
5437 if let hir::TyKind::Path(path) = ty.kind
5438 && let hir::QPath::TypeRelative(inner_ty, segment) = path
5439 && (Some(segment.ident.name) == self.name || self.name.is_none())
5440 && let hir::TyKind::Path(inner_path) = inner_ty.kind
5441 && let hir::QPath::Resolved(None, inner_path) = inner_path
5442 && let Res::SelfTyAlias { .. } = inner_path.res
5443 {
5444 self.paths.push(ty.as_unambig_ty());
5445 }
5446 hir::intravisit::walk_ty(self, ty);
5447 }
5448}
5449
5450#[derive(#[automatically_derived]
impl<'v> ::core::default::Default for ReturnsVisitor<'v> {
#[inline]
fn default() -> ReturnsVisitor<'v> {
ReturnsVisitor {
returns: ::core::default::Default::default(),
in_block_tail: ::core::default::Default::default(),
}
}
}Default)]
5453pub struct ReturnsVisitor<'v> {
5454 pub returns: Vec<&'v hir::Expr<'v>>,
5455 in_block_tail: bool,
5456}
5457
5458impl<'v> Visitor<'v> for ReturnsVisitor<'v> {
5459 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5460 match ex.kind {
5465 hir::ExprKind::Ret(Some(ex)) => {
5466 self.returns.push(ex);
5467 }
5468 hir::ExprKind::Block(block, _) if self.in_block_tail => {
5469 self.in_block_tail = false;
5470 for stmt in block.stmts {
5471 hir::intravisit::walk_stmt(self, stmt);
5472 }
5473 self.in_block_tail = true;
5474 if let Some(expr) = block.expr {
5475 self.visit_expr(expr);
5476 }
5477 }
5478 hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {
5479 self.visit_expr(then);
5480 if let Some(el) = else_opt {
5481 self.visit_expr(el);
5482 }
5483 }
5484 hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {
5485 for arm in arms {
5486 self.visit_expr(arm.body);
5487 }
5488 }
5489 _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),
5491 _ => self.returns.push(ex),
5492 }
5493 }
5494
5495 fn visit_body(&mut self, body: &hir::Body<'v>) {
5496 if !!self.in_block_tail {
::core::panicking::panic("assertion failed: !self.in_block_tail")
};assert!(!self.in_block_tail);
5497 self.in_block_tail = true;
5498 hir::intravisit::walk_body(self, body);
5499 }
5500}
5501
5502#[derive(#[automatically_derived]
impl ::core::default::Default for AwaitsVisitor {
#[inline]
fn default() -> AwaitsVisitor {
AwaitsVisitor { awaits: ::core::default::Default::default() }
}
}Default)]
5504struct AwaitsVisitor {
5505 awaits: Vec<HirId>,
5506}
5507
5508impl<'v> Visitor<'v> for AwaitsVisitor {
5509 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
5510 if let hir::ExprKind::Yield(_, hir::YieldSource::Await { expr: Some(id) }) = ex.kind {
5511 self.awaits.push(id)
5512 }
5513 hir::intravisit::walk_expr(self, ex)
5514 }
5515}
5516
5517pub trait NextTypeParamName {
5521 fn next_type_param_name(&self, name: Option<&str>) -> String;
5522}
5523
5524impl NextTypeParamName for &[hir::GenericParam<'_>] {
5525 fn next_type_param_name(&self, name: Option<&str>) -> String {
5526 let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
5528 let name = name.as_deref();
5529
5530 let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
5532
5533 let used_names: Vec<Symbol> = self
5535 .iter()
5536 .filter_map(|param| match param.name {
5537 hir::ParamName::Plain(ident) => Some(ident.name),
5538 _ => None,
5539 })
5540 .collect();
5541
5542 possible_names
5544 .iter()
5545 .find(|n| !used_names.contains(&Symbol::intern(n)))
5546 .unwrap_or(&"ParamName")
5547 .to_string()
5548 }
5549}
5550
5551struct ReplaceImplTraitVisitor<'a> {
5553 ty_spans: &'a mut Vec<Span>,
5554 param_did: DefId,
5555}
5556
5557impl<'a, 'hir> hir::intravisit::Visitor<'hir> for ReplaceImplTraitVisitor<'a> {
5558 fn visit_ty(&mut self, t: &'hir hir::Ty<'hir, AmbigArg>) {
5559 if let hir::TyKind::Path(hir::QPath::Resolved(
5560 None,
5561 hir::Path { res: Res::Def(_, segment_did), .. },
5562 )) = t.kind
5563 {
5564 if self.param_did == *segment_did {
5565 self.ty_spans.push(t.span);
5570 return;
5571 }
5572 }
5573
5574 hir::intravisit::walk_ty(self, t);
5575 }
5576}
5577
5578pub(super) fn get_explanation_based_on_obligation<'tcx>(
5579 tcx: TyCtxt<'tcx>,
5580 obligation: &PredicateObligation<'tcx>,
5581 trait_predicate: ty::PolyTraitPredicate<'tcx>,
5582 pre_message: String,
5583 long_ty_path: &mut Option<PathBuf>,
5584) -> String {
5585 if let ObligationCauseCode::MainFunctionType = obligation.cause.code() {
5586 "consider using `()`, or a `Result`".to_owned()
5587 } else {
5588 let ty_desc = match trait_predicate.self_ty().skip_binder().kind() {
5589 ty::FnDef(_, _) => Some("fn item"),
5590 ty::Closure(_, _) => Some("closure"),
5591 _ => None,
5592 };
5593
5594 let desc = match ty_desc {
5595 Some(desc) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", desc))
})format!(" {desc}"),
5596 None => String::new(),
5597 };
5598 if let ty::PredicatePolarity::Positive = trait_predicate.polarity() {
5599 let mention_unstable = !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
5604 && try { tcx.lookup_stability(trait_predicate.def_id())?.level.is_stable() }
5605 == Some(false);
5606 let unstable = if mention_unstable { "nightly-only, unstable " } else { "" };
5607
5608 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2}the {3}trait `{0}` is not implemented for{4} `{1}`",
trait_predicate.print_modifiers_and_trait_path(),
tcx.short_string(trait_predicate.self_ty().skip_binder(),
long_ty_path), pre_message, unstable, desc))
})format!(
5609 "{pre_message}the {unstable}trait `{}` is not implemented for{desc} `{}`",
5610 trait_predicate.print_modifiers_and_trait_path(),
5611 tcx.short_string(trait_predicate.self_ty().skip_binder(), long_ty_path),
5612 )
5613 } else {
5614 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}the trait bound `{1}` is not satisfied",
pre_message, trait_predicate))
})format!("{pre_message}the trait bound `{trait_predicate}` is not satisfied")
5618 }
5619 }
5620}
5621
5622struct ReplaceImplTraitFolder<'tcx> {
5624 tcx: TyCtxt<'tcx>,
5625 param: &'tcx ty::GenericParamDef,
5626 replace_ty: Ty<'tcx>,
5627}
5628
5629impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceImplTraitFolder<'tcx> {
5630 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
5631 if let ty::Param(ty::ParamTy { index, .. }) = t.kind() {
5632 if self.param.index == *index {
5633 return self.replace_ty;
5634 }
5635 }
5636 t.super_fold_with(self)
5637 }
5638
5639 fn cx(&self) -> TyCtxt<'tcx> {
5640 self.tcx
5641 }
5642}
5643
5644pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
5645 tcx: TyCtxt<'tcx>,
5646 sig: hir::FnSig<'tcx>,
5647 body: hir::TraitFn<'tcx>,
5648 opaque_def_id: LocalDefId,
5649 add_bounds: &str,
5650) -> Option<Vec<(Span, String)>> {
5651 let hir::IsAsync::Async(async_span) = sig.header.asyncness else {
5652 return None;
5653 };
5654 let async_span = tcx.sess.source_map().span_extend_while_whitespace(async_span);
5655
5656 let future = tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
5657 let [hir::GenericBound::Trait(trait_ref)] = future.bounds else {
5658 return None;
5660 };
5661 let Some(hir::PathSegment { args: Some(args), .. }) = trait_ref.trait_ref.path.segments.last()
5662 else {
5663 return None;
5665 };
5666 let Some(future_output_ty) = args.constraints.first().and_then(|constraint| constraint.ty())
5667 else {
5668 return None;
5670 };
5671
5672 let mut sugg = if future_output_ty.span.is_empty() {
5673 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(async_span, String::new()),
(future_output_ty.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" -> impl std::future::Future<Output = ()>{0}",
add_bounds))
}))]))vec![
5674 (async_span, String::new()),
5675 (
5676 future_output_ty.span,
5677 format!(" -> impl std::future::Future<Output = ()>{add_bounds}"),
5678 ),
5679 ]
5680 } else {
5681 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(future_output_ty.span.shrink_to_lo(),
"impl std::future::Future<Output = ".to_owned()),
(future_output_ty.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(">{0}", add_bounds))
})), (async_span, String::new())]))vec![
5682 (future_output_ty.span.shrink_to_lo(), "impl std::future::Future<Output = ".to_owned()),
5683 (future_output_ty.span.shrink_to_hi(), format!(">{add_bounds}")),
5684 (async_span, String::new()),
5685 ]
5686 };
5687
5688 if let hir::TraitFn::Provided(body) = body {
5690 let body = tcx.hir_body(body);
5691 let body_span = body.value.span;
5692 let body_span_without_braces =
5693 body_span.with_lo(body_span.lo() + BytePos(1)).with_hi(body_span.hi() - BytePos(1));
5694 if body_span_without_braces.is_empty() {
5695 sugg.push((body_span_without_braces, " async {} ".to_owned()));
5696 } else {
5697 sugg.extend([
5698 (body_span_without_braces.shrink_to_lo(), "async {".to_owned()),
5699 (body_span_without_braces.shrink_to_hi(), "} ".to_owned()),
5700 ]);
5701 }
5702 }
5703
5704 Some(sugg)
5705}
5706
5707fn point_at_assoc_type_restriction<G: EmissionGuarantee>(
5710 tcx: TyCtxt<'_>,
5711 err: &mut Diag<'_, G>,
5712 self_ty_str: &str,
5713 trait_name: &str,
5714 predicate: ty::Predicate<'_>,
5715 generics: &hir::Generics<'_>,
5716 data: &ImplDerivedCause<'_>,
5717) {
5718 let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() else {
5719 return;
5720 };
5721 let ty::ClauseKind::Projection(proj) = clause else {
5722 return;
5723 };
5724 let name = tcx.item_name(proj.projection_term.def_id);
5725 let mut predicates = generics.predicates.iter().peekable();
5726 let mut prev: Option<(&hir::WhereBoundPredicate<'_>, Span)> = None;
5727 while let Some(pred) = predicates.next() {
5728 let curr_span = pred.span;
5729 let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind else {
5730 continue;
5731 };
5732 let mut bounds = pred.bounds.iter();
5733 while let Some(bound) = bounds.next() {
5734 let Some(trait_ref) = bound.trait_ref() else {
5735 continue;
5736 };
5737 if bound.span() != data.span {
5738 continue;
5739 }
5740 if let hir::TyKind::Path(path) = pred.bounded_ty.kind
5741 && let hir::QPath::TypeRelative(ty, segment) = path
5742 && segment.ident.name == name
5743 && let hir::TyKind::Path(inner_path) = ty.kind
5744 && let hir::QPath::Resolved(None, inner_path) = inner_path
5745 && let Res::SelfTyAlias { .. } = inner_path.res
5746 {
5747 let span = if pred.origin == hir::PredicateOrigin::WhereClause
5750 && generics
5751 .predicates
5752 .iter()
5753 .filter(|p| {
5754 #[allow(non_exhaustive_omitted_patterns)] match p.kind {
hir::WherePredicateKind::BoundPredicate(p) if
hir::PredicateOrigin::WhereClause == p.origin => true,
_ => false,
}matches!(
5755 p.kind,
5756 hir::WherePredicateKind::BoundPredicate(p)
5757 if hir::PredicateOrigin::WhereClause == p.origin
5758 )
5759 })
5760 .count()
5761 == 1
5762 {
5763 generics.where_clause_span
5766 } else if let Some(next_pred) = predicates.peek()
5767 && let hir::WherePredicateKind::BoundPredicate(next) = next_pred.kind
5768 && pred.origin == next.origin
5769 {
5770 curr_span.until(next_pred.span)
5772 } else if let Some((prev, prev_span)) = prev
5773 && pred.origin == prev.origin
5774 {
5775 prev_span.shrink_to_hi().to(curr_span)
5777 } else if pred.origin == hir::PredicateOrigin::WhereClause {
5778 curr_span.with_hi(generics.where_clause_span.hi())
5779 } else {
5780 curr_span
5781 };
5782
5783 err.span_suggestion_verbose(
5784 span,
5785 "associated type for the current `impl` cannot be restricted in `where` \
5786 clauses, remove this bound",
5787 "",
5788 Applicability::MaybeIncorrect,
5789 );
5790 }
5791 if let Some(new) =
5792 tcx.associated_items(data.impl_or_alias_def_id).find_by_ident_and_kind(
5793 tcx,
5794 Ident::with_dummy_span(name),
5795 ty::AssocTag::Type,
5796 data.impl_or_alias_def_id,
5797 )
5798 {
5799 let span = tcx.def_span(new.def_id);
5802 err.span_label(
5803 span,
5804 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("associated type `<{0} as {1}>::{2}` is specified here",
self_ty_str, trait_name, name))
})format!(
5805 "associated type `<{self_ty_str} as {trait_name}>::{name}` is specified \
5806 here",
5807 ),
5808 );
5809 let mut visitor = SelfVisitor { name: Some(name), .. };
5812 visitor.visit_trait_ref(trait_ref);
5813 for path in visitor.paths {
5814 err.span_suggestion_verbose(
5815 path.span,
5816 "replace the associated type with the type specified in this `impl`",
5817 tcx.type_of(new.def_id).skip_binder(),
5818 Applicability::MachineApplicable,
5819 );
5820 }
5821 } else {
5822 let mut visitor = SelfVisitor { name: None, .. };
5823 visitor.visit_trait_ref(trait_ref);
5824 let span: MultiSpan =
5825 visitor.paths.iter().map(|p| p.span).collect::<Vec<Span>>().into();
5826 err.span_note(
5827 span,
5828 "associated types for the current `impl` cannot be restricted in `where` \
5829 clauses",
5830 );
5831 }
5832 }
5833 prev = Some((pred, curr_span));
5834 }
5835}
5836
5837fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec<hir::Mutability>) {
5838 let mut refs = ::alloc::vec::Vec::new()vec![];
5839
5840 while let ty::Ref(_, new_ty, mutbl) = ty.kind() {
5841 ty = *new_ty;
5842 refs.push(*mutbl);
5843 }
5844
5845 (ty, refs)
5846}
5847
5848struct FindTypeParam {
5851 param: rustc_span::Symbol,
5852 invalid_spans: Vec<Span> = Vec::new(),
5853 nested: bool = false,
5854}
5855
5856impl<'v> Visitor<'v> for FindTypeParam {
5857 fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
5858 }
5860
5861 fn visit_ty(&mut self, ty: &hir::Ty<'_, AmbigArg>) {
5862 match ty.kind {
5869 hir::TyKind::Ptr(_) | hir::TyKind::Ref(..) | hir::TyKind::TraitObject(..) => {}
5870 hir::TyKind::Path(hir::QPath::Resolved(None, path))
5871 if let [segment] = path.segments
5872 && segment.ident.name == self.param =>
5873 {
5874 if !self.nested {
5875 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs:5875",
"rustc_trait_selection::error_reporting::traits::suggestions",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs"),
::tracing_core::__macro_support::Option::Some(5875u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::suggestions"),
::tracing_core::field::FieldSet::new(&["message", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("FindTypeParam::visit_ty")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty) as
&dyn Value))])
});
} else { ; }
};debug!(?ty, "FindTypeParam::visit_ty");
5876 self.invalid_spans.push(ty.span);
5877 }
5878 }
5879 hir::TyKind::Path(_) => {
5880 let prev = self.nested;
5881 self.nested = true;
5882 hir::intravisit::walk_ty(self, ty);
5883 self.nested = prev;
5884 }
5885 _ => {
5886 hir::intravisit::walk_ty(self, ty);
5887 }
5888 }
5889 }
5890}
5891
5892struct ParamFinder {
5895 params: Vec<Symbol> = Vec::new(),
5896}
5897
5898impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParamFinder {
5899 fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
5900 match t.kind() {
5901 ty::Param(p) => self.params.push(p.name),
5902 _ => {}
5903 }
5904 t.super_visit_with(self)
5905 }
5906}
5907
5908impl ParamFinder {
5909 fn can_suggest_bound(&self, generics: &hir::Generics<'_>) -> bool {
5912 if self.params.is_empty() {
5913 return true;
5916 }
5917 generics.params.iter().any(|p| match p.name {
5918 hir::ParamName::Plain(p_name) => {
5919 self.params.iter().any(|p| *p == p_name.name || *p == kw::SelfUpper)
5921 }
5922 _ => true,
5923 })
5924 }
5925}